🪢 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(playground): allow arbitrary values for placeholders in playground (#7768)
Nimarbfdbd93997b3
diff --git a/CLAUDE.md b/CLAUDE.mdindex aa6d23574c..5efb098c2c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -189,3 +189,6 @@ To get a project, use the `get_project` capability with the full project name as## TypeScript Best Practices- In TypeScript, if possible, don't use the `any` type++## General Coding Guidelines+- For easier code reviews, prefer not to move functions etc around within a file unless necessary or instructed to do sodiff --git a/packages/shared/src/server/llm/compileChatMessages.ts b/packages/shared/src/server/llm/compileChatMessages.tsindex 51792a85bc..e7c3f0e2a6 100644--- a/packages/shared/src/server/llm/compileChatMessages.ts+++ b/packages/shared/src/server/llm/compileChatMessages.ts@@ -7,10 +7,9 @@ import {type PromptChatMessageSchema,type ChatMessageWithId,type ChatMessageWithIdNoPlaceholders,- ChatMessageSchema,} from "./types";-export type MessagePlaceholderValues = Record<string, ChatMessage[]>;+export type MessagePlaceholderValues = Record<string, unknown[]>;export type PromptMessage = z.infer<typeof PromptChatMessageSchema>;export function isPlaceholder(@@ -19,10 +18,6 @@ export function isPlaceholder(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>,@@ -54,14 +49,17 @@ function expandPlaceholder();}- 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`,- );+ // Allow arbitrary objects - just pass them through as ChatMessage+ // Users might want to use ChatML with placeholders for any message structure+ return replacementMessages.map((replacementMsg) => {+ if (typeof replacementMsg === "object" && replacementMsg !== null) {+ return replacementMsg as ChatMessage;}- }- return replacementMessages;++ throw new Error(+ `Invalid message in placeholder '${placeholder.name}': expected object but got ${typeof replacementMsg}`,+ );+ });}export function compileChatMessages(@@ -81,7 +79,7 @@ export function compileChatMessages(}return expandedMessages.map((message) => {- if (!message.content) {+ if (!message.content || typeof message.content !== "string") {return message;}@@ -94,7 +92,7 @@ export function compileChatMessages(export function compileChatMessagesWithIds(messages: ChatMessageWithId[],- placeholderValues: Record<string, ChatMessage[]>,+ placeholderValues: MessagePlaceholderValues,textVariables?: Record<string, string>,): ChatMessageWithIdNoPlaceholders[] {// TODO: check, is it even important to retain the IDs?@@ -114,7 +112,7 @@ export function compileChatMessagesWithIds(}return expandedMessages.map((message) => {- if (!message.content) {+ if (!message.content || typeof message.content !== "string") {return message;}diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.tsindex b225b5c047..590176d41d 100644--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts@@ -158,28 +158,47 @@ export async function fetchLLMCompletion(finalCallbacks = finalCallbacks.length > 0 ? finalCallbacks : undefined;+ // Helper function to safely stringify content+ const safeStringify = (content: any): string => {+ try {+ return JSON.stringify(content);+ } catch {+ return "[Unserializable content]";+ }+ };+let finalMessages: BaseMessage[];// VertexAI requires at least 1 user messageif (modelParams.adapter === LLMAdapter.VertexAI && messages.length === 1) {- finalMessages = [new HumanMessage(messages[0].content)];+ const safeContent =+ typeof messages[0].content === "string"+ ? messages[0].content+ : JSON.stringify(messages[0].content);+ finalMessages = [new HumanMessage(safeContent)];} else {finalMessages = messages.map((message) => {+ // For arbitrary content types, convert to string safely+ const safeContent =+ typeof message.content === "string"+ ? message.content+ : safeStringify(message.content);+if (message.role === ChatMessageRole.User)- return new HumanMessage(message.content);+ return new HumanMessage(safeContent);if (message.role === ChatMessageRole.System ||message.role === ChatMessageRole.Developer)- return new SystemMessage(message.content);+ return new SystemMessage(safeContent);if (message.type === ChatMessageType.ToolResult)return new ToolMessage({- content: message.content,+ content: safeContent,tool_call_id: message.toolCallId,});return new AIMessage({- content: message.content,+ content: safeContent,tool_calls:message.type === ChatMessageType.AssistantToolCall? (message.toolCalls as any)diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.tsindex 2298089ad9..8e716a32ee 100644--- a/packages/shared/src/server/llm/types.ts+++ b/packages/shared/src/server/llm/types.ts@@ -196,7 +196,7 @@ export const ChatMessageSchema = z.union([z.object({role: z.union([ChatMessageDefaultRoleSchema, z.string()]), // Users may ingest any string as role via API/SDK- content: z.string(),+ content: z.union([z.string(), z.array(z.any()), z.any()]), // Support arbitrary content types for message placeholders}).transform((msg) => {return {diff --git a/web/src/__tests__/compileChatMessages.servertest.ts b/web/src/__tests__/compileChatMessages.servertest.tsindex c63876ddc0..66f7725102 100644--- a/web/src/__tests__/compileChatMessages.servertest.ts+++ b/web/src/__tests__/compileChatMessages.servertest.ts@@ -65,35 +65,48 @@ describe("compileChatMessages", () => {}).toThrow("Missing value for message placeholder: missing_placeholder");});- it("should throw error when placeholder messages lack required properties", () => {+ it("should allow arbitrary placeholder fill-in values", () => {const promptTemplate = [+ { role: "system", content: "You are a helpful assistant." },{type: ChatMessageType.Placeholder,- name: "invalid_messages",+ name: "arbitrary_messages",},];- // Test missing role property- const placeholderValuesNoRole = {- invalid_messages: [{ content: "Hello" }],+ // Test with arbitrary objects (non-role/content structure)+ const placeholderValues = {+ arbitrary_messages: [+ { type: "custom", data: ["some data", "and some more data!"], id: 123 },+ { action: "click", target: "button", value: "submit" },+ { role: "user", content: "This still works" }, // Mixed with standard format+ ],};- expect(() => {- compileChatMessages(promptTemplate, placeholderValuesNoRole);- }).toThrow(- "Invalid message format in placeholder 'invalid_messages': messages must have 'role' and 'content' properties",+ const compiledMessages = compileChatMessages(+ promptTemplate,+ placeholderValues,);- // 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",- );+ expect(compiledMessages).toHaveLength(4);+ expect(compiledMessages[0]).toEqual({+ role: "system",+ content: "You are a helpful assistant.",+ });+ expect(compiledMessages[1]).toEqual({+ type: "custom",+ data: ["some data", "and some more data!"],+ id: 123,+ });+ expect(compiledMessages[2]).toEqual({+ action: "click",+ target: "button",+ value: "submit",+ });+ expect(compiledMessages[3]).toEqual({+ role: "user",+ content: "This still works",+ });});it("should compile placeholders without applying text substitutions when no variables provided", () => {diff --git a/web/src/features/playground/page/components/MessagePlaceholderComponent.tsx b/web/src/features/playground/page/components/MessagePlaceholderComponent.tsxindex 6817fc42f8..80624f2718 100644--- a/web/src/features/playground/page/components/MessagePlaceholderComponent.tsx+++ b/web/src/features/playground/page/components/MessagePlaceholderComponent.tsx@@ -2,10 +2,7 @@ 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 { type ChatMessage } from "@langfuse/shared";import { usePlaygroundContext } from "../context";import { type PlaceholderMessageFillIn } from "../types";@@ -32,17 +29,27 @@ export const MessagePlaceholderComponent: React.FC<{(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.",- );+ // Basic validation: must be an array of objects+ if (!Array.isArray(parsed)) {+ setError("Input must be an array of objects");+ return;}++ // Check that all items are objects+ const allObjects = parsed.every(+ (item) =>+ typeof item === "object" && item !== null && !Array.isArray(item),+ );++ if (!allObjects) {+ setError("All items must be objects");+ return;+ }++ // Allow arbitrary objects - no strict role/content validation+ updateMessagePlaceholderValue(name, parsed as ChatMessage[]);+ setError(null);} catch {setError("Invalid JSON format");}diff --git a/web/src/features/playground/page/context/index.tsx b/web/src/features/playground/page/context/index.tsxindex 6987413d7c..ee3e8a7752 100644--- a/web/src/features/playground/page/context/index.tsx+++ b/web/src/features/playground/page/context/index.tsx@@ -23,7 +23,6 @@ import {ToolCallResponseSchema,type UIModelParams,type ToolCallResponse,- type LLMToolDefinition,type LLMToolCall,ChatMessageType,type ChatMessage,@@ -138,7 +137,12 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({structuredOutputSchema: cachedStructuredOutputSchema,} = playgroundCache;- setMessages(cachedMessages.map((m) => ({ ...m, id: uuidv4() })));+ setMessages(+ cachedMessages.map((m) => ({+ ...m,+ id: "id" in m && typeof m.id === "string" ? m.id : uuidv4(),+ })),+ );if (cachedOutput) {// Try parsing a previous output with tool calls@@ -291,7 +295,9 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({messagePlaceholders,);const leftOverVariables = extractVariables(- finalMessages.map((m) => m.content).join("\n"),+ finalMessages+ .map((m) => (typeof m.content === "string" ? m.content : ""))+ .join("\n"),);if (!modelParams.provider.value || !modelParams.model.value) {@@ -732,18 +738,28 @@ function getFinalMessages();// 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),- );+ return compiledMessages.filter((m) => {+ // Standard ChatMessage filtering+ if (typeof m.content === "string") {+ return (+ m.content.length > 0 ||+ ("toolCalls" in m &&+ m.toolCalls &&+ Array.isArray(m.toolCalls) &&+ m.toolCalls.length > 0)+ );+ }++ // For arbitrary objects, keep them (assume they have meaningful content)+ return true;+ });}function getOutputJson(output: string,messages: ChatMessageWithId[],modelParams: UIModelParams,- tools: LLMToolDefinition[],+ tools: PlaygroundTool[],structuredOutputSchema: PlaygroundSchema | null,) {return JSON.stringify(diff --git a/worker/src/features/experiments/experimentService.ts b/worker/src/features/experiments/experimentService.tsindex 575b0e1835..c48717cf9a 100644--- a/worker/src/features/experiments/experimentService.ts+++ b/worker/src/features/experiments/experimentService.ts@@ -102,16 +102,14 @@ const replaceVariablesInPrompt = ();}+ // Allow arbitrary objects - e.g. for users who want to pass ChatML messages.+ // Used to validate for role and content key existence here.const validMessages = actualValue.every(- (msg) =>- typeof msg === "object" &&- msg !== null &&- "role" in msg &&- "content" in msg,+ (msg) => typeof msg === "object" && msg !== null,);if (!validMessages) {throw new Error(- `Invalid placeholder value for '${placeholderName}': messages must have 'role' and 'content' properties`,+ `Invalid placeholder value for '${placeholderName}': all items must be objects`,);}@@ -129,7 +127,10 @@ const replaceVariablesInPrompt = (return compiledMessages.map((message) => ({...message,- content: processContent(message.content),+ // Only process content if it exists as string (for standard ChatMessages)+ ...(typeof message.content === "string" && {+ content: processContent(message.content),+ }),type: ChatMessageType.PublicAPICreated as const,}));};