Skip to content

: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.

feat(aio): add tool role and structured tool calls to playground messages (#112333)

Juraj Majerik989b8b4aa328
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 7767c7103d18..f249836caecc 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1756,6 +1756,10 @@ snapshots:
hash: v1.k794b7964.15fbabb08961435e861f16da95aaefeb3304c30b466197488268e540b8e20533.jfPtk0lZ5lhpRemspY5PLR53qxrhMfyR_WYQDEYWuvo
components-mcp-use-case-card--surveys-create--light:
hash: v1.k794b7964.2ce59a009bfce14f01a88f688627cf4b1def20c28ce5124288a54f9c62ffd3a6.wIhKopBY00iVCPnC9GB4QncFt-dCm8Gq9Uz6FYXBZ68
+ components-message-tool-calls-editor--editable-tool-calls--dark:
+ hash: v1.k794b7964.7adaad1e91b71d0b933afe541a20fd43112e39d56d6638abadfae6a830bb0c15.TxnbKwXIG1XbB5e4KpRJa4-PA-wl-kKOWbtX1ERVqLU
+ components-message-tool-calls-editor--editable-tool-calls--light:
+ hash: v1.k794b7964.4a10839159f5b3f989112539bb2a720f04460890fae5914a3516457e7cba92f3.Snir6e_iAMVVl1tdItfy70BRcAHw5Zem9Kk0ujjMQIo
components-navpanelproductpush--all-products--dark:
hash: v1.k794b7964.d6cc4da0e30950f4e3bf7338d86856529e48c45785bae5a85ccf4fd3ed7c3ad0.8n61Z9x6l3I3qfdAzk46yr7fAFHoYNdo3tjEKyJlcIo
components-navpanelproductpush--all-products--light:
@@ -2536,6 +2540,10 @@ snapshots:
hash: v1.k794b7964.e66bf82a582145f768e6a70a9696d7740cb012c2022c398b68a0311ef0aa8a37.yDQ1kPl_Hi9xOUuxr9j5k7-ZlW9fyhYL3VnQRYg0nMk
components-template-variable-text-area--filled-and-unfilled-variables--light:
hash: v1.k794b7964.1377bea2cf4a8e52c8da776a97346ea4c8c1becd10a9fe80abbe820d56d666e4.b5L2IxrKavjH9TYToZRloZVq1ZmlgYbvPU90Nc04Otw
+ components-tool-call-display--streamed-tool-call--dark:
+ hash: v1.k794b7964.5d1893cd81b904b00103ea1f5ccc2f6087b9cd55e93c6372ccf77a39102ec1b5.kVv0HwIqvf-w9Xn_R1hEMhy4NDNkqbiT2CJ7V8nP3fQ
+ components-tool-call-display--streamed-tool-call--light:
+ hash: v1.k794b7964.f0d2d11d7c55b1a1982e00b1b331e71616445300b8f892587ded56a153df673d.pu6VpTNncfZsmeCcjfXTKKGPPCBJy_xT5Qc4F7fqNws
components-tz-label--absolute-timestamp--dark:
hash: v1.k794b7964.e5939abb9b33f906d4d27d30344bb10dece07742fd0921be4d0875d2d977d81e.0x8wWYgIz71dN5jLN8DG2WgaaSA4lInr-a2JEd4MzuI
components-tz-label--absolute-timestamp--light:
diff --git a/products/ai_observability/backend/providers/formatters/test/test_openai_formatter.py b/products/ai_observability/backend/providers/formatters/test/test_openai_formatter.py
index 3ac878d120b9..fbdc5850ee5b 100644
--- a/products/ai_observability/backend/providers/formatters/test/test_openai_formatter.py
+++ b/products/ai_observability/backend/providers/formatters/test/test_openai_formatter.py
@@ -10,11 +10,15 @@ class TestConvertToOpenAIMessages:
"content": [
{"type": "text", "text": "Checking the weather."},
{"type": "tool_use", "id": "call_1", "name": "get_weather", "input": {"location": "Paris"}},
+ {"type": "tool_use", "id": "call_2", "name": "get_weather", "input": {"location": "Rome"}},
],
},
{
"role": "user",
- "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "Sunny, 21C"}],
+ "content": [
+ {"type": "tool_result", "tool_use_id": "call_1", "content": "Sunny, 21C"},
+ {"type": "tool_result", "tool_use_id": "call_2", "content": "Cloudy, 18C"},
+ ],
},
]
)
@@ -28,8 +32,14 @@ class TestConvertToOpenAIMessages:
"id": "call_1",
"type": "function",
"function": {"name": "get_weather", "arguments": '{"location": "Paris"}'},
- }
+ },
+ {
+ "id": "call_2",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": '{"location": "Rome"}'},
+ },
],
},
{"role": "tool", "tool_call_id": "call_1", "content": "Sunny, 21C"},
+ {"role": "tool", "tool_call_id": "call_2", "content": "Cloudy, 18C"},
]
diff --git a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx
index 9fc3de77409f..ffa0c7c84abc 100644
--- a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx
+++ b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx
@@ -59,9 +59,11 @@ import {
} from './llmPlaygroundPromptsLogic'
import { llmPlaygroundRunLogic, type ComparisonItem, type UsageSummary } from './llmPlaygroundRunLogic'
import { llmPlaygroundVariablesLogic } from './llmPlaygroundVariablesLogic'
+import { MessageToolCallsEditor } from './MessageToolCallsEditor'
import { PlaygroundSaveMenu } from './PlaygroundSaveMenu'
import { PlaygroundVariablesPanel } from './PlaygroundVariablesPanel'
import { TemplateVariableTextArea } from './TemplateVariableTextArea'
+import { ToolCallDisplay } from './ToolCallDisplay'
// Cap inline JSON previews at 20 lines so they don't dominate the layout
const INLINE_JSON_MAX_LINES = 20
@@ -370,13 +372,14 @@ function hasUsage(usage: UsageSummary | undefined): boolean {
function PromptResultCard({ item }: { item?: ComparisonItem }): JSX.Element {
const isStreaming = !!item && item.latencyMs == null && !item.error
const { addResultToConversation } = useActions(llmPlaygroundPromptsLogic)
- const canAddToConversation = !!item?.response && !item.error && !isStreaming
+ const hasToolCalls = !!item?.toolCalls?.length
+ const canAddToConversation = (!!item?.response || hasToolCalls) && !item?.error && !isStreaming
const handleAddToConversation = (): void => {
- if (!item?.response) {
+ if (!item || (!item.response && !item.toolCalls?.length)) {
return
}
- addResultToConversation(item.response, item.promptId)
+ addResultToConversation(item.response, item.toolCalls, item.promptId)
}
return (
@@ -424,18 +427,25 @@ function PromptResultCard({ item }: { item?: ComparisonItem }): JSX.Element {
<LemonMarkdown className="whitespace-pre-wrap break-words [&_img]:max-w-full [&_img]:h-auto [&_img]:rounded [&_img]:my-2">
{item.response}
</LemonMarkdown>
- ) : isStreaming ? (
+ ) : isStreaming && !hasToolCalls ? (
<div className="h-full flex items-center justify-center text-xs text-muted">
<div className="inline-flex items-center gap-2">
<span className="inline-block h-3.5 w-3.5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
<span>Generating response...</span>
</div>
</div>
- ) : (
+ ) : !hasToolCalls ? (
<span className="text-muted italic">No response</span>
+ ) : null}
+ {hasToolCalls && (
+ <div className={`space-y-2 ${item.response ? 'mt-2' : ''}`}>
+ {item.toolCalls?.map((toolCall) => (
+ <ToolCallDisplay key={toolCall.id} toolCall={toolCall} />
+ ))}
+ </div>
)}
</div>
- {(!!item.response || hasUsage(item.usage)) && (
+ {(!!item.response || hasToolCalls || hasUsage(item.usage)) && (
<MetadataHeader
className="mt-2 pt-2"
isError={item.error}
@@ -859,6 +869,8 @@ function getRoleDotClass(role: string): string {
return 'bg-[var(--color-green-500)]'
case 'system':
return 'bg-[var(--color-purple-500)]'
+ case 'tool':
+ return 'bg-[var(--color-orange-500)]'
default:
return 'bg-muted'
}
@@ -1030,7 +1042,15 @@ function MessageDisplay({
const handleRoleChange = (newRole: MessageRole): void => {
posthog.capture('llma playground message role changed', { from: message.role, to: newRole })
- updateMessage(index, { role: newRole }, promptId)
+ updateMessage(
+ index,
+ {
+ role: newRole,
+ ...(newRole !== 'assistant' ? { toolCalls: undefined } : {}),
+ ...(newRole !== 'tool' ? { toolCallId: undefined, toolName: undefined } : {}),
+ },
+ promptId
+ )
}
const handleContentChange = (newContent: string | undefined): void => {
@@ -1040,6 +1060,7 @@ function MessageDisplay({
const roleOptions: { label: string; value: MessageRole }[] = [
{ label: 'User', value: 'user' },
{ label: 'Assistant', value: 'assistant' },
+ { label: 'Tool', value: 'tool' },
]
const trimmedContent = message.content.trim()
@@ -1058,7 +1079,7 @@ function MessageDisplay({
noPadding
onClick={() => {
posthog.capture('llma playground response copied', {
- content_type: message.role === 'assistant' ? 'assistant_message' : 'user_message',
+ content_type: `${message.role}_message`,
})
void copyToClipboard(message.content, `${message.role} message`)
}}
@@ -1108,31 +1129,71 @@ function MessageDisplay({
<span className="text-xs text-muted truncate flex-1">
{message.content
? message.content.slice(0, 80) + (message.content.length > 80 ? '…' : '')
- : `Empty ${message.role} message`}
+ : message.toolCalls?.length
+ ? `${message.toolCalls.length} tool call${message.toolCalls.length === 1 ? '' : 's'}`
+ : `Empty ${message.role} message`}
</span>
)}
</div>
<AnimatedCollapsible collapsed={collapsed}>
- {useJsonEditor ? (
- <div className={`border rounded ${INLINE_JSON_MAX_HEIGHT_CLASS}`}>
- <JSONEditor
+ <div>
+ {message.role === 'tool' && (
+ <div className="flex gap-2 mb-2">
+ <LemonInput
+ size="small"
+ className="flex-1"
+ placeholder="Tool name"
+ value={message.toolName ?? ''}
+ onChange={(value) => updateMessage(index, { toolName: value }, promptId)}
+ data-attr="llma-playground-tool-result-name"
+ />
+ <LemonInput
+ size="small"
+ className="flex-1 font-mono"
+ placeholder="Tool call id"
+ value={message.toolCallId ?? ''}
+ onChange={(value) => updateMessage(index, { toolCallId: value }, promptId)}
+ data-attr="llma-playground-tool-result-call-id"
+ />
+ </div>
+ )}
+ {useJsonEditor ? (
+ <div className={`border rounded ${INLINE_JSON_MAX_HEIGHT_CLASS}`}>
+ <JSONEditor
+ value={message.content}
+ onChange={handleContentChange}
+ defaultNumberOfLines={2}
+ maxNumberOfLines={INLINE_JSON_MAX_LINES}
+ />
+ </div>
+ ) : (
+ <TemplateVariableTextArea
+ placeholder={
+ message.role === 'tool'
+ ? 'Enter the tool result here...'
+ : `Enter ${message.role} message here...`
+ }
value={message.content}
onChange={handleContentChange}
- defaultNumberOfLines={2}
- maxNumberOfLines={INLINE_JSON_MAX_LINES}
+ unfilledVariables={unfilledVariables}
+ minRows={2}
+ onPressCmdEnter={() => submitPrompt()}
/>
- </div>
- ) : (
- <TemplateVariableTextArea
- placeholder={`Enter ${message.role} message here...`}
- value={message.content}
- onChange={handleContentChange}
- unfilledVariables={unfilledVariables}
- minRows={2}
- onPressCmdEnter={() => submitPrompt()}
- />
- )}
+ )}
+ {message.role === 'assistant' && (
+ <MessageToolCallsEditor
+ toolCalls={message.toolCalls ?? []}
+ onChange={(toolCalls) =>
+ updateMessage(
+ index,
+ { toolCalls: toolCalls.length > 0 ? toolCalls : undefined },
+ promptId
+ )
+ }
+ />
+ )}
+ </div>
</AnimatedCollapsible>
</div>
diff --git a/products/ai_observability/frontend/playground/MessageToolCallsEditor.stories.tsx b/products/ai_observability/frontend/playground/MessageToolCallsEditor.stories.tsx
new file mode 100644
index 000000000000..be3f1e8ffedf
--- /dev/null
+++ b/products/ai_observability/frontend/playground/MessageToolCallsEditor.stories.tsx
@@ -0,0 +1,25 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { useState } from 'react'
+
+import type { MessageToolCall } from './llmPlaygroundPromptsLogic'
+import { MessageToolCallsEditor } from './MessageToolCallsEditor'
+
+const meta: Meta<typeof MessageToolCallsEditor> = {
+ title: 'Components/Message Tool Calls Editor',
+ component: MessageToolCallsEditor,
+}
+export default meta
+type Story = StoryObj<typeof MessageToolCallsEditor>
+
+export const EditableToolCalls: Story = {
+ render: function Render() {
+ const [toolCalls, setToolCalls] = useState<MessageToolCall[]>([
+ { id: 'call_1a2b3c4d', name: 'get_weather', arguments: '{\n "location": "San Francisco, CA"\n}' },
+ ])
+ return (
+ <div className="max-w-150">
+ <MessageToolCallsEditor toolCalls={toolCalls} onChange={setToolCalls} />
+ </div>
+ )
+ },
+}
diff --git a/products/ai_observability/frontend/playground/MessageToolCallsEditor.tsx b/products/ai_observability/frontend/playground/MessageToolCallsEditor.tsx
new file mode 100644
index 000000000000..041cd537b171
--- /dev/null
+++ b/products/ai_observability/frontend/playground/MessageToolCallsEditor.tsx
@@ -0,0 +1,84 @@
+import posthog from 'posthog-js'
+
+import { IconPlus, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonTag } from '@posthog/lemon-ui'
+
+import { uuid } from 'lib/utils/dom'
+
+import { JSONEditor } from '../components/JSONEditor'
+import type { MessageToolCall } from './llmPlaygroundPromptsLogic'
+
+/** Editable list of an assistant message's tool calls: name, call id, and JSON arguments. */
+export function MessageToolCallsEditor({
+ toolCalls,
+ onChange,
+}: {
+ toolCalls: MessageToolCall[]
+ onChange: (toolCalls: MessageToolCall[]) => void
+}): JSX.Element {
+ const updateToolCall = (index: number, payload: Partial<MessageToolCall>): void => {
+ onChange(toolCalls.map((toolCall, i) => (i === index ? { ...toolCall, ...payload } : toolCall)))
+ }
+
+ return (
+ <div className="mt-2 space-y-2">
+ {toolCalls.map((toolCall, index) => (
+ <div key={index} className="border rounded p-2 space-y-2">
+ <div className="flex items-center gap-2">
+ <LemonTag type="default" size="small">
+ Tool call
+ </LemonTag>
+ <LemonInput
+ size="small"
+ className="flex-1"
+ placeholder="Tool name"
+ value={toolCall.name}
+ onChange={(value) => updateToolCall(index, { name: value })}
+ data-attr="llma-playground-tool-call-name"
+ />
+ <LemonInput
+ size="small"
+ className="flex-1 font-mono"
+ placeholder="Call id"
+ value={toolCall.id}
+ onChange={(value) => updateToolCall(index, { id: value })}
+ data-attr="llma-playground-tool-call-id"
+ />
+ <LemonButton
+ size="small"
+ status="danger"
+ icon={<IconTrash />}
+ noPadding
+ tooltip="Delete tool call"
+ onClick={() => {
+ posthog.capture('llma playground tool call removed')
+ onChange(toolCalls.filter((_, i) => i !== index))
+ }}
+ data-attr="llma-playground-remove-tool-call"
+ />
+ </div>
+ <div className="border rounded">
+ <JSONEditor
+ value={toolCall.arguments}
+ onChange={(value) => updateToolCall(index, { arguments: value ?? '' })}
+ defaultNumberOfLines={2}
+ maxNumberOfLines={12}
+ />
+ </div>
+ </div>
+ ))}
+ <LemonButton
+ type="secondary"
+ size="xsmall"
+ icon={<IconPlus />}
+ onClick={() => {
+ posthog.capture('llma playground tool call added')
+ onChange([...toolCalls, { id: `call_${uuid().slice(0, 8)}`, name: '', arguments: '{}' }])
+ }}
+ data-attr="llma-playground-add-tool-call"
+ >
+ Tool call
+ </LemonButton>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/playground/ToolCallDisplay.stories.tsx b/products/ai_observability/frontend/playground/ToolCallDisplay.stories.tsx
new file mode 100644
index 000000000000..9cd4d6e268f6
--- /dev/null
+++ b/products/ai_observability/frontend/playground/ToolCallDisplay.stories.tsx
@@ -0,0 +1,26 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { ToolCallDisplay } from './ToolCallDisplay'
+
+const meta: Meta<typeof ToolCallDisplay> = {
+ title: 'Components/Tool Call Display',
+ component: ToolCallDisplay,
+}
+export default meta
+type Story = StoryObj<typeof ToolCallDisplay>
+
+export const StreamedToolCall: Story = {
+ render: function Render() {
+ return (
+ <div className="max-w-150">
+ <ToolCallDisplay
+ toolCall={{
+ id: 'call_1a2b3c4d',
+ name: 'get_weather',
+ arguments: '{"location": "San Francisco, CA", "unit": "celsius"}',
+ }}
+ />
+ </div>
+ )
+ },
+}
diff --git a/products/ai_observability/frontend/playground/ToolCallDisplay.tsx b/products/ai_observability/frontend/playground/ToolCallDisplay.tsx
new file mode 100644
index 000000000000..d5cb1ac80e1a
--- /dev/null
+++ b/products/ai_observability/frontend/playground/ToolCallDisplay.tsx
@@ -0,0 +1,30 @@
+import { LemonTag } from '@posthog/lemon-ui'
+
+import type { AggregatedToolCall } from './llmPlaygroundRunLogic'
+
+function formatArguments(args: string): string {
+ try {
+ return JSON.stringify(JSON.parse(args), null, 2)
+ } catch {
+ // Streamed arguments can be a partial JSON string until the chunks finish.
+ return args
+ }
+}
+
+/** Read-only card for a tool call the model issued, shown in the result panel. */
+export function ToolCallDisplay({ toolCall }: { toolCall: AggregatedToolCall }): JSX.Element {
+ return (
+ <div className="border rounded p-2 bg-surface-primary">
+ <div className="flex items-center gap-2 mb-1">
+ <LemonTag type="default" size="small">
+ Tool call
+ </LemonTag>
+ <span className="font-mono text-xs font-semibold">{toolCall.name || '…'}</span>
+ <span className="font-mono text-xs text-muted truncate">{toolCall.id}</span>
+ </div>
+ <pre className="text-xs whitespace-pre-wrap break-words m-0 font-mono">
+ {formatArguments(toolCall.arguments)}
+ </pre>
+ </div>
+ )
+}
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts b/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts
index dff9e661c693..968ca97952b9 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts
@@ -621,6 +621,24 @@ describe('llmPlaygroundLogic', () => {
])
})
+ it('should keep structured tool calls on the appended assistant message even without text', () => {
+ llmPlaygroundPromptsLogic.actions.setMessages([{ role: 'user', content: 'Weather?' }])
+
+ llmPlaygroundPromptsLogic.actions.addResultToConversation('', [
+ { id: 'call_1', name: 'get_weather', arguments: '{"location": "Paris"}' },
+ ])
+
+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual([
+ { role: 'user', content: 'Weather?' },
+ {
+ role: 'assistant',
+ content: '',
+ toolCalls: [{ id: 'call_1', name: 'get_weather', arguments: '{"location": "Paris"}' }],
+ },
+ { role: 'user', content: '' },
+ ])
+ })
+
it('should append a result to the targeted prompt without changing other prompt columns', () => {
llmPlaygroundPromptsLogic.actions.setPromptConfigs([
createPromptConfig({
@@ -633,7 +651,7 @@ describe('llmPlaygroundLogic', () => {
}),
])
- llmPlaygroundPromptsLogic.actions.addResultToConversation('Second response', 'prompt-two')
+ llmPlaygroundPromptsLogic.actions.addResultToConversation('Second response', undefined, 'prompt-two')
expect(llmPlaygroundPromptsLogic.values.promptConfigs).toMatchObject([
{
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts b/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts
index b575e335046c..4a9439caab2f 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts
@@ -23,6 +23,7 @@ import { llmPromptLogic } from '../prompts/llmPromptLogic'
import { getApiErrorDetail } from '../prompts/utils'
import { normalizeLLMProvider } from '../settings/llmProviderKeysLogic'
import { isOTelPartsMessage, normalizeRole, safeStringify } from '../utils'
+import { isMessageSendable } from './playgroundMessageMapping'
import { isTraceLikeSelection } from './playgroundModelMatching'
import { type PlaygroundModelConfig, parsePlaygroundConfig, serializePlaygroundConfig } from './playgroundPromptConfig'
@@ -37,12 +38,25 @@ export function cleanSourceSearchParams(searchParams: Record<string, any>): Reco
return clean
}
-export type MessageRole = 'user' | 'assistant' | 'system'
+export type MessageRole = 'user' | 'assistant' | 'system' | 'tool'
export type ReasoningLevel = 'minimal' | 'low' | 'medium' | 'high' | null
+export interface MessageToolCall {
+ id: string
+ name: string
+ /** JSON string, the shape providers stream. Parsed into an object at request time. */
+ arguments: string
+}
+
export interface Message {
role: MessageRole
content: string
+ /** Assistant messages only. */
+ toolCalls?: MessageToolCall[]
+ /** Tool messages only: id of the tool call this result answers. */
+ toolCallId?: string
+ /** Tool messages only. */
+ toolName?: string
}
export interface PromptConfig {
@@ -512,10 +526,12 @@ export interface llmPlaygroundPromptsLogicActions {
}
addResultToConversation: (
response: string,
+ toolCalls?: MessageToolCall[],
promptId?: string
) => {
promptId: string | undefined
response: string
+ toolCalls: MessageToolCall[] | undefined
}
applySavedModelSelection: (selection: { model: string; provider: string | null; providerKeyId: string | null }) => {
selection: {
@@ -777,7 +793,11 @@ export const llmPlaygroundPromptsLogic = kea<llmPlaygroundPromptsLogicType>([
setMessages: (messages: Message[], promptId?: string) => ({ messages, promptId }),
deleteMessage: (index: number, promptId?: string) => ({ index, promptId }),
addMessage: (message?: Partial<Message>, promptId?: string) => ({ message, promptId }),
- addResultToConversation: (response: string, promptId?: string) => ({ response, promptId }),
+ addResultToConversation: (response: string, toolCalls?: MessageToolCall[], promptId?: string) => ({
+ response,
+ toolCalls,
+ promptId,
+ }),
updateMessage: (index: number, payload: Partial<Message>, promptId?: string) => ({ index, payload, promptId }),
clearLinkedSource: true,
setSourceNames: (promptName: string | null, evaluationName: string | null, promptId?: string) => ({
@@ -900,16 +920,24 @@ export const llmPlaygroundPromptsLogic = kea<llmPlaygroundPromptsLogicType>([
}),
addResultToConversation: (
state: PromptConfig[],
- { response, promptId }: { response: string; promptId?: string }
+ {
+ response,
+ toolCalls,
+ promptId,
+ }: { response: string; toolCalls?: MessageToolCall[]; promptId?: string }
) => {
- if (!response.trim()) {
+ if (!response.trim() && !toolCalls?.length) {
return state
}
return updatePromptConfigs(state, promptId, (prompt) => ({
...prompt,
messages: [
...prompt.messages,
- { role: 'assistant', content: response },
+ {
+ role: 'assistant',
+ content: response,
+ ...(toolCalls?.length ? { toolCalls } : {}),
+ },
{ role: 'user', content: '' },
],
}))
@@ -1189,7 +1217,7 @@ export const llmPlaygroundPromptsLogic = kea<llmPlaygroundPromptsLogicType>([
hasRunnablePrompts: [
(s) => [s.promptConfigs],
(promptConfigs: PromptConfig[]): boolean =>
- promptConfigs.some((prompt) => prompt.messages.some((message) => message.content.trim().length > 0)),
+ promptConfigs.some((prompt) => prompt.messages.some(isMessageSendable)),
],
}),
@@ -1221,9 +1249,10 @@ export const llmPlaygroundPromptsLogic = kea<llmPlaygroundPromptsLogicType>([
}
},
- addMessage: () => {
+ addMessage: ({ message }) => {
posthog.capture('llma playground message added', {
message_count: values.activePromptConfig?.messages.length ?? 0,
+ role: message?.role ?? 'user',
})
},
deleteMessage: () => {
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts
index d34561f65bb7..93ccbe5ad5ca 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts
@@ -120,6 +120,11 @@ describe('llmPlaygroundRunLogic', () => {
llmPlaygroundPromptsLogic.actions.setSystemPrompt('You answer questions about {{topic}}.')
llmPlaygroundPromptsLogic.actions.setMessages([
{ role: 'user', content: 'Tell me about {{topic}} and {{missing}}' },
+ {
+ role: 'assistant',
+ content: '',
+ toolCalls: [{ id: 'call_1', name: 'search', arguments: '{"query": "{{topic}}"}' }],
+ },
])
llmPlaygroundVariablesLogic.actions.setVariableValue('topic', 'penguins')
llmPlaygroundRunLogic.actions.submitPrompt()
@@ -130,11 +135,18 @@ describe('llmPlaygroundRunLogic', () => {
// 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}}' }],
+ messages: [
+ { role: 'user', content: 'Tell me about penguins and {{missing}}' },
+ {
+ role: 'assistant',
+ content: [{ type: 'tool_use', id: 'call_1', name: 'search', input: { query: 'penguins' } }],
+ },
+ ],
})
// 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}}')
+ expect(llmPlaygroundPromptsLogic.values.messages[1].toolCalls?.[0].arguments).toBe('{"query": "{{topic}}"}')
logic.unmount()
streamSpy.mockRestore()
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts
index f8e26b1c414f..db3e42129a18 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts
@@ -16,6 +16,7 @@ import type { LLMProviderKey } from '../settings/llmProviderKeysLogic'
import { llmPlaygroundModelLogic } from './llmPlaygroundModelLogic'
import { llmPlaygroundPromptsLogic, type Message, type PromptConfig } from './llmPlaygroundPromptsLogic'
import { llmPlaygroundVariablesLogic } from './llmPlaygroundVariablesLogic'
+import { isMessageSendable, toProviderMessages } from './playgroundMessageMapping'
import { resolveProviderKeyForPrompt } from './playgroundModelMatching'
import { extractVariablesFromTexts, getVariableValue, substituteVariables } from './playgroundTemplating'
@@ -100,15 +101,6 @@ export function describeError(err: unknown, fallbackMessage: string): { message:
}
}
-function formatToolCalls(toolCalls: AggregatedToolCall[]): string {
- if (toolCalls.length === 0) {
- return ''
- }
- return toolCalls
- .map((tc) => JSON.stringify({ id: tc.id, name: tc.name, arguments: tc.arguments }, null, 2))
- .join('\n\n')
-}
-
function normalizeUsageFromStreamChunk(data: Record<string, unknown>): UsageSummary {
const promptTokens = (data.input_tokens as number | undefined) ?? (data.prompt_tokens as number | undefined) ?? null
const completionTokens =
@@ -321,7 +313,7 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
.map((prompt: PromptConfig, index: number) => ({
prompt,
index,
- messagesToSend: prompt.messages.filter((m) => m.content.trim()),
+ messagesToSend: prompt.messages.filter(isMessageSendable),
}))
.filter((item: { messagesToSend: Message[] }) => item.messagesToSend.length > 0)
@@ -337,6 +329,7 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
runnablePrompts.flatMap(({ prompt, messagesToSend }) => [
prompt.systemPrompt,
...messagesToSend.map((m) => m.content),
+ ...messagesToSend.flatMap((m) => m.toolCalls?.map((toolCall) => toolCall.arguments) ?? []),
])
)
const runUnfilledVariables = runVariables.filter((name) => !getVariableValue(values.variableValues, name))
@@ -372,6 +365,14 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
(m: Message): Message => ({
...m,
content: substituteVariables(m.content, values.variableValues),
+ ...(m.toolCalls?.length
+ ? {
+ toolCalls: m.toolCalls.map((toolCall) => ({
+ ...toolCall,
+ arguments: substituteVariables(toolCall.arguments, values.variableValues),
+ })),
+ }
+ : {}),
})
)
const liveItemId = uuid()
@@ -443,9 +444,7 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
const requestData: Record<string, unknown> = {
system: resolvedSystemPrompt,
- messages: resolvedMessages
- .filter((m: Message) => m.role === 'user' || m.role === 'assistant')
- .map((m: Message) => ({ role: m.role, content: m.content })),
+ messages: toProviderMessages(resolvedMessages),
model: selectedModel.id,
provider: selectedModelProvider,
thinking: prompt.thinking,
@@ -486,10 +485,7 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
ttftMs = firstTokenTime - startTime
}
toolCalls = appendToolCallChunk(toolCalls, data)
- const toolCallsText = formatToolCalls(toolCalls)
- const separator = responseText.trim() && toolCallsText ? '\n\n' : ''
actions.updateComparisonItem(liveItemId, {
- response: responseText + separator + toolCallsText,
toolCalls,
ttftMs,
})
@@ -579,11 +575,6 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
}
}
- const toolCallsText = formatToolCalls(toolCalls)
- if (toolCallsText) {
- const separator = responseText.trim() ? '\n\n' : ''
- responseText += separator + toolCallsText
- }
upsertLiveItem()
posthog.capture('llma playground prompt completed', {
diff --git a/products/ai_observability/frontend/playground/playgroundMessageMapping.test.ts b/products/ai_observability/frontend/playground/playgroundMessageMapping.test.ts
new file mode 100644
index 000000000000..51a701f67c27
--- /dev/null
+++ b/products/ai_observability/frontend/playground/playgroundMessageMapping.test.ts
@@ -0,0 +1,70 @@
+import type { Message } from './llmPlaygroundPromptsLogic'
+import { isMessageSendable, toProviderMessages } from './playgroundMessageMapping'
+
+describe('playgroundMessageMapping', () => {
+ it('maps a tool-calling exchange to content blocks and merges consecutive tool results into one user turn', () => {
+ const messages: Message[] = [
+ { role: 'user', content: 'Weather in Paris and Rome?' },
+ {
+ role: 'assistant',
+ content: 'Checking both.',
+ toolCalls: [
+ { id: 'call_1', name: 'get_weather', arguments: '{"location": "Paris"}' },
+ { id: 'call_2', name: 'get_weather', arguments: '{"location": "Rome"}' },
+ ],
+ },
+ { role: 'tool', content: 'Sunny, 21C', toolCallId: 'call_1', toolName: 'get_weather' },
+ { role: 'tool', content: 'Cloudy, 18C', toolCallId: 'call_2', toolName: 'get_weather' },
+ { role: 'user', content: 'Which is warmer?' },
+ ]
+
+ expect(toProviderMessages(messages)).toEqual([
+ { role: 'user', content: 'Weather in Paris and Rome?' },
+ {
+ role: 'assistant',
+ content: [
+ { type: 'text', text: 'Checking both.' },
+ { type: 'tool_use', id: 'call_1', name: 'get_weather', input: { location: 'Paris' } },
+ { type: 'tool_use', id: 'call_2', name: 'get_weather', input: { location: 'Rome' } },
+ ],
+ },
+ {
+ role: 'user',
+ content: [
+ { type: 'tool_result', tool_use_id: 'call_1', content: 'Sunny, 21C' },
+ { type: 'tool_result', tool_use_id: 'call_2', content: 'Cloudy, 18C' },
+ ],
+ },
+ { role: 'user', content: 'Which is warmer?' },
+ ])
+ })
+
+ it.each([
+ ['unparseable JSON', 'not json', 'not json'],
+ ['a non-object JSON value', '[1, 2]', '[1, 2]'],
+ ['an empty string', '', {}],
+ ])('passes %s tool call arguments through instead of substituting them', (_, args, expectedInput) => {
+ const result = toProviderMessages([
+ { role: 'assistant', content: '', toolCalls: [{ id: 'call_1', name: 'lookup', arguments: args }] },
+ ])
+
+ expect(result).toEqual([
+ {
+ role: 'assistant',
+ content: [{ type: 'tool_use', id: 'call_1', name: 'lookup', input: expectedInput }],
+ },
+ ])
+ })
+
+ it.each([
+ ['an empty user message', { role: 'user', content: ' ' } as Message, false],
+ [
+ 'an assistant message with only tool calls',
+ { role: 'assistant', content: '', toolCalls: [{ id: 'c', name: 'f', arguments: '{}' }] } as Message,
+ true,
+ ],
+ ['a tool message with empty content', { role: 'tool', content: '', toolCallId: 'c' } as Message, true],
+ ])('counts %s as sendable: %p', (_, message, expected) => {
+ expect(isMessageSendable(message)).toBe(expected)
+ })
+})
diff --git a/products/ai_observability/frontend/playground/playgroundMessageMapping.ts b/products/ai_observability/frontend/playground/playgroundMessageMapping.ts
new file mode 100644
index 000000000000..3abc7ae45802
--- /dev/null
+++ b/products/ai_observability/frontend/playground/playgroundMessageMapping.ts
@@ -0,0 +1,83 @@
+import { isObject } from 'lib/utils/guards'
+
+import type { Message } from './llmPlaygroundPromptsLogic'
+
+export interface ProviderMessage {
+ role: 'user' | 'assistant'
+ content: string | Record<string, unknown>[]
+}
+
+/** A message earns a slot in the request when it carries text, tool calls, or a tool result. */
+export function isMessageSendable(message: Message): boolean {
+ return message.content.trim().length > 0 || !!message.toolCalls?.length || message.role === 'tool'
+}
+
+// Arguments that do not parse to an object are passed through as the raw string, so the
+// backend rejects them with a message naming the tool instead of silently sending {}.
+function parseToolCallArguments(args: string): unknown {
+ if (!args.trim()) {
+ return {}
+ }
+ try {
+ const parsed = JSON.parse(args)
+ return isObject(parsed) ? parsed : args
+ } catch {
+ return args
+ }
+}
+
+function isToolResultOnlyMessage(message: ProviderMessage): boolean {
+ return (
+ message.role === 'user' &&
+ Array.isArray(message.content) &&
+ message.content.every((block) => isObject(block) && block.type === 'tool_result')
+ )
+}
+
+/**
+ * Maps playground messages to the proxy's provider-neutral wire shape: Anthropic-style
+ * content blocks. Assistant tool calls become `tool_use` blocks; tool messages become
+ * user-role turns of `tool_result` blocks. Consecutive tool messages merge into one user
+ * turn, because Anthropic requires every result for a turn in the single next user message.
+ * The provider adapters absorb the per-provider differences from there.
+ */
+export function toProviderMessages(messages: Message[]): ProviderMessage[] {
+ const result: ProviderMessage[] = []
+ for (const message of messages) {
+ if (message.role === 'system') {
+ continue
+ }
+ if (message.role === 'tool') {
+ const block: Record<string, unknown> = {
+ type: 'tool_result',
+ tool_use_id: message.toolCallId ?? '',
+ content: message.content,
+ }
+ const previous = result[result.length - 1]
+ if (previous && isToolResultOnlyMessage(previous)) {
+ ;(previous.content as Record<string, unknown>[]).push(block)
+ } else {
+ result.push({ role: 'user', content: [block] })
+ }
+ continue
+ }
+ if (message.role === 'assistant' && message.toolCalls?.length) {
+ const content: Record<string, unknown>[] = []
+ if (message.content.trim()) {
+ content.push({ type: 'text', text: message.content })
+ }
+ for (const toolCall of message.toolCalls) {
+ content.push({
+ type: 'tool_use',
+ id: toolCall.id,
+ name: toolCall.name,
+ input: parseToolCallArguments(toolCall.arguments),
+ })
+ }
+ result.push({ role: 'assistant', content })
+ continue
+ }
+ result.push({ role: message.role, content: message.content })
+ }
+ return result
+}
diff --git a/products/ai_observability/frontend/playground/playgroundPromptConfig.test.ts b/products/ai_observability/frontend/playground/playgroundPromptConfig.test.ts
index f2ed0d5c4297..892f9713b9f8 100644
--- a/products/ai_observability/frontend/playground/playgroundPromptConfig.test.ts
+++ b/products/ai_observability/frontend/playground/playgroundPromptConfig.test.ts
@@ -15,7 +15,12 @@ describe('playgroundPromptConfig', () => {
tools: [{ type: 'function', function: { name: 'lookup' } }],
messages: [
{ role: 'user', content: 'Hi {{name}}' },
- { role: 'assistant', content: 'Hello!' },
+ {
+ role: 'assistant',
+ content: 'Hello!',
+ toolCalls: [{ id: 'call_1', name: 'lookup', arguments: '{"q": "x"}' }],
+ },
+ { role: 'tool', content: '{"rows": 2}', toolCallId: 'call_1', toolName: 'lookup' },
],
})
@@ -33,7 +38,12 @@ describe('playgroundPromptConfig', () => {
tools: [{ type: 'function', function: { name: 'lookup' } }],
messages: [
{ role: 'user', content: 'Hi {{name}}' },
- { role: 'assistant', content: 'Hello!' },
+ {
+ role: 'assistant',
+ content: 'Hello!',
+ toolCalls: [{ id: 'call_1', name: 'lookup', arguments: '{"q": "x"}' }],
+ },
+ { role: 'tool', content: '{"rows": 2}', toolCallId: 'call_1', toolName: 'lookup' },
],
})
})
diff --git a/products/ai_observability/frontend/playground/playgroundPromptConfig.ts b/products/ai_observability/frontend/playground/playgroundPromptConfig.ts
index 698594e0db9c..96024221a05f 100644
--- a/products/ai_observability/frontend/playground/playgroundPromptConfig.ts
+++ b/products/ai_observability/frontend/playground/playgroundPromptConfig.ts
@@ -1,6 +1,6 @@
import { isObject } from 'lib/utils/guards'
-import type { Message, MessageRole, PromptConfig, ReasoningLevel } from './llmPlaygroundPromptsLogic'
+import type { Message, MessageRole, MessageToolCall, PromptConfig, ReasoningLevel } from './llmPlaygroundPromptsLogic'
export interface PlaygroundModelConfig {
model: string
@@ -23,7 +23,7 @@ const PLAYGROUND_CONFIG_KEYS = new Set([
'messages',
])
-const MESSAGE_ROLES: MessageRole[] = ['user', 'assistant', 'system']
+const MESSAGE_ROLES: MessageRole[] = ['user', 'assistant', 'system', 'tool']
const REASONING_LEVELS: Exclude<ReasoningLevel, null>[] = ['minimal', 'low', 'medium', 'high']
export interface ParsedPlaygroundConfig {
@@ -89,7 +89,21 @@ export function serializePlaygroundConfig(
config.tools = prompt.tools
}
if (prompt.messages.length > 0) {
- config.messages = prompt.messages.map((message) => ({ role: message.role, content: message.content }))
+ config.messages = prompt.messages.map((message) => ({
+ role: message.role,
+ content: message.content,
+ ...(message.toolCalls?.length
+ ? {
+ tool_calls: message.toolCalls.map((toolCall) => ({
+ id: toolCall.id,
+ name: toolCall.name,
+ arguments: toolCall.arguments,
+ })),
+ }
+ : {}),
+ ...(message.toolCallId ? { tool_call_id: message.toolCallId } : {}),
+ ...(message.toolName ? { tool_name: message.toolName } : {}),
+ }))
}
return Object.keys(config).length > 0 ? config : null
@@ -106,11 +120,36 @@ export function parsePlaygroundConfig(config: unknown): ParsedPlaygroundConfig |
}
const messages: Message[] = Array.isArray(config.messages)
- ? config.messages.flatMap((entry): Message[] =>
- isObject(entry) && MESSAGE_ROLES.includes(entry.role as MessageRole) && typeof entry.content === 'string'
- ? [{ role: entry.role as MessageRole, content: entry.content }]
+ ? config.messages.flatMap((entry): Message[] => {
+ if (
+ !isObject(entry) ||
+ !MESSAGE_ROLES.includes(entry.role as MessageRole) ||
+ typeof entry.content !== 'string'
+ ) {
+ return []
+ }
+ const toolCalls: MessageToolCall[] = Array.isArray(entry.tool_calls)
+ ? entry.tool_calls.flatMap((call): MessageToolCall[] =>
+ isObject(call) &&
+ typeof call.id === 'string' &&
+ typeof call.name === 'string' &&
+ typeof call.arguments === 'string'
+ ? [{ id: call.id, name: call.name, arguments: call.arguments }]
+ : []
+ )
: []
- )
+ return [
+ {
+ role: entry.role as MessageRole,
+ content: entry.content,
+ ...(toolCalls.length > 0 ? { toolCalls } : {}),
+ ...(typeof entry.tool_call_id === 'string' && entry.tool_call_id
+ ? { toolCallId: entry.tool_call_id }
+ : {}),
+ ...(typeof entry.tool_name === 'string' && entry.tool_name ? { toolName: entry.tool_name } : {}),
+ },
+ ]
+ })
: []
const tools =