: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(aio): import trace tool calls and results as structured turns (#113398)
Juraj Majerik9fb9da0ccb2e
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts b/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.tsindex 5facefe13fe7..41f3d6c6a86f 100644--- a/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts+++ b/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts@@ -998,14 +998,14 @@ describe('llmPlaygroundLogic', () => {llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input })- expect(llmPlaygroundPromptsLogic.values.messages).toHaveLength(2)- expect(llmPlaygroundPromptsLogic.values.messages[0]).toEqual({- role: 'user',- content: 'What is the weather in Paris?',- })- expect(llmPlaygroundPromptsLogic.values.messages[1].role).toBe('assistant')- expect(llmPlaygroundPromptsLogic.values.messages[1].content).toContain('[Tool call: get_weather]')- expect(llmPlaygroundPromptsLogic.values.messages[1].content).toContain('Paris')+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual([+ { role: 'user', content: 'What is the weather in Paris?' },+ {+ role: 'assistant',+ content: '',+ toolCalls: [{ id: 'call_123', name: 'get_weather', arguments: '{"city": "Paris"}' }],+ },+ ])})it.each([@@ -1015,41 +1015,59 @@ describe('llmPlaygroundLogic', () => {{ type: 'text', text: 'Let me search for that.' },{ type: 'tool_use', id: 'tu_1', name: 'search', input: { query: 'cats' } },],- expectedSubstrings: ['Let me search for that.', '[Tool call: search]', 'cats'],+ expectedMessages: [+ {+ role: 'assistant',+ content: 'Let me search for that.',+ toolCalls: [+ { id: 'tu_1', name: 'search', arguments: JSON.stringify({ query: 'cats' }, null, 2) },+ ],+ },+ ],},{name: 'Anthropic tool_use only',content: [{ type: 'tool_use', id: 'tu_1', name: 'do_thing', input: { param: 'value' } }],- expectedSubstrings: ['[Tool call: do_thing]'],+ expectedMessages: [+ {+ role: 'assistant',+ content: '',+ toolCalls: [+ { id: 'tu_1', name: 'do_thing', arguments: JSON.stringify({ param: 'value' }, null, 2) },+ ],+ },+ ],},{name: 'Anthropic tool_result',content: [{ type: 'tool_result', tool_use_id: 'tu_1', content: 'Result data here' }],- expectedSubstrings: ['[Tool result for tu_1]', 'Result data here'],+ expectedMessages: [{ role: 'tool', content: 'Result data here', toolCallId: 'tu_1' }],},{name: 'OpenAI Responses API function_call',content: [{ type: 'function_call', name: 'my_func', call_id: 'fc_1', arguments: '{"x": 1}' }],- expectedSubstrings: ['[Function call: my_func]', '{"x": 1}'],+ expectedMessages: [+ {+ role: 'assistant',+ content: '',+ toolCalls: [{ id: 'fc_1', name: 'my_func', arguments: '{"x": 1}' }],+ },+ ],},{name: 'OpenAI Responses API function_call_output',content: [{ type: 'function_call_output', call_id: 'fc_1', output: 'result: 42' }],- expectedSubstrings: ['[Function output for fc_1]', 'result: 42'],+ expectedMessages: [{ role: 'tool', content: 'result: 42', toolCallId: 'fc_1' }],},- ])('should format $name content blocks', ({ content, expectedSubstrings }) => {+ ])('should import $name content blocks as structured turns', ({ content, expectedMessages }) => {const input = [{ role: 'assistant', content }]llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input })- const result = llmPlaygroundPromptsLogic.values.messages[0].content- expect(result).not.toBe('')- for (const substring of expectedSubstrings) {- expect(result).toContain(substring)- }+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual(expectedMessages)})- it('should merge tool-role messages into the preceding assistant turn', () => {+ it('should import tool-role messages as tool turns with the name resolved from the call', () => {const input = [{ role: 'user', content: 'What year was Python created?' },{@@ -1069,17 +1087,24 @@ describe('llmPlaygroundLogic', () => {llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input })- const messages = llmPlaygroundPromptsLogic.values.messages- expect(messages).toHaveLength(3)- expect(messages[0]).toEqual({ role: 'user', content: 'What year was Python created?' })- expect(messages[1].role).toBe('assistant')- expect(messages[1].content).toContain('[Tool call: research]')- expect(messages[1].content).toContain('[Tool result for call_abc]')- expect(messages[1].content).toContain('Python was created in 1991.')- expect(messages[2]).toEqual({ role: 'assistant', content: 'Python was created in 1991.' })+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual([+ { role: 'user', content: 'What year was Python created?' },+ {+ role: 'assistant',+ content: '',+ toolCalls: [{ id: 'call_abc', name: 'research', arguments: '{"question":"..."}' }],+ },+ {+ role: 'tool',+ content: 'Python was created in 1991.',+ toolCallId: 'call_abc',+ toolName: 'research',+ },+ { role: 'assistant', content: 'Python was created in 1991.' },+ ])})- it('should merge Anthropic-style tool_result user messages into the preceding assistant turn', () => {+ it('should import Anthropic-style tool_result user messages as tool turns', () => {const input = [{ role: 'user', content: 'Search cats' },{@@ -1094,34 +1119,33 @@ describe('llmPlaygroundLogic', () => {llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input })- const messages = llmPlaygroundPromptsLogic.values.messages- expect(messages).toHaveLength(2)- expect(messages[0]).toEqual({ role: 'user', content: 'Search cats' })- expect(messages[1].role).toBe('assistant')- expect(messages[1].content).toContain('[Tool call: search]')- expect(messages[1].content).toContain('[Tool result for tu_1]')- expect(messages[1].content).toContain('Found 42 cats')+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual([+ { role: 'user', content: 'Search cats' },+ {+ role: 'assistant',+ content: '',+ toolCalls: [{ id: 'tu_1', name: 'search', arguments: JSON.stringify({ query: 'cats' }, null, 2) }],+ },+ { role: 'tool', content: 'Found 42 cats', toolCallId: 'tu_1', toolName: 'search' },+ ])})- it('should fall back to a user turn for a tool message without a preceding assistant', () => {+ it('should import a tool message without a preceding assistant as a tool turn without a name', () => {const input = [{ role: 'tool', tool_call_id: 'call_123', content: 'Weather in Paris: 22°C' }]llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input })- expect(llmPlaygroundPromptsLogic.values.messages).toHaveLength(1)- expect(llmPlaygroundPromptsLogic.values.messages[0].role).toBe('user')- expect(llmPlaygroundPromptsLogic.values.messages[0].content).toBe(- '[Tool result for call_123]\nWeather in Paris: 22°C'- )+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual([+ { role: 'tool', content: 'Weather in Paris: 22°C', toolCallId: 'call_123' },+ ])})- it('should drop the "for …" suffix when a tool message has no tool_call_id', () => {+ it('should import a tool message without a tool_call_id as a tool turn without an id', () => {const input = [{ role: 'tool', content: 'Some result' }]llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input })- expect(llmPlaygroundPromptsLogic.values.messages[0].role).toBe('user')- expect(llmPlaygroundPromptsLogic.values.messages[0].content).toBe('[Tool result]\nSome result')+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual([{ role: 'tool', content: 'Some result' }])})it('should handle OpenAI Responses API top-level function_call and function_call_output items in input', () => {@@ -1145,14 +1169,22 @@ describe('llmPlaygroundLogic', () => {llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input })- const messages = llmPlaygroundPromptsLogic.values.messages- // system is extracted, function_call_output merges into the assistant turn- expect(messages).toHaveLength(2)- expect(messages[0]).toEqual({ role: 'user', content: 'What is the weather?' })- expect(messages[1].role).toBe('assistant')- expect(messages[1].content).toContain('[Function call: ask_clarification]')- expect(messages[1].content).toContain('[Function output for call_abc123]')- expect(messages[1].content).toContain('London')+ // system is extracted; the call and its output become structured turns+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual([+ { role: 'user', content: 'What is the weather?' },+ {+ role: 'assistant',+ content: '',+ toolCalls: [+ {+ id: 'call_abc123',+ name: 'ask_clarification',+ arguments: '{"question":"Which city?","options":["London","Paris"]}',+ },+ ],+ },+ { role: 'tool', content: 'London', toolCallId: 'call_abc123', toolName: 'ask_clarification' },+ ])})it('should handle OpenAI Responses API function_call item in output', () => {@@ -1171,16 +1203,20 @@ describe('llmPlaygroundLogic', () => {llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input, output })- const messages = llmPlaygroundPromptsLogic.values.messages- expect(messages).toHaveLength(2)- expect(messages[1].role).toBe('assistant')- expect(messages[1].content).toContain('[Function call: search_products]')- expect(messages[1].content).toContain('blue widgets')+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual([+ { role: 'user', content: 'Find me some products' },+ {+ role: 'assistant',+ content: '',+ toolCalls: [+ { id: 'call_def456', name: 'search_products', arguments: '{"queries":["blue widgets"]}' },+ ],+ },+ ])})- it('should merge function_call_output in output into preceding assistant turn', () => {- // A function_call followed immediately by function_call_output in $ai_output_choices —- // the output item should be folded into the assistant turn, not emitted as a user bubble.+ it('should import function_call and function_call_output items in output as structured turns', () => {+ // A function_call followed immediately by function_call_output in $ai_output_choicesconst input = [{ role: 'user', content: 'What is the weather in Paris?' }]const output = [{@@ -1200,13 +1236,15 @@ describe('llmPlaygroundLogic', () => {llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input, output })- const messages = llmPlaygroundPromptsLogic.values.messages- // function_call_output should merge into the function_call's assistant turn- expect(messages).toHaveLength(2)- expect(messages[1].role).toBe('assistant')- expect(messages[1].content).toContain('[Function call: get_weather]')- expect(messages[1].content).toContain('[Function output for call_ghi789]')- expect(messages[1].content).toContain('22°C, sunny')+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual([+ { role: 'user', content: 'What is the weather in Paris?' },+ {+ role: 'assistant',+ content: '',+ toolCalls: [{ id: 'call_ghi789', name: 'get_weather', arguments: '{"city":"Paris"}' }],+ },+ { role: 'tool', content: '22°C, sunny', toolCallId: 'call_ghi789', toolName: 'get_weather' },+ ])})it('should not produce "null" string for messages with null content', () => {@@ -1231,7 +1269,7 @@ describe('llmPlaygroundLogic', () => {expect(llmPlaygroundPromptsLogic.values.messages).toHaveLength(2)// Fallbacks are stringified via String(), not empty — we just verify content exists.expect(llmPlaygroundPromptsLogic.values.messages[0].content).not.toBe('')- expect(llmPlaygroundPromptsLogic.values.messages[1].content).toContain('[Tool call: x]')+ expect(llmPlaygroundPromptsLogic.values.messages[1].toolCalls?.[0].name).toBe('x')})it('should append output as assistant messages alongside input', () => {@@ -1260,10 +1298,14 @@ describe('llmPlaygroundLogic', () => {llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input, output })- expect(llmPlaygroundPromptsLogic.values.messages).toHaveLength(2)- expect(llmPlaygroundPromptsLogic.values.messages[1].role).toBe('assistant')- expect(llmPlaygroundPromptsLogic.values.messages[1].content).toContain('Let me search.')- expect(llmPlaygroundPromptsLogic.values.messages[1].content).toContain('[Tool call: search]')+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual([+ { role: 'user', content: 'Search for cats' },+ {+ role: 'assistant',+ content: 'Let me search.',+ toolCalls: [{ id: 'tu_1', name: 'search', arguments: JSON.stringify({ query: 'cats' }, null, 2) }],+ },+ ])})it('should handle OpenAI Responses API output (type: "message" with output_text content blocks)', () => {@@ -1362,10 +1404,14 @@ describe('llmPlaygroundLogic', () => {llmPlaygroundPromptsLogic.actions.setupPlaygroundFromEvent({ input, output })- expect(llmPlaygroundPromptsLogic.values.messages).toHaveLength(2)- expect(llmPlaygroundPromptsLogic.values.messages[1].role).toBe('assistant')- expect(llmPlaygroundPromptsLogic.values.messages[1].content).toContain('[Tool call: get_weather]')- expect(llmPlaygroundPromptsLogic.values.messages[1].content).toContain('Paris')+ expect(llmPlaygroundPromptsLogic.values.messages).toEqual([+ { role: 'user', content: 'What is the weather in Paris?' },+ {+ role: 'assistant',+ content: '',+ toolCalls: [{ id: 'call_abc', name: 'get_weather', arguments: '{"city": "Paris"}' }],+ },+ ])})it('should reset to default system prompt when none provided', () => {diff --git a/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts b/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.tsindex dd8472e1a07b..002b6889e28f 100644--- a/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts+++ b/products/ai_observability/frontend/playground/llmPlaygroundPromptsLogic.ts@@ -22,10 +22,11 @@ import { normalizeMessage } from '../messageNormalization'import { llmPromptLogic } from '../prompts/llmPromptLogic'import { getApiErrorDetail } from '../prompts/utils'import { normalizeLLMProvider } from '../settings/llmProviderKeysLogic'-import { isOTelPartsMessage, normalizeRole, safeStringify } from '../utils'+import { isOTelPartsMessage, normalizeRole } from '../utils'import { isMessageSendable } from './playgroundMessageMapping'import { isTraceLikeSelection } from './playgroundModelMatching'import { type PlaygroundModelConfig, parsePlaygroundConfig, serializePlaygroundConfig } from './playgroundPromptConfig'+import { type RawMessage, appendRawMessage, flattenOutputMessages } from './playgroundTraceImport'const SOURCE_PARAM_KEYS = ['source_prompt_name', 'source_prompt_version', 'source_evaluation_id'] as const@@ -198,278 +199,6 @@ export function updatePromptConfigs(return state.map((prompt) => (prompt.id === targetPromptId ? updater(prompt) : prompt))}-// Input processing helpers for setupPlaygroundFromEvent--interface RawMessage {- role: string- content: unknown- tool_calls?: unknown- tool_call_id?: unknown- type?: string-}--type ConversationRole = 'user' | 'assistant'--enum InputMessageRole {- User = 'user',- Assistant = 'assistant',- AI = 'ai',- Model = 'model',-}--// Formats a typed content block (one with a `type` field) into readable text.-// Returns null for unrecognized types so callers can fall through.-function formatContentBlock(part: Record<string, unknown>): string | null {- const type = part.type-- if (type === 'text' || type === 'output_text' || type === 'input_text') {- const text = part.text- return typeof text === 'string' && text.trim().length > 0 ? text : null- }-- // Anthropic: { type: 'tool_use', id, name, input }- if (type === 'tool_use') {- const name = part.name ?? 'unknown'- const input = part.input !== undefined ? safeStringify(part.input) : '{}'- return `[Tool call: ${name}]\n${input}`- }-- // Anthropic: { type: 'tool_result', tool_use_id, content }- if (type === 'tool_result') {- const toolId = typeof part.tool_use_id === 'string' ? part.tool_use_id : null- const content = typeof part.content === 'string' ? part.content : safeStringify(part.content)- const header = toolId ? `[Tool result for ${toolId}]` : '[Tool result]'- return `${header}\n${content}`- }-- // OpenAI Responses API: { type: 'function_call', name, call_id, arguments }- if (type === 'function_call') {- const name = part.name ?? 'unknown'- const args = typeof part.arguments === 'string' ? part.arguments : safeStringify(part.arguments)- return `[Function call: ${name}]\n${args}`- }-- // OpenAI Responses API: { type: 'function_call_output', call_id, output }- if (type === 'function_call_output') {- const callId = typeof part.call_id === 'string' ? part.call_id : null- const output = typeof part.output === 'string' ? part.output : safeStringify(part.output)- const header = callId ? `[Function output for ${callId}]` : '[Function output]'- return `${header}\n${output}`- }-- return null-}--// Formats OpenAI-style top-level tool_calls arrays into readable text-function formatToolCallsForPlayground(toolCalls: unknown): string {- if (!Array.isArray(toolCalls) || toolCalls.length === 0) {- return ''- }- return toolCalls- .map((tc) => {- if (!isObject(tc)) {- return safeStringify(tc)- }- const fn = isObject(tc.function) ? tc.function : tc- const name = fn.name ?? 'unknown'- const args = fn.arguments ?? '{}'- const argsStr = typeof args === 'string' ? args : safeStringify(args)- return `[Tool call: ${name}]\n${argsStr}`- })- .join('\n\n')-}--function extractTextFromMessagePart(part: unknown): string | null {- if (!isObject(part)) {- return null- }-- // Typed content blocks are handled by formatContentBlock, which checks- // `type` before any generic field extraction — preventing e.g. a- // tool_result's `.content` from being misidentified as plain text.- if (typeof part.type === 'string') {- return formatContentBlock(part)- }-- // Untyped objects: try common text field names- if (typeof part.text === 'string' && part.text.trim().length > 0) {- return part.text- }-- if (typeof part.content === 'string' && part.content.trim().length > 0) {- return part.content- }-- if (typeof part.output_text === 'string' && part.output_text.trim().length > 0) {- return part.output_text- }-- if (typeof part.value === 'string' && part.value.trim().length > 0) {- return part.value- }-- return null-}--function normalizeMessageContent(content: unknown): string {- if (content === null || content === undefined) {- return ''- }-- if (typeof content === 'string') {- return content- }-- if (Array.isArray(content)) {- const extractedTextParts = content- .map(extractTextFromMessagePart)- .filter((part): part is string => part !== null)-- if (extractedTextParts.length > 0) {- return extractedTextParts.join('\n\n')- }- }-- return safeStringify(content)-}--// Safety cap on recursion depth in flattenOutputMessages. Trace payloads can't have true cycles-// (they come from `JSON.parse`), but deeply nested `{ message: { message: … } }` chains or arrays-// of arrays could run the stack down — bail early and hand back an empty list instead.-const MAX_OUTPUT_FLATTEN_DEPTH = 100--// Flattens a raw generation output (string, single message, message array, or an-// OpenAI/LiteLLM-style { choices: [...] } wrapper) into a list of RawMessage entries-// without splitting structured content blocks — unlike `normalizeMessages` from utils,-// which fans out tool_use/tool_result blocks into separate display bubbles.-function flattenOutputMessages(output: unknown, depth: number = 0): RawMessage[] {- if (output == null || depth > MAX_OUTPUT_FLATTEN_DEPTH) {- return []- }-- if (typeof output === 'string') {- return [{ role: InputMessageRole.Assistant, content: output }]- }-- if (Array.isArray(output)) {- return output.flatMap((item) => flattenOutputMessages(item, depth + 1))- }-- if (isObject(output)) {- if (Array.isArray(output.choices)) {- return output.choices.flatMap((item) => flattenOutputMessages(item, depth + 1))- }- if (isObject(output.message)) {- return flattenOutputMessages(output.message, depth + 1)- }- // OpenAI Responses API top-level function_call / function_call_output items have no role.- // Convert them to synthetic RawMessages so extractConversationMessage can format them.- // Preserve `type` so isToolResultMessage can still identify function_call_output and fold- // it into the preceding assistant turn rather than emitting a standalone user bubble.- if (output.type === 'function_call' || output.type === 'function_call_output') {- return [- {- role: output.type === 'function_call_output' ? InputMessageRole.User : InputMessageRole.Assistant,- content: formatContentBlock(output) ?? '',- tool_call_id: output.call_id,- type: String(output.type),- },- ]- }- return [- {- role: typeof output.role === 'string' ? output.role : InputMessageRole.Assistant,- content: output.content,- tool_calls: output.tool_calls,- tool_call_id: output.tool_call_id,- },- ]- }-- return []-}--function extractConversationMessage(rawMessage: RawMessage): { role: ConversationRole; content: string } {- // OpenAI Responses API sends function_call / function_call_output items at the top level of the- // conversation array with no `role`. Route them through formatContentBlock so they get the same- // `[Function call: name]` / `[Function output for id]` treatment as typed content blocks.- const rawAsBlock = rawMessage as unknown as Record<string, unknown>- const topLevelType = rawMessage.type- if (- typeof rawMessage.role !== 'string' &&- (topLevelType === 'function_call' || topLevelType === 'function_call_output')- ) {- const formatted = formatContentBlock(rawAsBlock) ?? ''- const role: ConversationRole =- topLevelType === 'function_call_output' ? InputMessageRole.User : InputMessageRole.Assistant- return { role, content: formatted }- }-- const normalizedMessageRole = normalizeRole(rawMessage.role, InputMessageRole.User)- const enumMap: Partial<Record<string, ConversationRole>> = {- [InputMessageRole.User]: InputMessageRole.User,- [InputMessageRole.Assistant]: InputMessageRole.Assistant,- }- const enumRole: ConversationRole | undefined = enumMap[normalizedMessageRole]-- let content = normalizeMessageContent(rawMessage.content)-- // Tool-role messages collapse into a user turn since the playground only renders user/assistant.- // Prefix with `[Tool result …]` so the origin is preserved — in practice the caller will merge- // this into the preceding assistant turn via `appendRawMessage`, but the prefix is kept for the- // rare case where a tool result has no preceding assistant (e.g. a broken trace).- if (normalizedMessageRole === 'tool') {- const toolId = typeof rawMessage.tool_call_id === 'string' ? rawMessage.tool_call_id : null- const header = toolId ? `[Tool result for ${toolId}]` : '[Tool result]'- content = `${header}\n${content}`- }-- // Append top-level tool_calls (OpenAI format) when present- const toolCallsText = formatToolCallsForPlayground(rawMessage.tool_calls)- if (toolCallsText) {- content = content ? `${content}\n\n${toolCallsText}` : toolCallsText- }-- return {- role: enumRole ?? InputMessageRole.User,- content,- }-}--// Detects messages whose entire purpose is carrying a tool response — OpenAI `role: 'tool'` or an-// Anthropic-style `role: 'user'` message whose content is a pure `tool_result` / `function_call_output`-// block. Such messages don't represent a real user turn and should be folded into the preceding-// assistant turn rather than rendered as standalone user bubbles in the playground.-function isToolResultMessage(raw: RawMessage): boolean {- if (normalizeRole(raw.role, '') === 'tool') {- return true- }- // OpenAI Responses API top-level function_call_output item (no role)- if (raw.type === 'function_call_output') {- return true- }- if (Array.isArray(raw.content) && raw.content.length > 0) {- return raw.content.every((c) => isObject(c) && (c.type === 'tool_result' || c.type === 'function_call_output'))- }- return false-}--// Appends a raw message to a running conversation, merging tool-result messages into the previous-// assistant turn rather than emitting a separate user bubble. This keeps the playground's display-// in line with how tool calls/results conceptually bind together, without requiring a dedicated-// tool role in the playground's Message model.-function appendRawMessage(conversation: Message[], raw: RawMessage): void {- const extracted = extractConversationMessage(raw)- const prev = conversation[conversation.length - 1]-- if (isToolResultMessage(raw) && prev?.role === InputMessageRole.Assistant) {- prev.content = prev.content ? `${prev.content}\n\n${extracted.content}` : extracted.content- return- }-- conversation.push(extracted)-}-export type LLMPlaygroundPromptsLogicProps = Record<string, never>// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -1466,7 +1195,7 @@ export const llmPlaygroundPromptsLogic = kea<llmPlaygroundPromptsLogicType>([// Append the generation output as assistant turn(s) so users see the full exchange.// `flattenOutputMessages` unwraps LiteLLM/OpenAI `choices` shapes and string outputs,- // then `appendRawMessage` folds any tool-result messages into the preceding assistant turn.+ // then `appendRawMessage` turns tool calls and results into structured turns.if (payload.output != null) {try {for (const msg of flattenOutputMessages(payload.output)) {diff --git a/products/ai_observability/frontend/playground/playgroundTraceImport.ts b/products/ai_observability/frontend/playground/playgroundTraceImport.tsnew file mode 100644index 000000000000..c875203fc39c--- /dev/null+++ b/products/ai_observability/frontend/playground/playgroundTraceImport.ts@@ -0,0 +1,308 @@+import { isObject } from 'lib/utils/guards'++import { normalizeRole, safeStringify } from '../utils'+import type { Message, MessageToolCall } from './llmPlaygroundPromptsLogic'++export interface RawMessage {+ role: string+ content: unknown+ tool_calls?: unknown+ tool_call_id?: unknown+ type?: string+ name?: unknown+ call_id?: unknown+ arguments?: unknown+ output?: unknown+}++enum InputMessageRole {+ User = 'user',+ Assistant = 'assistant',+}++// Formats a typed content block (one with a `type` field) into readable text.+// Returns null for unrecognized types so callers can fall through.+function formatContentBlock(part: Record<string, unknown>): string | null {+ const type = part.type++ if (type === 'text' || type === 'output_text' || type === 'input_text') {+ const text = part.text+ return typeof text === 'string' && text.trim().length > 0 ? text : null+ }++ return null+}++function extractTextFromMessagePart(part: unknown): string | null {+ if (!isObject(part)) {+ return null+ }++ // Typed content blocks are handled by formatContentBlock, which checks+ // `type` before any generic field extraction — preventing e.g. a+ // tool_result's `.content` from being misidentified as plain text.+ if (typeof part.type === 'string') {+ return formatContentBlock(part)+ }++ // Untyped objects: try common text field names+ if (typeof part.text === 'string' && part.text.trim().length > 0) {+ return part.text+ }++ if (typeof part.content === 'string' && part.content.trim().length > 0) {+ return part.content+ }++ if (typeof part.output_text === 'string' && part.output_text.trim().length > 0) {+ return part.output_text+ }++ if (typeof part.value === 'string' && part.value.trim().length > 0) {+ return part.value+ }++ return null+}++function normalizeMessageContent(content: unknown): string {+ if (content === null || content === undefined) {+ return ''+ }++ if (typeof content === 'string') {+ return content+ }++ if (Array.isArray(content)) {+ const extractedTextParts = content+ .map(extractTextFromMessagePart)+ .filter((part): part is string => part !== null)++ if (extractedTextParts.length > 0) {+ return extractedTextParts.join('\n\n')+ }+ }++ return safeStringify(content)+}++function toolCallArgumentsString(value: unknown): string {+ if (typeof value === 'string') {+ return value+ }+ return value === undefined || value === null ? '{}' : safeStringify(value)+}++// Anthropic `tool_use` and OpenAI Responses API `function_call` blocks+function toolCallFromBlock(block: Record<string, unknown>): MessageToolCall {+ const id = block.type === 'function_call' ? block.call_id : block.id+ return {+ id: typeof id === 'string' ? id : '',+ name: typeof block.name === 'string' ? block.name : 'unknown',+ arguments: toolCallArgumentsString(block.type === 'function_call' ? block.arguments : block.input),+ }+}++// OpenAI chat `tool_calls` arrays on assistant messages+function toolCallsFromOpenAI(toolCalls: unknown): MessageToolCall[] {+ if (!Array.isArray(toolCalls)) {+ return []+ }+ return toolCalls.filter(isObject).map((tc) => {+ const fn = isObject(tc.function) ? tc.function : tc+ return {+ id: typeof tc.id === 'string' ? tc.id : '',+ name: typeof fn.name === 'string' ? fn.name : 'unknown',+ arguments: toolCallArgumentsString(fn.arguments),+ }+ })+}++function findToolName(conversation: Message[], callId: string | undefined): string | undefined {+ if (!callId) {+ return undefined+ }+ for (let i = conversation.length - 1; i >= 0; i--) {+ const match = conversation[i].toolCalls?.find((toolCall) => toolCall.id === callId)+ if (match?.name) {+ return match.name+ }+ }+ return undefined+}++function toolResultMessage(conversation: Message[], callId: unknown, content: unknown): Message {+ const id = typeof callId === 'string' && callId ? callId : undefined+ const name = findToolName(conversation, id)+ return {+ role: 'tool',+ content: normalizeMessageContent(content),+ ...(id ? { toolCallId: id } : {}),+ ...(name ? { toolName: name } : {}),+ }+}++function isToolCallBlock(part: unknown): part is Record<string, unknown> {+ return isObject(part) && (part.type === 'tool_use' || part.type === 'function_call')+}++function isToolResultBlock(part: unknown): part is Record<string, unknown> {+ return isObject(part) && (part.type === 'tool_result' || part.type === 'function_call_output')+}++function appendBlocks(+ conversation: Message[],+ role: 'user' | 'assistant',+ blocks: unknown[],+ extraToolCalls: MessageToolCall[] = []+): void {+ const textParts: string[] = []+ const toolCalls: MessageToolCall[] = [...extraToolCalls]+ const toolResults: { callId: unknown; content: unknown }[] = []++ for (const part of blocks) {+ if (isToolCallBlock(part)) {+ toolCalls.push(toolCallFromBlock(part))+ } else if (isToolResultBlock(part)) {+ toolResults.push({+ callId: part.type === 'tool_result' ? part.tool_use_id : part.call_id,+ content: part.type === 'tool_result' ? part.content : part.output,+ })+ } else {+ const text = extractTextFromMessagePart(part)+ if (text !== null) {+ textParts.push(text)+ }+ }+ }++ if (textParts.length === 0 && toolCalls.length === 0 && toolResults.length === 0) {+ // Nothing recognizable: keep the raw payload visible rather than dropping the turn.+ conversation.push({ role, content: blocks.length > 0 ? safeStringify(blocks) : '' })+ return+ }++ const content = textParts.join('\n\n')+ const pushTextAndCalls = (): void => {+ if (toolCalls.length > 0) {+ conversation.push({ role: 'assistant', content, toolCalls })+ } else if (role === 'assistant') {+ if (content || toolResults.length === 0) {+ conversation.push({ role: 'assistant', content })+ }+ } else if (content) {+ conversation.push({ role: 'user', content })+ }+ }+ const pushResults = (): void => {+ for (const result of toolResults) {+ conversation.push(toolResultMessage(conversation, result.callId, result.content))+ }+ }++ // Tool results become their own turns. In a user message they answer the preceding+ // assistant call, so they go before the user's text; in an assistant message they follow it.+ if (role === 'user') {+ pushResults()+ pushTextAndCalls()+ } else {+ pushTextAndCalls()+ pushResults()+ }+}++/**+ * Appends a raw trace message to a running conversation as structured playground messages:+ * assistant tool calls become `toolCalls` data, tool results become tool-role messages, and+ * anything unrecognizable keeps its text form. One raw message can produce several playground+ * messages (e.g. an Anthropic user message holding two tool_result blocks).+ */+export function appendRawMessage(conversation: Message[], raw: RawMessage): void {+ // OpenAI Responses API sends function_call / function_call_output items at the top level+ // of the conversation array with no `role`.+ if (typeof raw.role !== 'string' && (raw.type === 'function_call' || raw.type === 'function_call_output')) {+ if (raw.type === 'function_call') {+ const toolCall = toolCallFromBlock(raw as unknown as Record<string, unknown>)+ const previous = conversation[conversation.length - 1]+ // Parallel calls arrive as consecutive items but belong to one model turn.+ if (previous?.role === 'assistant') {+ previous.toolCalls = [...(previous.toolCalls ?? []), toolCall]+ } else {+ conversation.push({ role: 'assistant', content: '', toolCalls: [toolCall] })+ }+ } else {+ conversation.push(toolResultMessage(conversation, raw.call_id, raw.output))+ }+ return+ }++ const normalizedRole = normalizeRole(raw.role, InputMessageRole.User)++ if (normalizedRole === 'tool') {+ conversation.push(toolResultMessage(conversation, raw.tool_call_id, raw.content))+ return+ }++ const role: 'user' | 'assistant' =+ normalizedRole === InputMessageRole.Assistant ? InputMessageRole.Assistant : InputMessageRole.User+ const topLevelToolCalls = toolCallsFromOpenAI(raw.tool_calls)++ if (Array.isArray(raw.content)) {+ appendBlocks(conversation, role, raw.content, topLevelToolCalls)+ return+ }++ conversation.push({+ role,+ content: normalizeMessageContent(raw.content),+ ...(topLevelToolCalls.length > 0 ? { toolCalls: topLevelToolCalls } : {}),+ })+}++// Safety cap on recursion depth in flattenOutputMessages. Trace payloads can't have true cycles+// (they come from `JSON.parse`), but deeply nested `{ message: { message: … } }` chains or arrays+// of arrays could run the stack down — bail early and hand back an empty list instead.+const MAX_OUTPUT_FLATTEN_DEPTH = 100++// Flattens a raw generation output (string, single message, message array, or an+// OpenAI/LiteLLM-style { choices: [...] } wrapper) into a list of RawMessage entries+// without splitting structured content blocks — unlike `normalizeMessages` from utils,+// which fans out tool_use/tool_result blocks into separate display bubbles.+export function flattenOutputMessages(output: unknown, depth: number = 0): RawMessage[] {+ if (output == null || depth > MAX_OUTPUT_FLATTEN_DEPTH) {+ return []+ }++ if (typeof output === 'string') {+ return [{ role: InputMessageRole.Assistant, content: output }]+ }++ if (Array.isArray(output)) {+ return output.flatMap((item) => flattenOutputMessages(item, depth + 1))+ }++ if (isObject(output)) {+ if (Array.isArray(output.choices)) {+ return output.choices.flatMap((item) => flattenOutputMessages(item, depth + 1))+ }+ if (isObject(output.message)) {+ return flattenOutputMessages(output.message, depth + 1)+ }+ // OpenAI Responses API top-level function_call / function_call_output items have no role.+ // Pass them through untouched so appendRawMessage can turn them into structured turns.+ if (output.type === 'function_call' || output.type === 'function_call_output') {+ return [output as unknown as RawMessage]+ }+ return [+ {+ role: typeof output.role === 'string' ? output.role : InputMessageRole.Assistant,+ content: output.content,+ tool_calls: output.tool_calls,+ tool_call_id: output.tool_call_id,+ },+ ]+ }++ return []+}