:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(llma): add template variables to the playground (#109146)
Juraj Majerik72a4a9ed6478
diff --git a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsxindex 4b3cef481781..67d11f2bb7a6 100644--- a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx+++ b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx@@ -60,6 +60,7 @@ import {} from './llmPlaygroundPromptsLogic'import { llmPlaygroundRunLogic, type ComparisonItem, type UsageSummary } from './llmPlaygroundRunLogic'import { PlaygroundSaveMenu } from './PlaygroundSaveMenu'+import { PlaygroundVariablesPanel } from './PlaygroundVariablesPanel'// Cap inline JSON previews at 20 lines so they don't dominate the layoutconst INLINE_JSON_MAX_LINES = 20@@ -247,6 +248,7 @@ function PlaygroundLayout(): JSX.Element {<div className="flex flex-1 min-h-0 flex-col gap-4"><RateLimitBanner /><SubscriptionRequiredBanner />+ <PlaygroundVariablesPanel /><section className="rounded overflow-hidden min-h-0 flex flex-1 flex-col bg-transparent">{sourceSetupLoading ? (diff --git a/products/ai_observability/frontend/playground/PlaygroundVariablesPanel.tsx b/products/ai_observability/frontend/playground/PlaygroundVariablesPanel.tsxnew file mode 100644index 000000000000..1953a1f122db--- /dev/null+++ b/products/ai_observability/frontend/playground/PlaygroundVariablesPanel.tsx@@ -0,0 +1,64 @@+import { useActions, useValues } from 'kea'++import { IconChevronRight } from '@posthog/icons'+import { LemonButton, LemonTextArea } from '@posthog/lemon-ui'++import { AnimatedCollapsible } from 'lib/components/AnimatedCollapsible'++import { llmPlaygroundPromptsLogic } from './llmPlaygroundPromptsLogic'+import { llmPlaygroundVariablesLogic } from './llmPlaygroundVariablesLogic'+import { getVariableValue } from './playgroundTemplating'++export function PlaygroundVariablesPanel(): JSX.Element {+ const { detectedVariables, variableValues } = useValues(llmPlaygroundVariablesLogic)+ const { setVariableValue } = useActions(llmPlaygroundVariablesLogic)+ const { collapsedSections } = useValues(llmPlaygroundPromptsLogic)+ const { toggleCollapsed } = useActions(llmPlaygroundPromptsLogic)++ const collapsed = !!collapsedSections['variables']++ return (+ <div className="border rounded p-4 py-2 shrink-0">+ <div className={collapsed ? '' : 'mb-2'}>+ <LemonButton+ size="small"+ noPadding+ icon={+ <IconChevronRight className={`transition-transform ${collapsed ? 'rotate-0' : 'rotate-90'}`} />+ }+ onClick={() => toggleCollapsed('variables')}+ aria-expanded={!collapsed}+ data-attr="llma-playground-toggle-variables"+ >+ Variables{detectedVariables.length > 0 ? ` (${detectedVariables.length})` : ''}+ </LemonButton>+ </div>++ <AnimatedCollapsible collapsed={collapsed}>+ {detectedVariables.length === 0 ? (+ <p className="text-xs text-muted mb-1">+ Add a placeholder like <code>{'{{topic}}'}</code> to the system prompt or a message, then fill+ in a test value here. Values are applied when you run. Saved prompts keep the placeholders.+ </p>+ ) : (+ <div className="space-y-2 mb-2 max-h-80 overflow-y-auto pr-1">+ {detectedVariables.map((name) => (+ <div key={name} className="flex items-start gap-2">+ <code className="text-xs pt-2 whitespace-nowrap">{`{{${name}}}`}</code>+ <LemonTextArea+ className="text-sm flex-1"+ placeholder="Value"+ value={getVariableValue(variableValues, name)}+ onChange={(value) => setVariableValue(name, value)}+ minRows={1}+ maxRows={6}+ data-attr="llma-playground-variable-value"+ />+ </div>+ ))}+ </div>+ )}+ </AnimatedCollapsible>+ </div>+ )+}diff --git a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.tsindex 9f1192b10016..c418361c2d30 100644--- a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts+++ b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts@@ -17,6 +17,7 @@ import {llmPlaygroundRunLogic,mergeUsage,} from './llmPlaygroundRunLogic'+import { llmPlaygroundVariablesLogic } from './llmPlaygroundVariablesLogic'function setPlaygroundAccessLevel(level: AccessControlLevel): void {window.POSTHOG_APP_CONTEXT = {@@ -108,6 +109,37 @@ describe('llmPlaygroundRunLogic', () => {streamSpy.mockRestore()})+ it('sends variable-substituted content while the editor keeps the raw template', async () => {+ const streamSpy = jest.spyOn(api, 'stream').mockImplementation(async () => {})++ const logic = llmPlaygroundRunLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ llmPlaygroundPromptsLogic.actions.setModel('gpt-5-mini')+ llmPlaygroundPromptsLogic.actions.setSystemPrompt('You answer questions about {{topic}}.')+ llmPlaygroundPromptsLogic.actions.setMessages([+ { role: 'user', content: 'Tell me about {{topic}} and {{missing}}' },+ ])+ llmPlaygroundVariablesLogic.actions.setVariableValue('topic', 'penguins')+ llmPlaygroundRunLogic.actions.submitPrompt()++ await expectLogic(logic).toFinishAllListeners()++ expect(streamSpy).toHaveBeenCalledTimes(1)+ // Filled variables resolve, unfilled ones stay in place (same as SDK compile)+ expect(streamSpy.mock.calls[0][1]?.data).toMatchObject({+ system: 'You answer questions about penguins.',+ messages: [{ role: 'user', content: 'Tell me about penguins and {{missing}}' }],+ })+ // Substitution must not write back into the editor state+ expect(llmPlaygroundPromptsLogic.values.systemPrompt).toBe('You answer questions about {{topic}}.')+ expect(llmPlaygroundPromptsLogic.values.messages[0].content).toBe('Tell me about {{topic}} and {{missing}}')++ logic.unmount()+ streamSpy.mockRestore()+ })+it('does not run a completion without editor access to the playground and explains why', async () => {// Both message textareas submit on Cmd+Enter, bypassing the Run button's disabledReason,// so the gate has to hold in the logic itself.diff --git a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.tsindex 9bcc62c1e483..19f1aa1fd755 100644--- a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts+++ b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts@@ -15,7 +15,9 @@ import { llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'import type { LLMProviderKey } from '../settings/llmProviderKeysLogic'import { llmPlaygroundModelLogic } from './llmPlaygroundModelLogic'import { llmPlaygroundPromptsLogic, type Message, type PromptConfig } from './llmPlaygroundPromptsLogic'+import { llmPlaygroundVariablesLogic } from './llmPlaygroundVariablesLogic'import { resolveProviderKeyForPrompt } from './playgroundModelMatching'+import { substituteVariables } from './playgroundTemplating'interface ToolCallChunk {id?: string@@ -172,6 +174,7 @@ export interface llmPlaygroundRunLogicValues {activeProviderKeyId: string | null // llmPlaygroundModelLogiceffectiveModelOptions: ModelOption[] // llmPlaygroundModelLogicpromptConfigs: PromptConfig[] // llmPlaygroundPromptsLogic+ variableValues: Record<string, string> // llmPlaygroundVariablesLogicproviderKeys: LLMProviderKey[] // llmProviderKeysLogiccomparisonItems: ComparisonItem[]rateLimitedUntil: number | null@@ -230,6 +233,8 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([['effectiveModelOptions', 'activeProviderKeyId'],llmProviderKeysLogic,['providerKeys'],+ llmPlaygroundVariablesLogic,+ ['variableValues'],],actions: [llmPlaygroundPromptsLogic, ['resetPlayground']],})),@@ -340,6 +345,14 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([currentAbortController = abortControllertry {const runs = runnablePrompts.map(async ({ prompt, index, messagesToSend }) => {+ // Resolve {{variables}} only in what is sent; the editors keep the raw template.+ const resolvedSystemPrompt = substituteVariables(prompt.systemPrompt, values.variableValues)+ const resolvedMessages = messagesToSend.map(+ (m: Message): Message => ({+ ...m,+ content: substituteVariables(m.content, values.variableValues),+ })+ )const liveItemId = uuid()let responseUsage: UsageSummary = {}let ttftMs: number | null = null@@ -360,8 +373,8 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([promptId: prompt.id,promptLabel: `Prompt ${index + 1}`,model: prompt.model,- systemPrompt: prompt.systemPrompt,- requestMessages: messagesToSend,+ systemPrompt: resolvedSystemPrompt,+ requestMessages: resolvedMessages,response: responseText,reasoning: responseReasoning,toolCalls,@@ -408,8 +421,8 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([selectedModelProvider = selectedModel.provider.toLowerCase()const requestData: Record<string, unknown> = {- system: prompt.systemPrompt,- messages: messagesToSend+ system: resolvedSystemPrompt,+ messages: resolvedMessages.filter((m: Message) => m.role === 'user' || m.role === 'assistant').map((m: Message) => ({ role: m.role, content: m.content })),model: selectedModel.id,diff --git a/products/ai_observability/frontend/playground/llmPlaygroundVariablesLogic.test.ts b/products/ai_observability/frontend/playground/llmPlaygroundVariablesLogic.test.tsnew file mode 100644index 000000000000..d40ef53c2019--- /dev/null+++ b/products/ai_observability/frontend/playground/llmPlaygroundVariablesLogic.test.ts@@ -0,0 +1,54 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import { createPromptConfig, llmPlaygroundPromptsLogic } from './llmPlaygroundPromptsLogic'+import { llmPlaygroundVariablesLogic } from './llmPlaygroundVariablesLogic'++describe('llmPlaygroundVariablesLogic', () => {+ beforeEach(() => {+ initKeaTests()+ })++ it('detects variables across all comparison panels and shares values by name', async () => {+ // Detection that only reads the active panel would hide panel 2's variables,+ // and per-panel values would break the "fill {{topic}} once" comparison flow.+ const logic = llmPlaygroundVariablesLogic()+ logic.mount()++ llmPlaygroundPromptsLogic.actions.setPromptConfigs([+ createPromptConfig({+ systemPrompt: 'Answer about {{topic}}.',+ messages: [{ role: 'user', content: '{{question}}' }],+ }),+ createPromptConfig({ systemPrompt: 'Be {{tone}} about {{topic}}.', messages: [] }),+ ])++ await expectLogic(logic).toMatchValues({+ detectedVariables: ['topic', 'question', 'tone'],+ unfilledVariables: ['topic', 'question', 'tone'],+ })++ logic.actions.setVariableValue('topic', 'penguins')++ await expectLogic(logic).toMatchValues({+ unfilledVariables: ['question', 'tone'],+ })++ logic.unmount()+ })++ it('clears values when a new source loads into the playground', async () => {+ // Without this, loading a different saved prompt that reuses a variable+ // name silently sends the previous prompt's value.+ const logic = llmPlaygroundVariablesLogic()+ logic.mount()++ logic.actions.setVariableValue('topic', 'penguins')+ llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({})++ await expectLogic(logic).toMatchValues({ variableValues: {} })++ logic.unmount()+ })+})diff --git a/products/ai_observability/frontend/playground/llmPlaygroundVariablesLogic.ts b/products/ai_observability/frontend/playground/llmPlaygroundVariablesLogic.tsnew file mode 100644index 000000000000..68f88a655bb5--- /dev/null+++ b/products/ai_observability/frontend/playground/llmPlaygroundVariablesLogic.ts@@ -0,0 +1,105 @@+import { MakeLogicType, actions, connect, kea, path, props, reducers, selectors } from 'kea'++import { llmPlaygroundPromptsLogic, type PromptConfig } from './llmPlaygroundPromptsLogic'+import { extractVariables, getVariableValue } from './playgroundTemplating'++export type LLMPlaygroundVariablesLogicProps = Record<string, never>++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface llmPlaygroundVariablesLogicValues {+ promptConfigs: PromptConfig[] // llmPlaygroundPromptsLogic+ detectedVariables: string[]+ unfilledVariables: string[]+ variableValues: Record<string, string>+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface llmPlaygroundVariablesLogicActions {+ resetPlayground: () => {+ value: true+ } // llmPlaygroundPromptsLogic+ setupPlaygroundFromEvent: (payload: import('./llmPlaygroundPromptsLogic').PlaygroundSetupPayload) => {+ payload: import('./llmPlaygroundPromptsLogic').PlaygroundSetupPayload+ } // llmPlaygroundPromptsLogic+ setVariableValue: (+ name: string,+ value: string+ ) => {+ name: string+ value: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface llmPlaygroundVariablesLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ detectedVariables: (promptConfigs: PromptConfig[]) => string[]+ unfilledVariables: (detectedVariables: string[], variableValues: Record<string, string>) => string[]+ }+}++export type llmPlaygroundVariablesLogicType = MakeLogicType<+ llmPlaygroundVariablesLogicValues,+ llmPlaygroundVariablesLogicActions,+ LLMPlaygroundVariablesLogicProps,+ llmPlaygroundVariablesLogicMeta+>++export const llmPlaygroundVariablesLogic = kea<llmPlaygroundVariablesLogicType>([+ path(['products', 'ai_observability', 'frontend', 'playground', 'llmPlaygroundVariablesLogic']),+ props({} as LLMPlaygroundVariablesLogicProps),++ connect(() => ({+ values: [llmPlaygroundPromptsLogic, ['promptConfigs']],+ actions: [llmPlaygroundPromptsLogic, ['resetPlayground', 'setupPlaygroundFromEvent']],+ })),++ actions({+ setVariableValue: (name: string, value: string) => ({ name, value }),+ }),++ reducers({+ // Values are keyed by name and shared across comparison panels. Entries for+ // variables no longer present in any prompt are kept, so deleting and retyping+ // a placeholder does not lose its value. A future dataset row can hydrate this+ // record wholesale.+ variableValues: [+ {} as Record<string, string>,+ {+ resetPlayground: () => ({}),+ // A new source (saved prompt, evaluation, trace) starts a fresh test+ // context; values from the previous prompt must not silently fill+ // same-named variables in the new one.+ setupPlaygroundFromEvent: () => ({}),+ setVariableValue: (+ state: Record<string, string>,+ { name, value }: { name: string; value: string }+ ) => ({ ...state, [name]: value }),+ },+ ],+ }),++ selectors({+ detectedVariables: [+ (s) => [s.promptConfigs],+ (promptConfigs: PromptConfig[]): string[] => {+ const names: string[] = []+ for (const prompt of promptConfigs) {+ for (const text of [prompt.systemPrompt, ...prompt.messages.map((m) => m.content)]) {+ for (const name of extractVariables(text)) {+ if (!names.includes(name)) {+ names.push(name)+ }+ }+ }+ }+ return names+ },+ ],+ unfilledVariables: [+ (s) => [s.detectedVariables, s.variableValues],+ (detectedVariables: string[], variableValues: Record<string, string>): string[] =>+ detectedVariables.filter((name) => !getVariableValue(variableValues, name)),+ ],+ }),+])diff --git a/products/ai_observability/frontend/playground/playgroundTemplating.test.ts b/products/ai_observability/frontend/playground/playgroundTemplating.test.tsnew file mode 100644index 000000000000..d39a2f499a74--- /dev/null+++ b/products/ai_observability/frontend/playground/playgroundTemplating.test.ts@@ -0,0 +1,29 @@+import { extractVariables, substituteVariables } from './playgroundTemplating'++describe('playgroundTemplating', () => {+ // The syntax must stay identical to the SDK compile helpers (@posthog/ai and+ // posthog-python): if these cases drift, a prompt saved from the playground+ // compiles differently in production.+ it.each([+ ['names allow word chars, dots and hyphens', 'Hi {{user.first-name}}, ask {{q_1}}', ['user.first-name', 'q_1']],+ ['repeats are deduped, order of first appearance kept', '{{b}} {{a}} {{b}}', ['b', 'a']],+ ['whitespace inside braces is literal, same as the SDKs', '{{ spaced }} {{x }}', []],+ ['empty and unclosed braces are literal', '{{}} {{unclosed and {b}', []],+ ])('extractVariables: %s', (_name, text, expected) => {+ expect(extractVariables(text)).toEqual(expected)+ })++ it('substitutes every occurrence and leaves unfilled placeholders intact', () => {+ expect(substituteVariables('{{a}} and {{b}} and {{a}}', { a: 'x' })).toBe('x and {{b}} and x')+ expect(substituteVariables('{{a}}', { a: '' })).toBe('{{a}}')+ // Object.prototype keys must not leak function source text into the prompt+ expect(substituteVariables('{{constructor}} {{toString}}', {})).toBe('{{constructor}} {{toString}}')+ })++ it('substitutes multiline JSON values containing replacement patterns literally', () => {+ // `$&` and `$'` are special in String.replace string form; a naive+ // implementation corrupts JSON values that contain them.+ const value = '{"amount": "$& USD",\n "note": "$\' end"}'+ expect(substituteVariables('data: {{payload}}', { payload: value })).toBe(`data: ${value}`)+ })+})diff --git a/products/ai_observability/frontend/playground/playgroundTemplating.ts b/products/ai_observability/frontend/playground/playgroundTemplating.tsnew file mode 100644index 000000000000..663daa3fc95d--- /dev/null+++ b/products/ai_observability/frontend/playground/playgroundTemplating.ts@@ -0,0 +1,39 @@+/**+ * Template variable syntax shared with the SDK `compile` helpers+ * (posthog-js `packages/ai/src/prompts.ts`, posthog-python `posthog/ai/prompts.py`).+ * A variable is `{{name}}` where name is letters, digits, `_`, `-` or `.` — no+ * whitespace inside the braces. Anything else, including `{{ spaced }}` and+ * unbalanced braces, is literal text. Keep this regex identical to the SDKs so a+ * prompt saved from the playground compiles the same way in production.+ */+const TEMPLATE_VARIABLE_REGEX = /\{\{([\w.-]+)\}\}/g++/** Distinct variable names in order of first appearance. */+export function extractVariables(text: string): string[] {+ const names: string[] = []+ for (const match of text.matchAll(TEMPLATE_VARIABLE_REGEX)) {+ if (!names.includes(match[1])) {+ names.push(match[1])+ }+ }+ return names+}++/**+ * Own-property read of a variable value. A plain record inherits `constructor`,+ * `toString` and the rest of Object.prototype, so a bare `values[name]` would+ * hand function source text to a `{{constructor}}` placeholder.+ */+export function getVariableValue(values: Record<string, string>, name: string): string {+ return Object.prototype.hasOwnProperty.call(values, name) ? values[name] : ''+}++/**+ * Replace each `{{name}}` with its value. A variable with no value (or an empty+ * one) stays in place, matching the SDK `compile` behavior, so a forgotten value+ * is visible in the model's input instead of silently becoming an empty string.+ */+export function substituteVariables(text: string, values: Record<string, string>): string {+ // Function replacer so values containing `$&`-style patterns substitute literally+ return text.replace(TEMPLATE_VARIABLE_REGEX, (match, name: string) => getVariableValue(values, name) || match)+}