🪢 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
feat(prompts): prompt chat message placeholders in backend and api (#7388)
Nimarbd36669c6aee
diff --git a/CLAUDE.md b/CLAUDE.mdindex 15d0a06142..5e1f2017f1 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -182,4 +182,7 @@ To get a project, use the `get_project` capability with the full project name as## Front-end Tips### Window Location Handling-- Whenever you want to use or do use window.location..., ensure that you also add proper handling for a custom basePath\ No newline at end of file+- Whenever you want to use or do use window.location..., ensure that you also add proper handling for a custom basePath++## TypeScript Best Practices+- In TypeScript, if possible, don't use the `any` typediff --git a/fern/apis/server/definition/prompts.yml b/fern/apis/server/definition/prompts.ymlindex 9d736acca9..c8bb1e2dad 100644--- a/fern/apis/server/definition/prompts.yml+++ b/fern/apis/server/definition/prompts.yml@@ -82,7 +82,7 @@ types:CreateChatPromptRequest:properties:name: string- prompt: list<ChatMessage>+ prompt: list<ChatMessageWithPlaceholders>config: optional<unknown>labels:type: optional<list<string>>@@ -132,6 +132,11 @@ types:type: optional<map<string, unknown>>docs: The dependency resolution graph for the current prompt. Null if prompt has no dependencies.+ ChatMessageWithPlaceholders:+ union:+ chatmessage: ChatMessage+ placeholder: PlaceholderMessage+ChatMessage:properties:role:@@ -139,6 +144,11 @@ types:content:type: string+ PlaceholderMessage:+ properties:+ name:+ type: string+TextPrompt:extends: BasePromptproperties:@@ -147,4 +157,4 @@ types:ChatPrompt:extends: BasePromptproperties:- prompt: list<ChatMessage>+ prompt: list<ChatMessageWithPlaceholders>diff --git a/packages/shared/scripts/seeder/seed-postgres.ts b/packages/shared/scripts/seeder/seed-postgres.tsindex e69eb95015..504575dc40 100644--- a/packages/shared/scripts/seeder/seed-postgres.ts+++ b/packages/shared/scripts/seeder/seed-postgres.ts@@ -1,18 +1,18 @@-import {- PrismaClient,- type Project,- ScoreDataType,- JobConfiguration,- JobExecutionStatus,-} from "../../src/index";-import { hash } from "bcryptjs";+import { randomUUID } from "node:crypto";import { parseArgs } from "node:util";+import { hash } from "bcryptjs";import { v4 } from "uuid";-import { getDisplaySecretKey, hashSecretKey, logger } from "../../src/server";import { encrypt } from "../../src/encryption";-import { redis } from "../../src/server/redis/redis";-import { randomUUID } from "crypto";import {+ type JobConfiguration,+ JobExecutionStatus,+ PrismaClient,+ type Project,+ ScoreDataType,+} from "../../src/index";+import { getDisplaySecretKey, hashSecretKey, logger } from "../../src/server";+import { redis } from "../../src/server/redis/redis";+import {EVAL_TRACE_COUNT,FAILED_EVAL_TRACE_INTERVAL,SEED_CHAT_ML_PROMPTS,SEED_DATASETS,@@ -27,7 +27,6 @@ import {generateEvalScoreId,generateEvalTraceId,} from "./utils/seed-helpers";-import { EVAL_TRACE_COUNT } from "./utils/postgres-seed-constants";type ConfigCategory = {label: string;diff --git a/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts b/packages/shared/scripts/seeder/utils/postgres-seed-constants.tsindex 8aee4e115d..7f39d78de5 100644--- a/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts+++ b/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts@@ -307,6 +307,34 @@ export const SEED_CHAT_ML_PROMPTS = [labels: ["production", "latest"],tags: ["tag1", "tag2"],},+ {+ id: `prompt-chat-placeholder`,+ createdBy: "user-1",+ prompt: [+ {+ role: "system",+ content:+ 'You are a very enthusiastic Langfuse representative who loves to help people! Langfuse is an open-source observability tool for developers of applications that use Large Language Models (LLMs). Given the following sections from the Langfuse documentation, answer the question using only that information, outputted in markdown format.\n\nPlease follow these guidelines:\n- Refer to the respective links of the documentation and select quality examples\n- Be kind.\n- Include emojis where it makes sense.\n- If the users have problems using Langfuse, tell them to reach out to the founders directly via the chat widget or GitHub at the end of your answer.\n- Answer as markdown, use highlights and paragraphs to structure the text.\n- Do not mention that you are "enthusiastic", the user does not need to know, will feel it from the style of your answers.\n- Only use information that is available in the context, do not make up any code that is not in the context.\n- Always put an empji at the end of the message.',+ },+ {+ type: "placeholder",+ name: "message_history",+ },+ {+ role: "assistant",+ content:+ "Answering in next message based on your instructions only. What is the question?",+ },+ {+ role: "user",+ content: "{{question}}",+ },+ ],+ name: "prompt-chat-ml-with-placeholder",+ version: 1,+ labels: ["production", "latest"],+ tags: ["tag1", "tag2"],+ },];export const SEED_PROMPT_VERSIONS = [diff --git a/packages/shared/src/features/prompts/types.ts b/packages/shared/src/features/prompts/types.tsindex 5d154e42e5..45fedc022a 100644--- a/packages/shared/src/features/prompts/types.ts+++ b/packages/shared/src/features/prompts/types.ts@@ -1,13 +1,12 @@import { z } from "zod/v4";-import { Prompt } from "../../../prisma/generated/types";+import type { Prompt } from "../../../prisma/generated/types";import { jsonSchema } from "../../utils/zod";import { COMMIT_MESSAGE_MAX_LENGTH } from "./constants";+import { PromptChatMessageSchema } from "../../server/llm/types";import { PromptNameSchema } from "./validation";-export const SingleChatMessageSchema = z.object({- role: z.string(),- content: z.string(),-});+export const SingleChatMessageSchema = PromptChatMessageSchema;+export type SingleChatMessage = z.infer<typeof SingleChatMessageSchema>;export enum PromptType {// eslint-disable-next-line no-unused-vars@@ -44,7 +43,7 @@ const BaseCreateChatPromptSchema = z.object({name: PromptNameSchema,labels: z.array(PromptLabelSchema).default([]),type: z.literal(PromptType.Chat),- prompt: z.array(SingleChatMessageSchema),+ prompt: z.array(PromptChatMessageSchema),config: jsonSchema.nullable().default({}),tags: z.array(z.string()).nullish(),});@@ -137,7 +136,7 @@ export const BaseChatPromptSchema = z.object({tags: z.array(z.string()),labels: z.array(PromptLabelSchema),type: z.literal(PromptType.Chat),- prompt: z.array(SingleChatMessageSchema),+ prompt: z.array(PromptChatMessageSchema),config: jsonSchema,});diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 99081fd8f0..fd5318c5fe 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -45,6 +45,7 @@ export * from "./features/prompts/parsePromptDependencyTags";export * from "./features/prompts/validation";export * from "./features/prompts/types";export * from "./features/prompts/constants";+export * from "./server/llm/compileChatMessages";// export db types onlyexport * from "@prisma/client";diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex a6283a9d16..fc15597160 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -11,6 +11,7 @@ export * from "./auth/gitHubEnterpriseProvider";export * from "./llm/fetchLLMCompletion";export * from "./llm/utils";export * from "./llm/types";+export * from "./llm/compileChatMessages";export * from "./utils/DatabaseReadStream";export * from "./utils/transforms";export * from "./clickhouse/client";diff --git a/packages/shared/src/server/llm/compileChatMessages.ts b/packages/shared/src/server/llm/compileChatMessages.tsnew file mode 100644index 0000000000..1af76790e4--- /dev/null+++ b/packages/shared/src/server/llm/compileChatMessages.ts@@ -0,0 +1,116 @@+import { z } from "zod/v4";+import { v4 as uuidv4 } from "uuid";+import { type ChatMessage, type PlaceholderMessage, ChatMessageType, type PromptChatMessageSchema, type ChatMessageWithId, type ChatMessageWithIdNoPlaceholders, ChatMessageSchema } from "./types";++export type MessagePlaceholderValues = Record<string, ChatMessage[]>;+export type PromptMessage = z.infer<typeof PromptChatMessageSchema>;++export function isPlaceholder(message: PromptMessage): message is PlaceholderMessage {+ return "type" in message && message.type === ChatMessageType.Placeholder;+}++function validateMessage(message: unknown): message is ChatMessage {+ return ChatMessageSchema.safeParse(message).success;+}++function replaceTextVariables(+ content: string,+ textVariables: Record<string, string>+): string {+ let result = content;+ for (const [varName, varValue] of Object.entries(textVariables)) {+ // Create regex that handles optional whitespace around variable name+ const variablePattern = new RegExp(`{{\\s*${varName}\\s*}}`, "g");+ result = result.replace(variablePattern, varValue);+ }+ return result;+}++function expandPlaceholder(+ placeholder: PlaceholderMessage,+ placeholderValues: MessagePlaceholderValues+): ChatMessage[] {+ const replacementMessages = placeholderValues[placeholder.name];++ if (!replacementMessages) {+ throw new Error(`Missing value for message placeholder: ${placeholder.name}`);+ }++ if (!Array.isArray(replacementMessages)) {+ throw new Error(`Placeholder value for '${placeholder.name}' must be an array of messages`);+ }++ for (const replacementMsg of replacementMessages) {+ if (!validateMessage(replacementMsg)) {+ throw new Error(`Invalid message format in placeholder '${placeholder.name}': messages must have 'role' and 'content' properties`);+ }+ }+ return replacementMessages;+}++export function compileChatMessages(+ messages: PromptMessage[],+ placeholderValues: MessagePlaceholderValues,+ textVariables?: Record<string, string>+): ChatMessage[] {+ const expandedMessages = messages.flatMap((message) =>+ isPlaceholder(message)+ ? expandPlaceholder(message, placeholderValues)+ : [message as ChatMessage]+ );++ // substitute text variables+ if (!textVariables || Object.keys(textVariables).length === 0) {+ return expandedMessages;+ }++ return expandedMessages.map((message) => {+ if (!message.content) {+ return message;+ }++ return {+ ...message,+ content: replaceTextVariables(message.content, textVariables)+ };+ });+}++export function compileChatMessagesWithIds(+ messages: ChatMessageWithId[],+ placeholderValues: Record<string, ChatMessage[]>,+ textVariables?: Record<string, string>+): ChatMessageWithIdNoPlaceholders[] {+ // TODO: check, is it even important to retain the IDs?+ const expandedMessages = messages.flatMap((message) => {+ if (isPlaceholder(message)) {+ const expandedMsgs = expandPlaceholder(message, placeholderValues);+ return expandedMsgs.map(msg => ({ ...msg, id: uuidv4() }));+ } else {+ // Preserve message IDs for already non-placeholder messages+ return [message as ChatMessageWithIdNoPlaceholders];+ }+ });++ // substitute text variables+ if (!textVariables || Object.keys(textVariables).length === 0) {+ return expandedMessages;+ }++ return expandedMessages.map((message) => {+ if (!message.content) {+ return message;+ }++ return {+ ...message,+ content: replaceTextVariables(message.content, textVariables)+ };+ });+}++export function extractPlaceholderNames(messages: PromptMessage[]): string[] {+ return messages+ .filter((msg): msg is PlaceholderMessage => "type" in msg && msg.type === ChatMessageType.Placeholder)+ .map(msg => msg.name);+}diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.tsindex 5608434003..209494b7b3 100644--- a/packages/shared/src/server/llm/types.ts+++ b/packages/shared/src/server/llm/types.ts@@ -115,6 +115,8 @@ export enum ChatMessageRole {Tool = "tool",}+// Thought: should placeholder not semantically be part of this, because it can be+// PublicAPICreated of type? Works for now though.export enum ChatMessageType {System = "system",Developer = "developer",@@ -123,6 +125,7 @@ export enum ChatMessageType {AssistantToolCall = "assistant-tool-call",ToolResult = "tool-result",PublicAPICreated = "public-api-created",+ Placeholder = "placeholder",}export const SystemMessageSchema = z.object({@@ -171,6 +174,12 @@ export const ToolResultMessageSchema = z.object({});export type ToolResultMessage = z.infer<typeof ToolResultMessageSchema>;+export const PlaceholderMessageSchema = z.object({+ type: z.literal(ChatMessageType.Placeholder),+ name: z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/, "Placeholder name must start with a letter and contain only alphanumeric characters and underscores"),+});+export type PlaceholderMessage = z.infer<typeof PlaceholderMessageSchema>;+export const ChatMessageDefaultRoleSchema = z.enum(ChatMessageRole);export const ChatMessageSchema = z.union([SystemMessageSchema,@@ -193,12 +202,16 @@ export const ChatMessageSchema = z.union([]);export type ChatMessage = z.infer<typeof ChatMessageSchema>;-export type ChatMessageWithId = ChatMessage & { id: string };+export type ChatMessageWithId = (ChatMessage & { id: string }) | (PlaceholderMessage & { id: string });+export type ChatMessageWithIdNoPlaceholders = (ChatMessage & { id: string });-export const PromptChatMessageSchema = z.object({- role: z.string(),- content: z.string(),-});+export const PromptChatMessageSchema = z.union([+ z.object({+ role: z.string(),+ content: z.string(),+ }),+ PlaceholderMessageSchema,+]);export const PromptChatMessageListSchema = z.array(PromptChatMessageSchema);export type PromptVariable = { name: string; value: string; isUsed: boolean };diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex e2da80c17d..97a18ba005 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -6740,7 +6740,7 @@ components:prompt:type: arrayitems:- $ref: '#/components/schemas/ChatMessage'+ $ref: '#/components/schemas/ChatMessageWithPlaceholders'config:nullable: truelabels:@@ -6854,6 +6854,31 @@ components:- config- labels- tags+ ChatMessageWithPlaceholders:+ title: ChatMessageWithPlaceholders+ oneOf:+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - chatmessage+ - $ref: '#/components/schemas/ChatMessage'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - placeholder+ - $ref: '#/components/schemas/PlaceholderMessage'+ required:+ - typeChatMessage:title: ChatMessagetype: object@@ -6865,6 +6890,14 @@ components:required:- role- content+ PlaceholderMessage:+ title: PlaceholderMessage+ type: object+ properties:+ name:+ type: string+ required:+ - nameTextPrompt:title: TextPrompttype: object@@ -6882,7 +6915,7 @@ components:prompt:type: arrayitems:- $ref: '#/components/schemas/ChatMessage'+ $ref: '#/components/schemas/ChatMessageWithPlaceholders'required:- promptallOf:diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.jsonindex 8141b4af15..877e49e2f4 100644--- a/web/public/generated/postman/collection.json+++ b/web/public/generated/postman/collection.json@@ -2151,7 +2151,7 @@"auth": null,"body": {"mode": "raw",- "raw": "{\n \"type\": \"chat\",\n \"name\": \"example\",\n \"prompt\": [\n {\n \"role\": \"example\",\n \"content\": \"example\"\n }\n ],\n \"config\": \"UNKNOWN\",\n \"labels\": [\n \"example\"\n ],\n \"tags\": [\n \"example\"\n ],\n \"commitMessage\": \"example\"\n}",+ "raw": "{\n \"type\": \"chat\",\n \"name\": \"example\",\n \"prompt\": [\n {\n \"type\": \"chatmessage\",\n \"role\": \"example\",\n \"content\": \"example\"\n }\n ],\n \"config\": \"UNKNOWN\",\n \"labels\": [\n \"example\"\n ],\n \"tags\": [\n \"example\"\n ],\n \"commitMessage\": \"example\"\n}","options": {"raw": {"language": "json"diff --git a/web/src/__tests__/compileChatMessages.servertest.ts b/web/src/__tests__/compileChatMessages.servertest.tsnew file mode 100644index 0000000000..d6d55c3ab9--- /dev/null+++ b/web/src/__tests__/compileChatMessages.servertest.ts@@ -0,0 +1,152 @@+/** @jest-environment node */++import { ChatMessageType, compileChatMessages, extractPlaceholderNames } from "@langfuse/shared";++describe("compileChatMessages", () => {+ it("should compile message placeholders with provided values", () => {+ // Simulates how message placeholders would be compiled+ // during execution (e.g., in playground or experiments)++ const promptTemplate = [+ { role: "system", content: "You are a helpful assistant." },+ {+ type: ChatMessageType.Placeholder,+ name: "conversation_history"+ },+ { role: "user", content: "{{user_question}}" }+ ];++ const placeholderValues = {+ conversation_history: [+ { role: "user", content: "Hello!" },+ { role: "assistant", content: "Hi there! How can I help you?" },+ { role: "user", content: "What's the weather like?" }+ ]+ };++ const textVariables = {+ user_question: "Can you continue our conversation?"+ };++ // Simulate compilation logic that would happen in playground/experiments+ const compiledMessages = compileChatMessages(+ promptTemplate,+ placeholderValues,+ textVariables+ );++ expect(compiledMessages).toEqual([+ { role: "system", content: "You are a helpful assistant." },+ { role: "user", content: "Hello!" },+ { role: "assistant", content: "Hi there! How can I help you?" },+ { role: "user", content: "What's the weather like?" },+ { role: "user", content: "Can you continue our conversation?" }+ ]);+ });++ it("should throw error when placeholder value is missing", () => {+ const promptTemplate = [+ { role: "system", content: "You are a helpful assistant." },+ {+ type: ChatMessageType.Placeholder,+ name: "missing_placeholder"+ },+ { role: "user", content: "Hello" }+ ];++ const placeholderValues = {};++ expect(() => {+ compileChatMessages(promptTemplate, placeholderValues);+ }).toThrow("Missing value for message placeholder: missing_placeholder");+ });++ it("should throw error when placeholder messages lack required properties", () => {+ const promptTemplate = [+ {+ type: ChatMessageType.Placeholder,+ name: "invalid_messages"+ }+ ];++ // Test missing role property+ const placeholderValuesNoRole = {+ invalid_messages: [+ { content: "Hello" }+ ]+ };++ expect(() => {+ compileChatMessages(promptTemplate, placeholderValuesNoRole);+ }).toThrow("Invalid message format in placeholder 'invalid_messages': messages must have 'role' and 'content' properties");++ // Test missing content property+ const placeholderValuesNoContent = {+ invalid_messages: [+ { role: "user" }+ ]+ };++ expect(() => {+ compileChatMessages(promptTemplate, placeholderValuesNoContent);+ }).toThrow("Invalid message format in placeholder 'invalid_messages': messages must have 'role' and 'content' properties");+ });++ it("should compile placeholders without applying text substitutions when no variables provided", () => {+ const promptTemplate = [+ { role: "system", content: "You are a helpful assistant. {{system_var}}" },+ {+ type: ChatMessageType.Placeholder,+ name: "history"+ },+ { role: "user", content: "{{user_var}}" }+ ];++ const placeholderValues = {+ history: [+ { role: "user", content: "Previous message with {{var}}" },+ { role: "assistant", content: "Response with {{another_var}}" }+ ]+ };++ // No text variables provided+ const compiledMessages = compileChatMessages(promptTemplate, placeholderValues);++ expect(compiledMessages).toEqual([+ { role: "system", content: "You are a helpful assistant. {{system_var}}" },+ { role: "user", content: "Previous message with {{var}}" },+ { role: "assistant", content: "Response with {{another_var}}" },+ { role: "user", content: "{{user_var}}" }+ ]);+ });++ it("should extract all placeholder names from messages", () => {+ const promptTemplate = [+ { role: "system", content: "System message" },+ {+ type: ChatMessageType.Placeholder,+ name: "history"+ },+ { role: "user", content: "User message" },+ {+ type: ChatMessageType.Placeholder,+ name: "context"+ }+ ];++ const placeholderNames = extractPlaceholderNames(promptTemplate);++ expect(placeholderNames).toEqual(["history", "context"]);+ });++ it("should return empty array when no placeholders exist", () => {+ const promptTemplate = [+ { role: "system", content: "System message" },+ { role: "user", content: "User message" }+ ];++ const placeholderNames = extractPlaceholderNames(promptTemplate);++ expect(placeholderNames).toEqual([]);+ });+});diff --git a/web/src/__tests__/prompts.v2.servertest.ts b/web/src/__tests__/prompts.v2.servertest.tsindex 525f40f00c..2b972da0b2 100644--- a/web/src/__tests__/prompts.v2.servertest.ts+++ b/web/src/__tests__/prompts.v2.servertest.ts@@ -7,16 +7,18 @@ import {PromptSchema,PromptType,type ValidatedPrompt,+ type ChatMessage,type Prompt,} from "@langfuse/shared";import { parsePromptDependencyTags } from "@langfuse/shared";-import { nanoid } from "ai";+import { generateId, nanoid } from "ai";import { type PromptsMetaResponse } from "@/src/features/prompts/server/actions/getPromptsMeta";import {createOrgProjectAndApiKey,getObservationById,MAX_PROMPT_NESTING_DEPTH,+ ChatMessageType,} from "@langfuse/shared/src/server";import { randomUUID } from "node:crypto";@@ -452,6 +454,52 @@ describe("/api/public/v2/prompts API Endpoint", () => {expect(validatedPrompt.commitMessage).toBe("chore: setup initial prompt");});+ it("should create and fetch a chat prompt with message placeholders", async () => {+ const promptName = `prompt-name-message-placeholders${generateId()}`;+ const commitMessage = "feat: add message placeholders support";+ const chatMessages = [+ { role: "system", content: "You are a helpful assistant with conversation context." },+ {+ type: ChatMessageType.Placeholder,+ name: "conversation_history"+ },+ { role: "user", content: "{{user_question}}" }+ ];++ const response = await makeAPICall("POST", baseURI, {+ name: promptName,+ prompt: chatMessages,+ type: "chat",+ labels: ["production"],+ commitMessage: commitMessage+ });++ expect(response.status).toBe(201);++ const { body: fetchedPrompt } = await makeAPICall(+ "GET",+ `${baseURI}/${promptName}`,+ undefined,+ );++ const validatedPrompt = validatePrompt(fetchedPrompt);++ expect(validatedPrompt.name).toBe(promptName);+ expect(validatedPrompt.prompt).toEqual(chatMessages);+ expect(validatedPrompt.type).toBe("chat");+ expect(validatedPrompt.version).toBe(1);+ expect(validatedPrompt.labels).toEqual(["production", "latest"]);+ expect(validatedPrompt.createdBy).toBe("API");+ expect(validatedPrompt.config).toEqual({});+ expect(validatedPrompt.commitMessage).toBe(commitMessage);++ // Verify the placeholder message structure is preserved+ const messages = validatedPrompt.prompt as ChatMessage[];+ const placeholderMessage = messages[1] as { type: ChatMessageType.Placeholder; name: string };+ expect(placeholderMessage.type).toBe(ChatMessageType.Placeholder);+ expect(placeholderMessage.name).toBe("conversation_history");+ });+it("should fail if chat prompt has string prompt", async () => {const promptName = "prompt-name";const response = await makeAPICall("POST", baseURI, {diff --git a/web/src/components/ChatMessages/ChatMessageComponent.tsx b/web/src/components/ChatMessages/ChatMessageComponent.tsxindex 4ee5917fd9..1699289578 100644--- a/web/src/components/ChatMessages/ChatMessageComponent.tsx+++ b/web/src/components/ChatMessages/ChatMessageComponent.tsx@@ -8,6 +8,7 @@ import {SYSTEM_ROLES,type ChatMessageWithId,type LLMToolCall,+ type PlaceholderMessage,} from "@langfuse/shared";import { Button } from "@/src/components/ui/button";import { Card, CardContent } from "@/src/components/ui/card";@@ -45,15 +46,17 @@ const ROLES: ChatMessageRole[] = [const getRoleNamePlaceholder = (role: string) => {switch (role) {case ChatMessageRole.System:- return "a system";+ return "a system message";case ChatMessageRole.Developer:- return "a developer";+ return "a developer message";case ChatMessageRole.Assistant:- return "an assistant";+ return "an assistant message";case ChatMessageRole.User:- return "a user";+ return "a user message";case ChatMessageRole.Tool:- return "a tool response";+ return "a tool response message";+ case "placeholder":+ return "placeholder name (e.g. msg_history)";default:return `a ${role}`;}@@ -92,6 +95,9 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({} = useSortable({ id: message.id });const toggleRole = () => {+ // Only allow role toggling for messages that have a role property (not placeholder messages)+ if (!('role' in message)) return;+// if user has set custom roles, available roles will be non-empty and we toggle through custom and default roles (assistant, user)if (!!availableRoles && Boolean(availableRoles.length)) {let randomRole = availableRoles[roleIndex % availableRoles.length];@@ -113,7 +119,7 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({(toolCallIds && toolCallIds.length > 0),);const currentIndex = eligibleRoles.indexOf(- message.role as ChatMessageRole,+ ('role' in message ? message.role : ChatMessageRole.User) as ChatMessageRole,);const nextRole =eligibleRoles[(currentIndex + 1) % eligibleRoles.length];@@ -196,13 +202,28 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({};const onValueChange = useCallback(- (value: string) =>- updateMessage(message.type, message.id, "content", value),+ (value: string) => {+ if (message.type === ChatMessageType.Placeholder) {+ updateMessage(message.type, message.id, "name", value);+ } else {+ updateMessage(message.type, message.id, "content", value);+ }+ },[message.id, message.type, updateMessage],);- const showDragHandle = !SYSTEM_ROLES.includes(message.role);+ const onPlaceholderNameChange = useCallback(+ (value: string) => {+ if (message.type === ChatMessageType.Placeholder) {+ updateMessage(message.type, message.id, "name", value);+ }+ },+ [message.id, message.type, updateMessage],+ );++ const showDragHandle = !('role' in message && SYSTEM_ROLES.includes(message.role));const showToolCallSelect = message.type === ChatMessageType.ToolResult;+ const isPlaceholder = message.type === ChatMessageType.Placeholder;return (<Card@@ -233,14 +254,20 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({)}><div className="flex w-[4rem] flex-shrink-0 flex-col gap-1">- <Button- onClick={toggleRole}- type="button"- variant="ghost"- className="h-6 w-full px-1 py-0 text-[10px] font-semibold text-muted-foreground hover:bg-accent hover:text-accent-foreground"- >- {capitalize(message.role)}- </Button>+ {isPlaceholder ? (+ <span className="inline-flex items-center justify-center font-mono h-6 w-full text-[9px] rounded-md bg-accent px-4 text-muted-foreground">+ placeholder+ </span>+ ) : (+ <Button+ onClick={toggleRole}+ type="button"+ variant="ghost"+ className="h-6 w-full px-1 py-0 text-[10px] font-semibold text-muted-foreground hover:bg-accent hover:text-accent-foreground"+ >+ {capitalize(message.role)}+ </Button>+ )}</div><div className="flex flex-1 flex-col gap-1"><div className="flex gap-2">@@ -271,11 +298,19 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({</SelectContent></Select>)}- <MemoizedEditor- value={message.content}- onChange={onValueChange}- role={message.role}- />+ {isPlaceholder ? (+ <MemoizedEditor+ value={(message as PlaceholderMessage).name || ""}+ onChange={onPlaceholderNameChange}+ role={message.type}+ />+ ) : (+ <MemoizedEditor+ value={message.content}+ onChange={onValueChange}+ role={message.role}+ />+ )}</div>{message.type === ChatMessageType.AssistantToolCall && (<ToolCalls toolCalls={message.toolCalls as LLMToolCall[]} />@@ -303,7 +338,7 @@ const MemoizedEditor = memo(function MemoizedEditor(props: {onChange: (value: string) => void;}) {const { value, role, onChange } = props;- const placeholder = `Enter ${getRoleNamePlaceholder(role)} message here.`;+ const placeholder = `Enter ${getRoleNamePlaceholder(role)} here.`;return (<CodeMirrorEditordiff --git a/web/src/components/ChatMessages/index.tsx b/web/src/components/ChatMessages/index.tsxindex ebe448eaf0..0875792be2 100644--- a/web/src/components/ChatMessages/index.tsx+++ b/web/src/components/ChatMessages/index.tsx@@ -2,9 +2,16 @@ import { PlusCircleIcon } from "lucide-react";import { useEffect, useRef } from "react";import { Button } from "@/src/components/ui/button";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";import {ChatMessageRole,ChatMessageType,+ type ChatMessageWithId,SYSTEM_ROLES,} from "@langfuse/shared";@@ -60,8 +67,9 @@ export const ChatMessages: React.FC<ChatMessagesProps> = (props) => {if (newIndex < 0 || oldIndex < 0) {return;}- // prevent reordering system messages- if (SYSTEM_ROLES.includes(messages[newIndex].role)) {+ // prevent reordering system messages, placeholders can be reordered+ const targetMessage = messages[newIndex];+ if (targetMessage.type !== ChatMessageType.Placeholder && SYSTEM_ROLES.includes(targetMessage.role)) {return;}const newMessages = arrayMove(messages, oldIndex, newIndex);@@ -114,35 +122,66 @@ const AddMessageButton: React.FC<AddMessageButtonProps> = ({messages,addMessage,}) => {- const lastMessageRole = messages[messages.length - 1]?.role;+ // Skip placeholder messages when determining last roles+ const lastMessageWithRole = messages.slice().reverse().find((msg): msg is ChatMessageWithId & { role: string } => msg.type !== ChatMessageType.Placeholder);+ const lastMessageRole = lastMessageWithRole?.role;const nextMessageRole =lastMessageRole === ChatMessageRole.User? ChatMessageRole.Assistant: ChatMessageRole.User;+ const addRegularMessage = () => {+ if (nextMessageRole === ChatMessageRole.User) {+ addMessage({+ role: nextMessageRole,+ content: "",+ type: ChatMessageType.User,+ });+ } else {+ addMessage({+ role: nextMessageRole,+ content: "",+ type: ChatMessageType.AssistantText,+ });+ }+ };++ const addPlaceholderMessage = () => {+ addMessage({+ type: ChatMessageType.Placeholder,+ name: "",+ });+ };+return (- <Button- type="button" // prevents submitting a form if this button is inside a form- variant="outline"- className="w-full"- onClick={() => {- if (nextMessageRole === ChatMessageRole.User) {- addMessage({- role: nextMessageRole,- content: "",- type: ChatMessageType.User,- });- } else {- addMessage({- role: nextMessageRole,- content: "",- type: ChatMessageType.AssistantText,- });- }- }}- >- <PlusCircleIcon size={14} className="mr-2" />- <p>Add message</p>- </Button>+ <div className="flex gap-2">+ <Button+ type="button"+ variant="outline"+ className="flex-1"+ onClick={addRegularMessage}+ >+ <PlusCircleIcon size={14} className="mr-2" />+ <p>Add message</p>+ </Button>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="outline"+ className="flex-1"+ onClick={addPlaceholderMessage}+ >+ <PlusCircleIcon size={14} className="mr-2" />+ <p>Add message placeholder</p>+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p className="text-xs">Adds a placeholder to inject message pairs, e.g. a message history (with "role", "content" pairs) when compiling the message in the SDK.</p>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>);};diff --git a/web/src/components/ChatMessages/types.ts b/web/src/components/ChatMessages/types.tsindex f819ec0002..33c205bcdc 100644--- a/web/src/components/ChatMessages/types.ts+++ b/web/src/components/ChatMessages/types.ts@@ -1,15 +1,15 @@-import type { ChatMessage, ChatMessageWithId } from "@langfuse/shared";+import type { ChatMessage, ChatMessageWithId, PlaceholderMessage } from "@langfuse/shared";export type MessagesContext = {messages: ChatMessageWithId[];- addMessage: (message: ChatMessage) => ChatMessageWithId;+ addMessage: (message: ChatMessage | PlaceholderMessage) => ChatMessageWithId;setMessages: (messages: ChatMessageWithId[]) => void;deleteMessage: (id: string) => void;updateMessage: <T extends ChatMessageWithId["type"],Key extends keyof Omit<Extract<ChatMessageWithId, { type: T }>,- "id" | "type" | "role"+ "id" | "type">,Value = Extract<ChatMessageWithId, { type: T }>[Key],>(diff --git a/web/src/components/ChatMessages/utils/createEmptyMessage.ts b/web/src/components/ChatMessages/utils/createEmptyMessage.tsindex 8fb1b67beb..e4c3208fbc 100644--- a/web/src/components/ChatMessages/utils/createEmptyMessage.ts+++ b/web/src/components/ChatMessages/utils/createEmptyMessage.ts@@ -1,7 +1,7 @@import { v4 as uuidv4 } from "uuid";-import { type ChatMessage, type ChatMessageWithId } from "@langfuse/shared";+import { type ChatMessage, type ChatMessageWithIdNoPlaceholders } from "@langfuse/shared";-export function createEmptyMessage(message: ChatMessage): ChatMessageWithId {+export function createEmptyMessage(message: ChatMessage): ChatMessageWithIdNoPlaceholders {return {...message,content: message.content ?? "",diff --git a/web/src/components/schemas/ChatMlSchema.ts b/web/src/components/schemas/ChatMlSchema.tsindex 37cdb28e25..8149fd39aa 100644--- a/web/src/components/schemas/ChatMlSchema.ts+++ b/web/src/components/schemas/ChatMlSchema.ts@@ -125,11 +125,12 @@ export const ChatMlMessageSchema = z...other,...additional_kwargs,}))- .transform(({ role, name, content, audio, ...other }) => ({+ .transform(({ role, name, content, audio, type, ...other }) => ({role,name,content,audio,+ type,...(Object.keys(other).length === 0 ? {} : { json: other }),}));export type ChatMlMessageSchema = z.infer<typeof ChatMlMessageSchema>;diff --git a/web/src/components/trace/IOPreview.tsx b/web/src/components/trace/IOPreview.tsxindex 3a28c8f67e..e6c1fa8c47 100644--- a/web/src/components/trace/IOPreview.tsx+++ b/web/src/components/trace/IOPreview.tsx@@ -234,10 +234,14 @@ export const OpenAiMessageView: React.FC<{return !!message.json;};+ const isPlaceholderMessage = (message: ChatMlMessageSchema) => {+ return message.type === 'placeholder';+ };+const messagesToRender = useMemo(() =>messages.filter(- (message) => shouldRenderContent(message) || shouldRenderJson(message),+ (message) => shouldRenderContent(message) || shouldRenderJson(message) || isPlaceholderMessage(message),),[messages],);@@ -257,39 +261,57 @@ export const OpenAiMessageView: React.FC<{).map((message, index) => (<Fragment key={index}>- {shouldRenderContent(message) &&- (shouldRenderMarkdown ? (+ {isPlaceholderMessage(message) ? (+ shouldRenderMarkdown ? (<MarkdownJsonView- title={message.name ?? message.role}- content={message.content || '""'}- className={cn(!!message.json && "rounded-b-none")}- customCodeHeaderClassName={cn(- message.role === "assistant" && "bg-secondary",- message.role === "system" && "bg-primary-foreground",- )}- audio={message.audio}+ title="Placeholder"+ content={message.name || 'Unnamed placeholder'}+ customCodeHeaderClassName={cn("bg-primary-foreground")}/>) : (<JSONView- title={message.name ?? message.role}- json={message.content}+ title="Placeholder"+ json={message.name || 'Unnamed placeholder'}projectIdForPromptButtons={projectIdForPromptButtons}- className={cn(!!message.json && "rounded-b-none")}/>- ))}- {shouldRenderJson(message) && (- <JSONView- title={- message.content- ? undefined- : (message.name ?? message.role)- }- json={message.json}- projectIdForPromptButtons={projectIdForPromptButtons}- className={cn(- !!message.content && "rounded-t-none border-t-0",+ )+ ) : (+ <>+ {shouldRenderContent(message) &&+ (shouldRenderMarkdown ? (+ <MarkdownJsonView+ title={message.name ?? message.role}+ content={message.content || '""'}+ className={cn(!!message.json && !isPlaceholderMessage(message) && "rounded-b-none")}+ customCodeHeaderClassName={cn(+ message.role === "assistant" && "bg-secondary",+ message.role === "system" && "bg-primary-foreground",+ )}+ audio={message.audio}+ />+ ) : (+ <JSONView+ title={message.name ?? message.role}+ json={message.content}+ projectIdForPromptButtons={projectIdForPromptButtons}+ className={cn(!!message.json && !isPlaceholderMessage(message) && "rounded-b-none")}+ />+ ))}+ {shouldRenderJson(message) && !isPlaceholderMessage(message) && (+ <JSONView+ title={+ message.content+ ? undefined+ : (message.name ?? message.role)+ }+ json={message.json}+ projectIdForPromptButtons={projectIdForPromptButtons}+ className={cn(+ !!message.content && "rounded-t-none border-t-0",+ )}+ />)}- />+ </>)}{isCollapsed !== null && index === 0 ? (<Buttondiff --git a/web/src/features/experiments/server/router.ts b/web/src/features/experiments/server/router.tsindex 926b71956d..9ba8f38cc5 100644--- a/web/src/features/experiments/server/router.ts+++ b/web/src/features/experiments/server/router.ts@@ -7,6 +7,7 @@ import {redis,ZodModelConfig,ExperimentCreateQueue,+ type PlaceholderMessage,} from "@langfuse/shared/src/server";import {createTRPCRouter,@@ -104,6 +105,20 @@ export const experimentsRouter = createTRPCRouter({};}+ const promptMessages = prompt?.type === PromptType.Chat && Array.isArray(prompt.prompt)+ ? prompt.prompt+ : [];+ const hasPlaceholders = promptMessages.some((msg): msg is PlaceholderMessage =>+ (msg as PlaceholderMessage).type === "placeholder"+ );++ if (hasPlaceholders) {+ return {+ isValid: false,+ message: "Selected prompt has placeholders, those are not yet supported for experiments.",+ };+ }+const datasetItems = await ctx.prisma.datasetItem.findMany({where: {datasetId: input.datasetId,diff --git a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsxindex 9b69fbbcc7..86c7bdf7cb 100644--- a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx+++ b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx@@ -7,9 +7,9 @@ import { createEmptyMessage } from "@/src/components/ChatMessages/utils/createEmimport { Button } from "@/src/components/ui/button";import usePlaygroundCache from "@/src/features/playground/page/hooks/usePlaygroundCache";import {- type PlaygroundTool,type PlaygroundCache,type PlaygroundSchema,+ type PlaygroundTool,} from "@/src/features/playground/page/types";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";@@ -27,6 +27,9 @@ import {type ChatMessage,OpenAIResponseFormatSchema,type Prisma,+ PlaceholderMessageSchema,+ type PlaceholderMessage,+ isPlaceholder,PromptType,} from "@langfuse/shared";import { api } from "@/src/utils/api";@@ -138,34 +141,38 @@ export const JumpToPlaygroundButton: React.FC<JumpToPlaygroundButtonProps> = (};const ParsedChatMessageListSchema = z.array(- z.object({- role: z.enum(ChatMessageRole),- content: z.union([- z.string(),- z- .array(- z- .object({- text: z.string(),- })- .transform((v) => v.text),- )- .transform((v) => v.join("")),- z.union([z.null(), z.undefined()]).transform((_) => ""),- z.any().transform((v) => JSON.stringify(v, null, 2)),- ]),- tool_calls: z- .union([z.array(LLMToolCallSchema), z.array(OpenAIToolCallSchema)])- .optional(),- tool_call_id: z.string().optional(),- additional_kwargs: z- .object({- tool_calls: z- .union([z.array(LLMToolCallSchema), z.array(OpenAIToolCallSchema)])- .optional(),- })- .optional(),- }),+ z.union([+ // Regular chat message+ z.object({+ role: z.enum(ChatMessageRole),+ content: z.union([+ z.string(),+ z+ .array(+ z+ .object({+ text: z.string(),+ })+ .transform((v) => v.text),+ )+ .transform((v) => v.join("")),+ z.union([z.null(), z.undefined()]).transform((_) => ""),+ z.any().transform((v) => JSON.stringify(v, null, 2)),+ ]),+ tool_calls: z+ .union([z.array(LLMToolCallSchema), z.array(OpenAIToolCallSchema)])+ .optional(),+ tool_call_id: z.string().optional(),+ additional_kwargs: z+ .object({+ tool_calls: z+ .union([z.array(LLMToolCallSchema), z.array(OpenAIToolCallSchema)])+ .optional(),+ })+ .optional(),+ }),+ PlaceholderMessageSchema,+ ]));// Langchain integration has the tool definition in a tool message@@ -173,6 +180,9 @@ const ParsedChatMessageListSchema = z.array(const isLangchainToolDefinitionMessage = (message: z.infer<typeof ParsedChatMessageListSchema>[0],): message is { content: string; role: ChatMessageRole } => {+ if (!("content" in message) || typeof message.content !== "string") {+ return false;+ }try {return OpenAIToolSchema.safeParse(JSON.parse(message.content)).success;} catch {@@ -182,15 +192,22 @@ const isLangchainToolDefinitionMessage = (const transformToPlaygroundMessage = (message: z.infer<typeof ParsedChatMessageListSchema>[0],-): ChatMessage => {- const { role, content } = message;+): ChatMessage | PlaceholderMessage => {+ // Return placeholder messages as-is+ if (isPlaceholder(message)) {+ return message;+ }++ // Handle regular chat messages - remove the placeholder type+ const regularMessage = message as Exclude<typeof message, PlaceholderMessage>;+ const { role, content } = regularMessage;if (- message.role === "assistant" &&- (message.tool_calls || message.additional_kwargs?.tool_calls)+ regularMessage.role === "assistant" &&+ (regularMessage.tool_calls || regularMessage.additional_kwargs?.tool_calls)) {const toolCalls =- message.tool_calls ?? message.additional_kwargs?.tool_calls ?? [];+ regularMessage.tool_calls ?? regularMessage.additional_kwargs?.tool_calls ?? [];const playgroundMessage: ChatMessage = {role: ChatMessageRole.Assistant,@@ -210,12 +227,12 @@ const transformToPlaygroundMessage = (};return playgroundMessage;- } else if (message.role === "tool") {+ } else if (regularMessage.role === "tool") {const playgroundMessage: ChatMessage = {role: ChatMessageRole.Tool,content,type: ChatMessageType.ToolResult,- toolCallId: message.tool_call_id ?? "",+ toolCallId: regularMessage.tool_call_id ?? "",};return playgroundMessage;diff --git a/web/src/features/playground/page/components/MessagePlaceholderComponent.tsx b/web/src/features/playground/page/components/MessagePlaceholderComponent.tsxnew file mode 100644index 0000000000..4f9cd82e68--- /dev/null+++ b/web/src/features/playground/page/components/MessagePlaceholderComponent.tsx@@ -0,0 +1,74 @@+import { CheckCircle2, Circle, TrashIcon } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { CodeMirrorEditor } from "@/src/components/editor";+import { useState, useCallback } from "react";+import { type ChatMessage, PromptChatMessageListSchema } from "@langfuse/shared";++import { usePlaygroundContext } from "../context";+import { type PlaceholderMessageFillIn } from "../types";++export const MessagePlaceholderComponent: React.FC<{+ messagePlaceholder: PlaceholderMessageFillIn;+}> = ({ messagePlaceholder }) => {+ const { updateMessagePlaceholderValue, deleteMessagePlaceholder } =+ usePlaygroundContext();+ const { name, value, isUsed } = messagePlaceholder;+ const [error, setError] = useState<string | null>(null);++ const handleInputChange = useCallback((jsonString: string) => {+ try {+ const parsed = jsonString.trim() === "" ? [] : JSON.parse(jsonString);+ const result = PromptChatMessageListSchema.safeParse(parsed);++ if (result.success) {+ updateMessagePlaceholderValue(name, result.data as ChatMessage[]);+ setError(null);+ } else {+ setError(result.error.issues[0]?.message || "Invalid chat message format, ensure it has role and content keys.");+ }+ } catch {+ setError("Invalid JSON format");+ }+ }, [name, updateMessagePlaceholderValue]);++ const UsedIcon = isUsed ? CheckCircle2 : Circle;+ const iconColor = isUsed ? "green" : "grey";++ return (+ <div className="p-1">+ <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}>+ {name ? name : "Unnamed placeholder"}+ </p>+ </span>+ <Button+ variant="ghost"+ size="icon"+ title="Delete placeholder"+ disabled={isUsed}+ onClick={() => deleteMessagePlaceholder(name)}+ className="p-0"+ >+ {!isUsed && <TrashIcon size={16} />}+ </Button>+ </div>++ <CodeMirrorEditor+ value={value.length === 0 ? `[\n {\n "role": "",\n "content": ""\n }\n]` : JSON.stringify(value, null, 2)}+ onChange={handleInputChange}+ mode="json"+ minHeight="none"+ className="max-h-[15rem] w-full resize-y p-1 font-mono text-xs focus:outline-none"+ editable={true}+ lineNumbers={false}+ placeholder={`[\n {\n "role": "user",\n "content": "Hello!"\n },\n {\n "role": "assistant",\n "content": "Hi there!"\n }\n]`}+ />++ {error && (+ <p className="mt-1 text-xs text-red-500">{error}</p>+ )}+ </div>+ );+};diff --git a/web/src/features/playground/page/components/MessagePlaceholders.tsx b/web/src/features/playground/page/components/MessagePlaceholders.tsxnew file mode 100644index 0000000000..f84d8ed00e--- /dev/null+++ b/web/src/features/playground/page/components/MessagePlaceholders.tsx@@ -0,0 +1,38 @@+import { Divider } from "@tremor/react";++import { usePlaygroundContext } from "../context";+import { MessagePlaceholderComponent } from "./MessagePlaceholderComponent";++export const MessagePlaceholders = () => {+ const { messagePlaceholders } = usePlaygroundContext();++ return (+ <div className="flex h-full flex-col">+ <p className="font-semibold">Message Placeholders</p>+ {messagePlaceholders.length === 0 ? (+ <div className="mt-4 text-xs">+ <p className="mb-2">No message placeholders defined.</p>+ <p>Placeholders can be used to e.g. inject message histories into prompts.</p>+ </div>+ ) : (+ <div className="h-full overflow-auto">+ {messagePlaceholders+ .slice()+ .sort((a, b) => {+ if (a.isUsed && !b.isUsed) return -1;+ if (!a.isUsed && b.isUsed) return 1;+ return a.name.localeCompare(b.name);+ })+ .map((placeholder, index) => (+ <div key={placeholder.name}>+ <MessagePlaceholderComponent messagePlaceholder={placeholder} />+ {index !== messagePlaceholders.length - 1 && (+ <Divider className="my-2 text-muted-foreground" />+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ );+};diff --git a/web/src/features/playground/page/context/index.tsx b/web/src/features/playground/page/context/index.tsxindex d902e4c13b..6d74bb3637 100644--- a/web/src/features/playground/page/context/index.tsx+++ b/web/src/features/playground/page/context/index.tsx@@ -18,6 +18,7 @@ import {ChatMessageRole,extractVariables,type ChatMessageWithId,+ type ChatMessageWithIdNoPlaceholders,type PromptVariable,ToolCallResponseSchema,type UIModelParams,@@ -25,6 +26,9 @@ import {type LLMToolDefinition,type LLMToolCall,ChatMessageType,+ type ChatMessage,+ compileChatMessagesWithIds,+ type MessagePlaceholderValues,} from "@langfuse/shared";import type { MessagesContext } from "@/src/components/ChatMessages/types";@@ -33,14 +37,20 @@ import { env } from "@/src/env.mjs";import {type PlaygroundSchema,type PlaygroundTool,+ type PlaceholderMessageFillIn,} from "@/src/features/playground/page/types";import { getFinalModelParams } from "@/src/utils/getFinalModelParams";+type PlaygroundContextType = {promptVariables: PromptVariable[];updatePromptVariableValue: (variable: string, value: string) => void;deletePromptVariable: (variable: string) => void;+ messagePlaceholders: PlaceholderMessageFillIn[];+ updateMessagePlaceholderValue: (name: string, value: ChatMessage[]) => void;+ deleteMessagePlaceholder: (name: string) => void;+tools: PlaygroundTool[];setTools: React.Dispatch<React.SetStateAction<PlaygroundTool[]>>;@@ -77,6 +87,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({const projectId = useProjectIdFromURL();const { playgroundCache, setPlaygroundCache } = usePlaygroundCache();const [promptVariables, setPromptVariables] = useState<PromptVariable[]>([]);+ const [messagePlaceholders, setMessagePlaceholders] = useState<PlaceholderMessageFillIn[]>([]);const [output, setOutput] = useState("");const [outputToolCalls, setOutputToolCalls] = useState<LLMToolCall[]>([]);const [outputJson, setOutputJson] = useState("");@@ -160,7 +171,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({}, [playgroundCache, setModelParams]);const updatePromptVariables = useCallback(() => {- const messageContents = messages.map((m) => m.content).join("\n");+ const messageContents = messages.map((m) => ('content' in m ? m.content : m.name)).join("\n");const variables = extractVariables(messageContents).map((v) => v.trim()).filter(Boolean);@@ -219,6 +230,10 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({]);return toolCallMessage;+ } else if (message.type === ChatMessageType.Placeholder) {+ const placeholderMessage = { ...message, id: uuidv4() } as ChatMessageWithId;+ setMessages((prev) => [...prev, placeholderMessage]);+ return placeholderMessage;} else {const newMessage = createEmptyMessage(message);setMessages((prev) => [...prev, newMessage]);@@ -264,7 +279,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({setOutputJson("");setOutputToolCalls([]);- const finalMessages = getFinalMessages(promptVariables, messages);+ const finalMessages = getFinalMessages(promptVariables, messages, messagePlaceholders);const leftOverVariables = extractVariables(finalMessages.map((m) => m.content).join("\n"),);@@ -372,6 +387,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({messages,modelParams,promptVariables,+ messagePlaceholders,tools,capture,setPlaygroundCache,@@ -395,12 +411,57 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({setPromptVariables((prev) => prev.filter((v) => v.name !== variable));}, []);+ const updateMessagePlaceholderValue = useCallback((name: string, value: ChatMessage[]) => {+ setMessagePlaceholders((prev) =>+ prev.map((p) => (p.name === name ? { ...p, value } : p)),+ );+ }, []);++ const deleteMessagePlaceholder = useCallback((name: string) => {+ setMessagePlaceholders((prev) => prev.filter((p) => p.name !== name));+ }, []);++ const updateMessagePlaceholders = useCallback(() => {+ const placeholderNames = messages+ .filter((msg): msg is ChatMessageWithId & { type: ChatMessageType.Placeholder; name: string } =>+ msg.type === ChatMessageType.Placeholder+ )+ .map((msg) => msg.name);++ setMessagePlaceholders((prev) => {+ // Set isUsed flag for existing placeholders and remove unused ones+ const next = prev.reduce<PlaceholderMessageFillIn[]>((updatedPlaceholders, p) => {+ const isUsed = placeholderNames.includes(p.name);+ // Remove unused placeholders+ if (!isUsed && p.value.length === 0) {+ return updatedPlaceholders;+ }+ updatedPlaceholders.push({ ...p, isUsed });+ return updatedPlaceholders;+ }, []);++ // Add new placeholders+ for (const name of placeholderNames) {+ if (!next.some((p) => p.name === name)) {+ next.push({ name, value: [], isUsed: true });+ }+ }++ return next;+ });+ }, [messages]);++ useEffect(updateMessagePlaceholders, [messages, updateMessagePlaceholders]);+return (<PlaygroundContext.Providervalue={{promptVariables,updatePromptVariableValue,deletePromptVariable,+ messagePlaceholders,+ updateMessagePlaceholderValue,+ deleteMessagePlaceholder,tools,setTools,@@ -437,7 +498,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({async function getChatCompletionWithTools(projectId: string | undefined,- messages: ChatMessageWithId[],+ messages: ChatMessageWithIdNoPlaceholders[],modelParams: UIModelParams,tools: unknown[],streaming: boolean = false,@@ -607,7 +668,8 @@ async function getChatCompletionNonStreaming(function getFinalMessages(promptVariables: PromptVariable[],messages: ChatMessageWithId[],-) {+ messagePlaceholders: PlaceholderMessageFillIn[],+): ChatMessageWithIdNoPlaceholders[] {const missingVariables = promptVariables.filter((v) => !v.value && v.isUsed);if (missingVariables.length > 0) {throw new Error(@@ -617,24 +679,44 @@ function getFinalMessages();}- // Dynamically replace variables in the prompt- const finalMessages = messages- .filter(- (m) =>- m.content.length > 0 || ("toolCalls" in m && m.toolCalls.length > 0),- )- .map((m) => {- let content = m.content;- for (const variable of promptVariables) {- content = content.replace(- new RegExp(`{{\\s*${variable.name}\\s*}}`, "g"),- variable.value,- );- }+ const missingPlaceholders = messagePlaceholders.filter(+ (p) => p.value.length === 0 && p.isUsed,+ );+ if (missingPlaceholders.length > 0) {+ throw new Error(+ `Please set values for the following message placeholders: ${missingPlaceholders+ .map((p) => p.name)+ .join(", ")}`,+ );+ }- return { ...m, content };- });- return finalMessages;+ const placeholderValues: MessagePlaceholderValues = messagePlaceholders.reduce(+ (placeholderMap, p) => {+ placeholderMap[p.name] = p.value;+ return placeholderMap;+ },+ {} as MessagePlaceholderValues,+ );++ const textVariables = promptVariables.reduce(+ (variableMap, v) => {+ variableMap[v.name] = v.value;+ return variableMap;+ },+ {} as Record<string, string>,+ );++ const compiledMessages = compileChatMessagesWithIds(+ messages,+ placeholderValues,+ textVariables,+ );++ // Filter empty messages (except tool calls), e.g. if placeholder value was empty+ return compiledMessages.filter(+ (m) =>+ m.content.length > 0 || ("toolCalls" in m && m.toolCalls && m.toolCalls.length > 0),+ );}function getOutputJson(diff --git a/web/src/features/playground/page/playground.tsx b/web/src/features/playground/page/playground.tsxindex 6f62afec30..4f8c202871 100644--- a/web/src/features/playground/page/playground.tsx+++ b/web/src/features/playground/page/playground.tsx@@ -1,6 +1,7 @@import { ModelParameters } from "@/src/components/ModelParameters";import { usePlaygroundContext } from "./context";import { Variables } from "./components/Variables";+import { MessagePlaceholders } from "./components/MessagePlaceholders";import { Messages } from "./components/Messages";import { PlaygroundTools } from "./components/PlaygroundTools";import { StructuredOutputSchemaSection } from "./components/StructuredOutputSchemaSection";@@ -25,7 +26,10 @@ export default function Playground() {<StructuredOutputSchemaSection /></div><div className="flex-grow overflow-y-auto">- <Variables />+ <div className="space-y-6">+ <Variables />+ <MessagePlaceholders />+ </div></div></div></div>diff --git a/web/src/features/playground/page/types.ts b/web/src/features/playground/page/types.tsindex 23671a2d60..e984e998e0 100644--- a/web/src/features/playground/page/types.ts+++ b/web/src/features/playground/page/types.ts@@ -1,11 +1,12 @@import {- type PromptVariable,type ChatMessage,- type UIModelParams,+ type LLMJSONSchema,type LlmSchema,- type LLMToolDefinition,type LlmTool,- type LLMJSONSchema,+ type LLMToolDefinition,+ type PlaceholderMessage,+ type PromptVariable,+ type UIModelParams,} from "@langfuse/shared";export type PlaygroundTool = LLMToolDefinition & {@@ -21,12 +22,19 @@ export type PlaygroundSchema = {existingLlmSchema?: LlmSchema;};+export type PlaceholderMessageFillIn = {+ name: string;+ value: ChatMessage[];+ isUsed: boolean;+};+export type PlaygroundCache = {- messages: ChatMessage[];+ messages: (ChatMessage | PlaceholderMessage)[];modelParams?: Partial<UIModelParams> &Pick<UIModelParams, "provider" | "model">;output?: string | null;promptVariables?: PromptVariable[];+ // TODO: also cache placeholders?tools?: PlaygroundTool[];structuredOutputSchema?: PlaygroundSchema | null;} | null;diff --git a/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx b/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsxindex b101c1ccbe..f078a7178a 100644--- a/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx+++ b/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx@@ -50,17 +50,31 @@ export const PromptChatMessages: React.FC<PromptChatMessagesProps> = ({}setMessages(- parsedMessages.data.map((message) => ({- ...message,- id: uuidv4(),- type: ChatMessageType.PublicAPICreated,- })),+ parsedMessages.data.map((message) => {+ const id = uuidv4();+ // TODO: clean up - Placeholder messages could also be API created..+ if ('type' in message && message.type === ChatMessageType.Placeholder) {+ return {+ ...message,+ id,+ type: ChatMessageType.Placeholder,+ } as ChatMessageWithId;+ } else {+ return {+ ...message,+ id,+ type: ChatMessageType.PublicAPICreated,+ } as ChatMessageWithId;+ }+ }),);const customRoles = parsedMessages.data.reduce((acc, message) => {- const { role } = message;- if (ChatMessageDefaultRoleSchema.safeParse(role).error) {- acc.add(role);+ if ('role' in message) {+ const { role } = message;+ if (ChatMessageDefaultRoleSchema.safeParse(role).error) {+ acc.add(role);+ }}return acc;}, new Set<string>());diff --git a/web/src/features/prompts/components/NewPromptForm/validation.ts b/web/src/features/prompts/components/NewPromptForm/validation.tsindex 3da7360260..b02175a424 100644--- a/web/src/features/prompts/components/NewPromptForm/validation.ts+++ b/web/src/features/prompts/components/NewPromptForm/validation.ts@@ -1,8 +1,10 @@import { z } from "zod/v4";import {+ ChatMessageType,+ PlaceholderMessageSchema,PromptChatMessageListSchema,- TextPromptContentSchema,PromptNameSchema,+ TextPromptContentSchema,COMMIT_MESSAGE_MAX_LENGTH,PromptType,} from "@langfuse/shared";@@ -23,10 +25,23 @@ const NewPromptBaseSchema = z.object({const NewChatPromptSchema = NewPromptBaseSchema.extend({type: z.literal(PromptType.Chat),- chatPrompt: PromptChatMessageListSchema.refine(- (messages) => messages.every((message) => message.content.length > 0),- "Enter a chat message or remove the empty message",- ),+ chatPrompt: z.array(z.any())+ .refine(+ (messages: Array<{ type?: ChatMessageType; content?: string }>) =>+ messages.every((message) => {+ const isPlaceholder = message?.type === ChatMessageType.Placeholder;+ return !isPlaceholder || PlaceholderMessageSchema.safeParse(message).success;+ }),+ "Placeholder name must start with a letter and contain only alphanumeric characters and underscores"+ )+ .refine(+ (messages: Array<{ type?: ChatMessageType; content?: string }>) =>+ messages.every((message) => {+ const isPlaceholder = message?.type === ChatMessageType.Placeholder;+ return isPlaceholder || Boolean(message?.content?.trim()?.length);+ }),+ "Enter a chat message or remove the empty message"+ ),textPrompt: z.string(),});diff --git a/worker/src/features/experiments/experimentService.ts b/worker/src/features/experiments/experimentService.tsindex 305fb3eb6b..3c49299e2f 100644--- a/worker/src/features/experiments/experimentService.ts+++ b/worker/src/features/experiments/experimentService.ts@@ -3,20 +3,24 @@ import {ChatMessageRole,LLMApiKeySchema,logger,- PromptContent,+ type PromptContent,ExperimentMetadataSchema,PromptContentSchema,DatasetRunItemUpsertQueue,ChatMessageType,- ChatMessage,+ type ChatMessage,PromptService,+ compileChatMessages,+ extractPlaceholderNames,+ type MessagePlaceholderValues,+ type PromptMessage,} from "@langfuse/shared/src/server";import { kyselyPrisma, prisma } from "@langfuse/shared/src/db";-import { ExperimentCreateEventSchema } from "@langfuse/shared/src/server";+import { type ExperimentCreateEventSchema } from "@langfuse/shared/src/server";import {InvalidRequestError,LangfuseNotFoundError,- Prisma,+ type Prisma,extractVariables,datasetItemMatchesVariable,stringifyValue,@@ -24,7 +28,7 @@ import {import { backOff } from "exponential-backoff";import { callLLM } from "../../features/utilities";import { QueueJobs, redis } from "@langfuse/shared/src/server";-import { randomUUID } from "crypto";+import { randomUUID } from "node:crypto";import { v4 } from "uuid";import { compileHandlebarString } from "../../features/utilities";import { DatasetStatus } from "../../../../packages/shared/dist/prisma/generated/types";@@ -64,13 +68,62 @@ const replaceVariablesInPrompt = (type: ChatMessageType.System as const,},];- } else {- return prompt.map((message) => ({- ...message,- content: processContent(message.content),+ }++ const placeholderNames = extractPlaceholderNames(prompt as PromptMessage[]);+ const placeholderValues: MessagePlaceholderValues = {};+ // itemInput to placeholderValues+ for (const placeholderName of placeholderNames) {+ if (!(placeholderName in itemInput)) {+ // TODO: handle missing placeholder values+ // throw new Error(`Missing placeholder value for '${placeholderName}'`);+ continue;+ }+ const value = itemInput[placeholderName];++ // for stringified arrays (e.g. from dataset processing)+ let actualValue = value;+ if (typeof value === 'string') {+ try {+ actualValue = JSON.parse(value);+ } catch (_e) {+ throw new Error(`Invalid placeholder value for '${placeholderName}': unable to parse JSON`);+ }+ }++ if (!Array.isArray(actualValue)) {+ throw new Error(`Placeholder '${placeholderName}' must be an array of messages`);+ }++ const validMessages = actualValue.every(msg =>+ typeof msg === 'object' &&+ msg !== null &&+ 'role' in msg &&+ 'content' in msg+ );+ if (!validMessages) {+ throw new Error(`Invalid placeholder value for '${placeholderName}': messages must have 'role' and 'content' properties`);+ }++ placeholderValues[placeholderName] = actualValue.map(msg => ({+ ...msg,type: ChatMessageType.PublicAPICreated as const,}));}++ const compiledMessages = compileChatMessages(+ prompt as PromptMessage[],+ placeholderValues,+ {}+ );++ // TODO: validate correctness+ // handlebars variable substitution to all messages+ return compiledMessages.map((message) => ({+ ...message,+ content: processContent(message.content),+ type: ChatMessageType.PublicAPICreated as const,+ }));};const validateDatasetItem = (@@ -203,14 +256,20 @@ export const createExperimentJob = async ({: JSON.stringify(prompt.prompt),);+ // also extract placeholder names if prompt is an array+ const placeholderNames = prompt?.type !== "text" && Array.isArray(validatedPrompt.data)+ ? extractPlaceholderNames(validatedPrompt.data as PromptMessage[])+ : [];+ const allVariables = [...extractedVariables, ...placeholderNames];+// validate dataset items against prompt configurationconst validatedDatasetItems = datasetItems- .filter(({ input }) => validateDatasetItem(input, extractedVariables))+ .filter(({ input }) => validateDatasetItem(input, allVariables)).map((datasetItem) => ({...datasetItem,input: parseDatasetItemInput(datasetItem.input as Prisma.JsonObject, // this is safe because we already filtered for valid input- extractedVariables,+ allVariables,),}));