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.

fix(aiobs): render spans via recipes (#62508)

Carlos Marchal1859bff08745
diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/AIEventItems.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/AIEventItems.tsx
index 9b8ba90b3e42..5b38b9a04a44 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/components/AIEventItems.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/components/AIEventItems.tsx
@@ -30,8 +30,8 @@ export function AIEventExpanded({ event }: { event: Record<string, any> }): JSX.
<div>
{isGeneration ? (
<ConversationMessagesDisplay
- inputNormalized={normalizeMessages(input, 'user', tools)}
- outputNormalized={normalizeMessages(output, 'assistant')}
+ inputNormalized={normalizeMessages(input, 'user', tools).messages}
+ outputNormalized={normalizeMessages(output, 'assistant').messages}
errorData={event.properties.$ai_error}
httpStatus={event.properties.$ai_http_status}
raisedError={raisedError}
diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
index 0c05e43e5dbd..3d5655bf4e07 100644
--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
@@ -67,7 +67,7 @@ import { ClustersTabContent } from './components/ClustersTabContent'
import { CostBreakdownTooltip } from './components/CostBreakdownTooltip'
import { EvalResultBadges } from './components/EvalResultBadges'
import { EvalsTabContent } from './components/EvalsTabContent'
-import { EventContentDisplayAsync, EventContentGeneration } from './components/EventContentWithAsyncData'
+import { EventContentConversation } from './components/EventContentWithAsyncData'
import { FeedbackTag } from './components/FeedbackTag'
import { JSONValueDisplay } from './components/JSONValueDisplay'
import { MetricTag } from './components/MetricTag'
@@ -1390,8 +1390,8 @@ function EventContentDisplay({
return <></>
}
- const inputMessages = normalizeMessages(input, 'user')
- const outputMessages = normalizeMessages(output, 'assistant')
+ const inputMessages = normalizeMessages(input, 'user').messages
+ const outputMessages = normalizeMessages(output, 'assistant').messages
if (inputMessages.length > 0 || outputMessages.length > 0) {
return (
@@ -1698,8 +1698,9 @@ const EventContent = React.memo(
<>
{isLLMEvent(event) ? (
event.event === '$ai_generation' ? (
- <EventContentGeneration
+ <EventContentConversation
eventId={event.id}
+ generationEventId={event.id}
traceId={trace.id}
rawInput={event.properties.$ai_input}
rawOutput={
@@ -1715,20 +1716,25 @@ const EventContent = React.memo(
highlightMessageIndex={highlightMessageIndex}
/>
) : event.event === '$ai_embedding' ? (
- <EventContentDisplayAsync
+ <EventContentConversation
eventId={event.id}
+ traceId={trace.id}
rawInput={event.properties.$ai_input}
rawOutput="Embedding vector generated"
+ searchQuery={searchQuery}
+ displayOption={displayOption}
/>
) : (
- <EventContentDisplayAsync
+ <EventContentConversation
eventId={event.id}
+ traceId={trace.id}
rawInput={event.properties.$ai_input_state}
- rawOutput={
- event.properties.$ai_output_state ??
- event.properties.$ai_error
- }
+ rawOutput={event.properties.$ai_output_state}
+ errorData={event.properties.$ai_error}
+ httpStatus={event.properties.$ai_http_status}
raisedError={event.properties.$ai_is_error}
+ searchQuery={searchQuery}
+ displayOption={displayOption}
/>
)
) : (
diff --git a/products/ai_observability/frontend/AIObservabilityTracesScene.tsx b/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
index 0be69fc3d15d..40914237298d 100644
--- a/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTracesScene.tsx
@@ -403,7 +403,7 @@ const OutputMessageColumn: QueryContextColumnComponent = ({ record }) => {
}
OutputMessageColumn.displayName = 'OutputMessageColumn'
-type NormalizedMessage = ReturnType<typeof normalizeMessages>[number]
+type NormalizedMessage = ReturnType<typeof normalizeMessages>['messages'][number]
function hasDisplayableContent(message: NormalizedMessage): boolean {
const { content, tool_calls } = message as NormalizedMessage & { tool_calls?: unknown }
@@ -500,13 +500,13 @@ function safeNormalize(
raw: unknown,
defaultRole: string,
{ strict }: { strict: boolean } = { strict: false }
-): ReturnType<typeof normalizeMessages> {
+): NormalizedMessage[] {
const unwrapped = unwrapMessageContainer(raw, strict)
if (unwrapped == null) {
return []
}
try {
- return normalizeMessages(unwrapped, defaultRole)
+ return normalizeMessages(unwrapped, defaultRole).messages
} catch (e) {
console.warn('Error normalizing trace messages', e)
return []
diff --git a/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.tsx
index 246c0d619038..e2a9bddf485a 100644
--- a/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.tsx
@@ -84,8 +84,8 @@ export function ConversationDisplay({
<AIDataLoading variant="block" />
) : (
<ConversationMessagesDisplay
- inputNormalized={normalizeMessages(input, 'user', tools)}
- outputNormalized={normalizeMessages(output, 'assistant')}
+ inputNormalized={normalizeMessages(input, 'user', tools).messages}
+ outputNormalized={normalizeMessages(output, 'assistant').messages}
inputSourceIndices={inputSourceIndices}
errorData={eventProperties.$ai_error}
httpStatus={eventProperties.$ai_http_status}
diff --git a/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx b/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx
index 14287296a072..48ed88eb26f2 100644
--- a/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx
+++ b/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx
@@ -290,7 +290,7 @@ function AIInputCell({ eventData }: { eventData: EventData }): JSX.Element {
let inputNormalized: CompatMessage[] | undefined
try {
const parsed = parseJSONPreview(input)
- inputNormalized = normalizeMessages(parsed, 'user')
+ inputNormalized = normalizeMessages(parsed, 'user').messages
} catch (e) {
console.warn('Error normalizing properties.$ai_input', e)
}
@@ -312,7 +312,7 @@ function AIOutputCell({ eventData }: { eventData: EventData }): JSX.Element {
let outputNormalized: CompatMessage[] | undefined
try {
const parsed = parseJSONPreview(output)
- outputNormalized = normalizeMessages(parsed, 'assistant')
+ outputNormalized = normalizeMessages(parsed, 'assistant').messages
} catch (e) {
console.warn('Error normalizing properties.$ai_output_choices', e)
}
diff --git a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.test.ts b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.test.ts
index dd125f21e513..bb4655f4b66d 100644
--- a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.test.ts
+++ b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.test.ts
@@ -1,3 +1,5 @@
+import posthog from 'posthog-js'
+
import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
import {
@@ -5,6 +7,7 @@ import {
getEffectiveEventId,
getInitialFocusEventId,
getSingleTraceLoadTiming,
+ reportTraceNormalizationFailures,
resolveTraceEventById,
restoreTree,
} from './aiObservabilityTraceDataLogic'
@@ -549,3 +552,83 @@ describe('getSingleTraceLoadTiming', () => {
})
})
})
+
+describe('reportTraceNormalizationFailures', () => {
+ let capture: jest.SpyInstance
+
+ beforeEach(() => {
+ capture = jest.spyOn(posthog, 'capture').mockImplementation()
+ })
+
+ afterEach(() => {
+ capture.mockRestore()
+ })
+
+ const traceWith = (events: Partial<LLMTraceEvent>[]): LLMTrace => ({
+ id: 'trace-1',
+ createdAt: '2024-01-01T00:00:00Z',
+ distinctId: 'user-1',
+ events: events.map((e, i) => ({
+ id: `event-${i}`,
+ event: '$ai_generation',
+ properties: {},
+ createdAt: '2024-01-01T00:00:00Z',
+ ...e,
+ })),
+ })
+
+ it('captures both unrecognized sides of a generation', () => {
+ reportTraceNormalizationFailures(
+ traceWith([{ properties: { $ai_input: { weird: 1 }, $ai_output: { odd: 2 } } }])
+ )
+
+ expect(capture).toHaveBeenCalledTimes(2)
+ expect(capture).toHaveBeenCalledWith('llma message normalization failed', {
+ message_keys: ['weird'],
+ message_type: 'object',
+ })
+ expect(capture).toHaveBeenCalledWith('llma message normalization failed', {
+ message_keys: ['odd'],
+ message_type: 'object',
+ })
+ })
+
+ it('skips non-generation events', () => {
+ reportTraceNormalizationFailures(
+ traceWith([{ event: '$ai_span', properties: { $ai_input_state: { weird: 1 } } }])
+ )
+
+ expect(capture).not.toHaveBeenCalled()
+ })
+
+ it('does not capture a recognized generation', () => {
+ reportTraceNormalizationFailures(
+ traceWith([
+ {
+ properties: {
+ $ai_input: { role: 'user', content: 'hi' },
+ $ai_output_choices: { role: 'assistant', content: 'hello' },
+ },
+ },
+ ])
+ )
+
+ expect(capture).not.toHaveBeenCalled()
+ })
+
+ it('prefers $ai_output_choices over $ai_output', () => {
+ reportTraceNormalizationFailures(
+ traceWith([
+ {
+ properties: {
+ $ai_input: { role: 'user', content: 'hi' },
+ $ai_output_choices: { role: 'assistant', content: 'from choices' },
+ $ai_output: { unrecognized: true },
+ },
+ },
+ ])
+ )
+
+ expect(capture).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts
index e51d980081ef..33462564d3b3 100644
--- a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts
@@ -24,7 +24,7 @@ import type { aiObservabilityTraceDataLogicType } from './aiObservabilityTraceDa
import { aiObservabilityTraceLogic } from './aiObservabilityTraceLogic'
import { llmPersonsLazyLoaderLogic } from './llmPersonsLazyLoaderLogic'
import { llmSentimentLazyLoaderLogic } from './llmSentimentLazyLoaderLogic'
-import { normalizeMessages } from './messageNormalization'
+import { captureNormalizationFailure, normalizeMessages } from './messageNormalization'
import {
SearchOccurrence,
eventMatchesSearch,
@@ -164,6 +164,25 @@ function findEventWithParents(
return parentChain
}
+// Generations should always be conversations, so one whose input or output no recipe
+// recognizes is a parse gap worth surfacing. Spans/embeddings carry opaque state and
+// are skipped. Runs once per trace load over every generation, viewed or not.
+export function reportTraceNormalizationFailures(trace: LLMTrace): void {
+ for (const event of trace.events) {
+ if (event.event !== '$ai_generation') {
+ continue
+ }
+ const input = event.properties.$ai_input
+ const output = event.properties.$ai_output_choices ?? event.properties.$ai_output
+ if (!normalizeMessages(input, 'user', event.properties.$ai_tools).recognized) {
+ captureNormalizationFailure(input)
+ }
+ if (!normalizeMessages(output, 'assistant').recognized) {
+ captureNormalizationFailure(output)
+ }
+ }
+}
+
export const aiObservabilityTraceDataLogic = kea<aiObservabilityTraceDataLogicType>([
path(['scenes', 'ai-observability', 'aiObservabilityTraceDataLogic']),
props({} as TraceDataLogicProps),
@@ -446,6 +465,8 @@ export const aiObservabilityTraceDataLogic = kea<aiObservabilityTraceDataLogicTy
organization_name: appContext?.current_user?.organization?.name ?? null,
...timing,
})
+
+ reportTraceNormalizationFailures(trace)
},
})),
subscriptions(({ actions, props, values }) => ({
diff --git a/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx b/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx
index fa5379cbad28..306a3f0ffae7 100644
--- a/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx
+++ b/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx
@@ -9,22 +9,27 @@ import { normalizeMessage, normalizeMessages } from '../messageNormalization'
import { AIDataLoading } from './AIDataLoading'
import { JSONValueDisplay } from './JSONValueDisplay'
-interface EventContentGenerationProps {
+interface EventContentConversationProps {
eventId: string
traceId?: string | null
rawInput: unknown
rawOutput: unknown
- tools: unknown
- errorData: unknown
- httpStatus: unknown
- raisedError: boolean
+ tools?: unknown
+ errorData?: unknown
+ httpStatus?: unknown
+ raisedError?: boolean
searchQuery?: string
displayOption?: ConversationDisplayOption
/** Original $ai_input index to auto-expand (e.g. from sentiment tab deep link) */
highlightMessageIndex?: number | null
+ /** Generation id for per-message sentiment lookups; only generations have sentiment. */
+ generationEventId?: string
}
-export function EventContentGeneration({
+// Renders an event's input/output, routing to one of two renderers: the chat UI
+// when recipes recognize both sides as a conversation, or a raw JSON view
+// otherwise. One path for generations, spans, and embeddings.
+export function EventContentConversation({
eventId,
traceId,
rawInput,
@@ -36,17 +41,20 @@ export function EventContentGeneration({
searchQuery,
displayOption,
highlightMessageIndex,
-}: EventContentGenerationProps): JSX.Element {
+ generationEventId,
+}: EventContentConversationProps): JSX.Element {
const { input, output, isLoading } = useAIData({
uuid: eventId,
input: rawInput,
output: rawOutput,
})
- // Map each normalized input message back to its original index in $ai_input.
- // This serves as a stable key for looking up per-message sentiment results,
- // regardless of how normalizeMessage expands/transforms messages.
+ // Map each normalized input message back to its original index in $ai_input,
+ // a stable key for per-message sentiment lookups. Generations only.
const inputSourceIndices = React.useMemo(() => {
+ if (!generationEventId) {
+ return undefined
+ }
const indices: number[] = []
if (tools) {
indices.push(-1) // tools message prepended by normalizeMessages
@@ -60,16 +68,29 @@ export function EventContentGeneration({
}
}
return indices
- }, [input, tools])
+ }, [input, tools, generationEventId])
+
+ const { recognized: inputRecognized, messages: inputMessages } = React.useMemo(
+ () => normalizeMessages(input, 'user', tools),
+ [input, tools]
+ )
+ const { recognized: outputRecognized, messages: outputMessages } = React.useMemo(
+ () => normalizeMessages(output, 'assistant'),
+ [output]
+ )
if (isLoading) {
return <AIDataLoading variant="block" />
}
+ if (!inputRecognized || !outputRecognized) {
+ return <JsonInputOutput input={input} output={output} errorData={errorData} raisedError={raisedError} />
+ }
+
return (
<ConversationMessagesDisplay
- inputNormalized={normalizeMessages(input, 'user', tools)}
- outputNormalized={normalizeMessages(output, 'assistant')}
+ inputNormalized={inputMessages}
+ outputNormalized={outputMessages}
inputSourceIndices={inputSourceIndices}
errorData={errorData}
httpStatus={typeof httpStatus === 'number' ? httpStatus : undefined}
@@ -77,35 +98,26 @@ export function EventContentGeneration({
searchQuery={searchQuery}
displayOption={displayOption}
traceId={traceId}
- generationEventId={eventId}
+ generationEventId={generationEventId}
highlightMessageIndex={highlightMessageIndex}
/>
)
}
-interface EventContentDisplayAsyncProps {
- eventId: string
- rawInput: unknown
- rawOutput: unknown
- raisedError?: boolean
-}
-
-export function EventContentDisplayAsync({
- eventId,
- rawInput,
- rawOutput,
+// Raw renderer for input/output that no recipe recognized as a conversation.
+function JsonInputOutput({
+ input,
+ output,
+ errorData,
raisedError,
-}: EventContentDisplayAsyncProps): JSX.Element {
- const { input, output, isLoading } = useAIData({
- uuid: eventId,
- input: rawInput,
- output: rawOutput,
- })
-
- if (isLoading) {
- return <AIDataLoading variant="block" />
- }
-
+}: {
+ input: unknown
+ output: unknown
+ errorData?: unknown
+ raisedError?: boolean
+}): JSX.Element {
+ // On error, surface the error payload when there's no output to show.
+ const outputValue = raisedError ? (output ?? errorData) : output
return (
<div className="space-y-4">
<div>
@@ -121,7 +133,7 @@ export function EventContentDisplayAsync({
raisedError ? 'bg-danger-highlight' : 'bg-surface-secondary'
}`}
>
- <JSONValueDisplay value={output} />
+ <JSONValueDisplay value={outputValue} />
</div>
</div>
</div>
diff --git a/products/ai_observability/frontend/extractSessionTurns.ts b/products/ai_observability/frontend/extractSessionTurns.ts
index b28be5923f58..df4743f83671 100644
--- a/products/ai_observability/frontend/extractSessionTurns.ts
+++ b/products/ai_observability/frontend/extractSessionTurns.ts
@@ -107,7 +107,7 @@ export function getToolNamesCalled(events: LLMTraceEvent[]): string[] {
names.push(spanName)
}
} else if (event.event === '$ai_generation') {
- for (const msg of normalizeMessages(event.properties.$ai_output_choices, 'assistant')) {
+ for (const msg of normalizeMessages(event.properties.$ai_output_choices, 'assistant').messages) {
for (const tc of msg.tool_calls ?? []) {
const name = tc.function?.name
if (typeof name === 'string' && name) {
@@ -204,8 +204,8 @@ export function extractSessionTurns(traces: LLMTrace[], fullTraces: Record<strin
const rawOutput = readAiOutput(properties)
const aiTools = properties.$ai_tools
- const inputMessages = normalizeMessages(rawInput, 'user', aiTools)
- const outputMessages = normalizeMessages(rawOutput, 'assistant')
+ const inputMessages = normalizeMessages(rawInput, 'user', aiTools).messages
+ const outputMessages = normalizeMessages(rawOutput, 'assistant').messages
const newInputs: CompatMessage[] = []
const msgCountThisTurn = new Map<string, number>()
diff --git a/products/ai_observability/frontend/messageNormalization.test.ts b/products/ai_observability/frontend/messageNormalization.test.ts
index 70225f42066e..af5572b7a20a 100644
--- a/products/ai_observability/frontend/messageNormalization.test.ts
+++ b/products/ai_observability/frontend/messageNormalization.test.ts
@@ -1,6 +1,14 @@
-import { normalizeMessage, normalizeMessages } from './messageNormalization'
+import posthog from 'posthog-js'
+
+import { captureNormalizationFailure, normalizeMessage, normalizeMessages } from './messageNormalization'
+
+jest.mock('posthog-js', () => ({ __esModule: true, default: { capture: jest.fn() } }))
+
+const capture = jest.mocked(posthog.capture)
describe('messageNormalization', () => {
+ beforeEach(() => jest.clearAllMocks())
+
describe('delegates to the recipe normalizer', () => {
it('normalizeMessage normalizes a single message', () => {
expect(normalizeMessage({ role: 'assistant', content: 'hi' }, 'user')).toEqual([
@@ -10,12 +18,50 @@ describe('messageNormalization', () => {
it('normalizeMessages prepends an available-tools pseudo-message when tools are passed', () => {
const result = normalizeMessages({ role: 'user', content: 'hi' }, 'user', [{ name: 'search' }])
- expect(result[0]).toEqual({ role: 'available tools', content: '', tools: [{ name: 'search' }] })
+ expect(result.messages[0]).toEqual({ role: 'available tools', content: '', tools: [{ name: 'search' }] })
})
it('normalizeMessages carries no message for nullish/scalar input', () => {
- expect(normalizeMessages(null, 'user')).toEqual([])
- expect(normalizeMessages(42, 'user')).toEqual([])
+ expect(normalizeMessages(null, 'user').messages).toEqual([])
+ expect(normalizeMessages(42, 'user').messages).toEqual([])
+ })
+ })
+
+ describe('normalizeMessages recognition', () => {
+ it('reports a recognized conversation alongside its messages', () => {
+ expect(normalizeMessages({ role: 'assistant', content: 'hi' }, 'user')).toEqual({
+ messages: [{ role: 'assistant', content: 'hi' }],
+ recognized: true,
+ })
+ })
+
+ it('reports opaque state as unrecognized and salvages it', () => {
+ const result = normalizeMessages({ file_path: 'src/index.ts' }, 'user')
+ expect(result.recognized).toBe(false)
+ expect(result.messages).toHaveLength(1)
+ })
+
+ it("never captures — reporting a failure is the caller's decision", () => {
+ normalizeMessages({ file_path: 'src/index.ts' }, 'user')
+ expect(capture).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('captureNormalizationFailure', () => {
+ it('reports an object payload with its keys and type', () => {
+ captureNormalizationFailure({ file_path: 'src/index.ts' })
+ expect(capture).toHaveBeenCalledWith('llma message normalization failed', {
+ message_keys: ['file_path'],
+ message_type: 'object',
+ })
+ })
+
+ it('reports a scalar payload with no keys', () => {
+ captureNormalizationFailure('opaque')
+ expect(capture).toHaveBeenCalledWith('llma message normalization failed', {
+ message_keys: [],
+ message_type: 'string',
+ })
})
})
})
diff --git a/products/ai_observability/frontend/messageNormalization.ts b/products/ai_observability/frontend/messageNormalization.ts
index 267089bfaa3a..0a76d235a38f 100644
--- a/products/ai_observability/frontend/messageNormalization.ts
+++ b/products/ai_observability/frontend/messageNormalization.ts
@@ -1,6 +1,10 @@
-import { mergeRecipes, RecipeNormalizer, StoredRecipe } from './normalizer'
+import posthog from 'posthog-js'
+
+import { mergeRecipes, RecipeNormalizer, RunOutcome, StoredRecipe } from './normalizer'
import { CompatMessage } from './types'
+export type NormalizationResult = RunOutcome
+
// Constructed once: the constructor compiles and sorts every recipe, so per-call
// construction would be wasteful.
const recipeNormalizer = new RecipeNormalizer()
@@ -17,9 +21,16 @@ export function applyTeamParserRecipes(stored: StoredRecipe[]): void {
}
export function normalizeMessage(input: unknown, defaultRole: string): CompatMessage[] {
- return recipeNormalizer.normalizeMessage(input, defaultRole)
+ return recipeNormalizer.normalizeMessage(input, defaultRole).messages
}
-export function normalizeMessages(input: unknown, defaultRole: string, tools?: unknown): CompatMessage[] {
+export function normalizeMessages(input: unknown, defaultRole: string, tools?: unknown): NormalizationResult {
return recipeNormalizer.normalizeMessages(input, defaultRole, tools)
}
+
+export function captureNormalizationFailure(input: unknown): void {
+ posthog.capture('llma message normalization failed', {
+ message_keys: typeof input === 'object' && input !== null ? Object.keys(input) : [],
+ message_type: typeof input,
+ })
+}
diff --git a/products/ai_observability/frontend/normalizer/index.ts b/products/ai_observability/frontend/normalizer/index.ts
index aa82ccd27bc1..212d1347797f 100644
--- a/products/ai_observability/frontend/normalizer/index.ts
+++ b/products/ai_observability/frontend/normalizer/index.ts
@@ -1,8 +1,8 @@
-// Recipe-based parallel to the legacy `../utils` normalizer. Production routes
-// through `../messageNormalization`, which flag-switches between the two; this
-// module is also exercised directly by the parity test suite.
+// The recipe-based message normalizer. Production routes through
+// `../messageNormalization`; this module is also exercised directly by tests.
export { RecipeNormalizer } from './recipe/recipeNormalizer'
+export type { RunOutcome } from './recipe/runtime/pipeline'
export { mergeRecipes } from './recipe/merge'
export type { StoredRecipe } from './recipe/merge'
export { compileRecipe } from './recipe/compile/compiler'
diff --git a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.test.ts b/products/ai_observability/frontend/normalizer/recipe/compile/compiler.test.ts
index f4df95684cfa..9ce502a8b229 100644
--- a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.test.ts
+++ b/products/ai_observability/frontend/normalizer/recipe/compile/compiler.test.ts
@@ -4,8 +4,6 @@ import { SlotCoercer } from '../runtime/coercion'
import { Scope } from '../scope'
import { compileRecipe } from './compiler'
-jest.mock('posthog-js', () => ({ __esModule: true, default: { capture: jest.fn() } }))
-
const ENGINE: DispatchEngine = { dispatch: () => NO_MATCH, coercer: new SlotCoercer() }
const INPUT = { name: 'Ada', items: ['a', 'b'] }
diff --git a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts b/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts
index 34d8f2189b8c..50ad88ac8207 100644
--- a/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts
+++ b/products/ai_observability/frontend/normalizer/recipe/compile/compiler.ts
@@ -63,7 +63,6 @@ export function compileRecipe(raw: unknown, fallbackId?: string): Recipe {
}
return {
id,
- capture: stringField(raw, 'capture'),
rules: rulesRaw.map((r, i) => {
try {
return compileRule(r)
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/cajole.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/cajole.yaml
deleted file mode 100644
index b3c4a82c9935..000000000000
--- a/products/ai_observability/frontend/normalizer/recipe/default_recipes/cajole.yaml
+++ /dev/null
@@ -1,17 +0,0 @@
-# Last-resort salvage for shapes no provider matched. `capture:` fires on match
-# so brand-new shapes still surface in telemetry. Highest priority so it runs last.
-
-id: cajole
-capture: llma message normalization failed
-
-rules:
- - on:
- content: { is: string }
- emit:
- content: $.content
-
- - on:
- $: { exists: true }
- emit:
- content:
- stringify: $
diff --git a/products/ai_observability/frontend/normalizer/recipe/default_recipes/typed_agent_items.yaml b/products/ai_observability/frontend/normalizer/recipe/default_recipes/typed_agent_items.yaml
index 9d5ea42f000c..cc1450ffdf25 100644
--- a/products/ai_observability/frontend/normalizer/recipe/default_recipes/typed_agent_items.yaml
+++ b/products/ai_observability/frontend/normalizer/recipe/default_recipes/typed_agent_items.yaml
@@ -2,7 +2,7 @@
# {type: message, role, content}, {type: tool_call, callId, name, arguments},
# {type: tool_result, callId, name, output}. Items arrive as array elements that
# the dispatcher flattens, so each is matched here on its own. Without these,
-# tool_call / tool_result items match nothing and fall to cajole's stringify.
+# tool_call / tool_result items match nothing and fall to the catch-all stringify.
id: typed_agent_items
diff --git a/products/ai_observability/frontend/normalizer/recipe/merge.test.ts b/products/ai_observability/frontend/normalizer/recipe/merge.test.ts
index f9b6c90cd94d..d149ce5c5ace 100644
--- a/products/ai_observability/frontend/normalizer/recipe/merge.test.ts
+++ b/products/ai_observability/frontend/normalizer/recipe/merge.test.ts
@@ -9,15 +9,13 @@ describe('mergeRecipes', () => {
expect(ids(mergeRecipes([]))).toEqual(builtinIds())
})
- it('identifies customs by their database id, not any id in the source, before the catch-all', () => {
+ it('identifies customs by their database id, not any id in the source, and runs them last', () => {
const customs: StoredRecipe[] = [
{ id: 'db-first', source: 'rules: []\n' },
{ id: 'db-second', source: 'id: ignored\nrules: []\n' },
]
const merged = ids(mergeRecipes(customs))
- const cajoleIndex = merged.indexOf('cajole')
- expect(merged.slice(cajoleIndex - 2, cajoleIndex)).toEqual(['db-first', 'db-second'])
- expect(merged[merged.length - 1]).toBe('cajole')
+ expect(merged.slice(-2)).toEqual(['db-first', 'db-second'])
})
it('keeps every builtin present alongside the customs', () => {
diff --git a/products/ai_observability/frontend/normalizer/recipe/merge.ts b/products/ai_observability/frontend/normalizer/recipe/merge.ts
index 11d690cc091e..0239d92424b7 100644
--- a/products/ai_observability/frontend/normalizer/recipe/merge.ts
+++ b/products/ai_observability/frontend/normalizer/recipe/merge.ts
@@ -12,17 +12,14 @@ export interface StoredRecipe {
}
// Resolve a team's custom recipes into the ordered set the pipeline runs: the bundled
-// builtins in their dispatch order, with the team's customs spliced in (in their stored
-// order) right before the last builtin (`cajole`, the last-resort catch-all) so they get
-// a shot at inputs the specific builtins miss while never shadowing them. A custom that
-// fails to compile is skipped — there's no builtin to fall back to — so a bad edit can
-// never break trace rendering. The catch-all must stay last in the bundled order.
+// builtins in their dispatch order, followed by the team's customs (in their stored
+// order). Customs run last among the matchers — after every builtin but before the
+// pipeline's catch-all salvage — so they catch inputs the builtins miss without ever
+// shadowing them. A custom that fails to compile is skipped, so a bad edit can never
+// break trace rendering.
export function mergeRecipes(stored: StoredRecipe[]): Recipe[] {
- const builtins = loadRecipes()
const customs = stored.map(tryCompile).filter((recipe): recipe is Recipe => recipe !== undefined)
-
- const insertAt = builtins.length - 1
- return [...builtins.slice(0, insertAt), ...customs, ...builtins.slice(insertAt)]
+ return [...loadRecipes(), ...customs]
}
function tryCompile(recipe: StoredRecipe): Recipe | undefined {
diff --git a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.ts b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.ts
index 22d16b227dd9..36ce37402286 100644
--- a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.ts
+++ b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.test.ts
@@ -1,12 +1,10 @@
import { AVAILABLE_TOOLS_ROLE } from '../../utils'
import { RecipeNormalizer } from './recipeNormalizer'
-import { NO_MATCH } from './runtime/pipeline'
const mockRun = jest.fn()
jest.mock('./registry', () => ({ loadRecipes: () => [] }))
jest.mock('./runtime/pipeline', () => ({
- NO_MATCH: Symbol('no-match'),
RecipePipeline: jest.fn().mockImplementation(() => ({ run: mockRun })),
}))
@@ -19,37 +17,45 @@ describe('RecipeNormalizer', () => {
})
describe('normalizeMessage', () => {
- it("returns the pipeline's normalized messages for a matched input", () => {
- const messages = [{ role: 'assistant', content: 'hi' }]
- mockRun.mockReturnValue(messages)
- expect(normalizer.normalizeMessage({ role: 'assistant' }, 'user')).toBe(messages)
+ it("returns the pipeline's outcome for a matched input", () => {
+ const outcome = { messages: [{ role: 'assistant', content: 'hi' }], recognized: true }
+ mockRun.mockReturnValue(outcome)
+ expect(normalizer.normalizeMessage({ role: 'assistant' }, 'user')).toBe(outcome)
})
- it('returns no messages for undefined input without dispatching', () => {
- expect(normalizer.normalizeMessage(undefined, 'user')).toEqual([])
+ it('returns an empty recognized result for undefined input without dispatching', () => {
+ expect(normalizer.normalizeMessage(undefined, 'user')).toEqual({ messages: [], recognized: true })
expect(mockRun).not.toHaveBeenCalled()
})
- it('throws when nothing matches (catch-all coverage gap)', () => {
- mockRun.mockReturnValue(NO_MATCH)
- expect(() => normalizer.normalizeMessage({ weird: true }, 'user')).toThrow(/no recipe matched/)
+ it('passes through an unrecognized outcome without throwing', () => {
+ mockRun.mockReturnValue({ messages: [{ role: 'user', content: 'salvaged' }], recognized: false })
+ expect(normalizer.normalizeMessage({ weird: true }, 'user')).toEqual({
+ messages: [{ role: 'user', content: 'salvaged' }],
+ recognized: false,
+ })
})
})
describe('normalizeMessages', () => {
it('prepends an available-tools message when tools are given', () => {
- mockRun.mockReturnValue([{ role: 'assistant', content: 'hi' }])
+ mockRun.mockReturnValue({ messages: [{ role: 'assistant', content: 'hi' }], recognized: true })
const tools = [{ name: 'search' }]
- expect(normalizer.normalizeMessages({ role: 'assistant' }, 'user', tools)).toEqual([
- { role: AVAILABLE_TOOLS_ROLE, content: '', tools },
- { role: 'assistant', content: 'hi' },
- ])
+ expect(normalizer.normalizeMessages({ role: 'assistant' }, 'user', tools)).toEqual({
+ messages: [
+ { role: AVAILABLE_TOOLS_ROLE, content: '', tools },
+ { role: 'assistant', content: 'hi' },
+ ],
+ recognized: true,
+ })
})
- it('without tools just returns the normalized messages', () => {
- const messages = [{ role: 'assistant', content: 'hi' }]
- mockRun.mockReturnValue(messages)
- expect(normalizer.normalizeMessages({ role: 'assistant' }, 'user')).toEqual(messages)
+ it('propagates the recognized verdict from the input dispatch', () => {
+ mockRun.mockReturnValue({ messages: [{ role: 'assistant', content: 'hi' }], recognized: false })
+ expect(normalizer.normalizeMessages({ role: 'assistant' }, 'user')).toEqual({
+ messages: [{ role: 'assistant', content: 'hi' }],
+ recognized: false,
+ })
})
})
})
diff --git a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts
index ab028e80f704..4afc4fbc7b71 100644
--- a/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts
+++ b/products/ai_observability/frontend/normalizer/recipe/recipeNormalizer.ts
@@ -1,7 +1,7 @@
import { CompatMessage } from '../../types'
import { AVAILABLE_TOOLS_ROLE } from '../../utils'
import { loadRecipes } from './registry'
-import { NO_MATCH, RecipePipeline } from './runtime/pipeline'
+import { RecipePipeline, RunOutcome } from './runtime/pipeline'
import { Recipe } from './spec/recipe'
export class RecipeNormalizer {
@@ -15,30 +15,27 @@ export class RecipeNormalizer {
this.pipeline = new RecipePipeline(recipes)
}
- normalizeMessage(input: unknown, defaultRole: string): CompatMessage[] {
- // `undefined` carries no message (a missing field, a sparse array slot). cajole
- // intentionally doesn't match it, so handle it here rather than dispatch a miss.
+ normalizeMessage(input: unknown, defaultRole: string): RunOutcome {
+ // `undefined` carries no message (a missing field, a sparse array slot) and
+ // nothing to recognize — treat as an empty, recognized result.
if (input === undefined) {
- return []
+ return { messages: [], recognized: true }
}
- const result = this.pipeline.run(input, defaultRole)
- if (result === NO_MATCH) {
- // cajole.yaml matches anything, so NO_MATCH means a coverage gap, not a normal miss.
- throw new Error(`RecipeNormalizer: no recipe matched — cajole.yaml should be the final catch-all`)
- }
- return result
+ return this.pipeline.run(input, defaultRole)
}
- normalizeMessages(input: unknown, defaultRole: string, tools?: unknown): CompatMessage[] {
+ normalizeMessages(input: unknown, defaultRole: string, tools?: unknown): RunOutcome {
const messages: CompatMessage[] = []
if (tools) {
// `tools` is a function parameter, not a message shape, so it has no recipe.
messages.push({ role: AVAILABLE_TOOLS_ROLE, content: '', tools })
}
if (carriesMessages(input)) {
- messages.push(...this.normalizeMessage(input, defaultRole))
+ const outcome = this.normalizeMessage(input, defaultRole)
+ messages.push(...outcome.messages)
+ return { messages, recognized: outcome.recognized }
}
- return messages
+ return { messages, recognized: true }
}
}
diff --git a/products/ai_observability/frontend/normalizer/recipe/registry.ts b/products/ai_observability/frontend/normalizer/recipe/registry.ts
index 9b856d35c317..a30e34792619 100644
--- a/products/ai_observability/frontend/normalizer/recipe/registry.ts
+++ b/products/ai_observability/frontend/normalizer/recipe/registry.ts
@@ -2,7 +2,6 @@ import { parse as parseYaml } from 'yaml'
import { compileRecipe } from './compile/compiler'
import anthropic from './default_recipes/anthropic.yaml?raw'
-import cajole from './default_recipes/cajole.yaml?raw'
import compatArray from './default_recipes/compat_array.yaml?raw'
import dispatcherEntry from './default_recipes/dispatcher_entry.yaml?raw'
import langchain from './default_recipes/langchain.yaml?raw'
@@ -30,7 +29,6 @@ const RECIPE_SOURCES: readonly string[] = [
anthropic,
otel,
wrappers,
- cajole,
]
const RECIPES: Recipe[] = []
diff --git a/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.ts b/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.ts
index e7efb0d4dfca..571cd22d7382 100644
--- a/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.ts
+++ b/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.test.ts
@@ -24,22 +24,46 @@ class StubRule extends Rule {
const recipe = (id: string, rule: Rule): Recipe => ({ id, rules: [rule] })
describe('RecipePipeline', () => {
- it('dispatches to the matching rule and returns its messages', () => {
+ it('dispatches to the matching rule and returns its messages as recognized', () => {
const messages: CompatMessage[] = [{ role: 'user', content: 'hi' }]
const pipeline = new RecipePipeline([recipe('only', new StubRule(MATCH_ALL, messages))])
- expect(pipeline.run({ role: 'user' }, 'user')).toEqual(messages)
+ expect(pipeline.run({ role: 'user' }, 'user')).toEqual({ messages, recognized: true })
})
it('when several recipes match, the first in order wins', () => {
const first = recipe('first', new StubRule(MATCH_ALL, [{ role: 'user', content: 'first-wins' }]))
const second = recipe('second', new StubRule(MATCH_ALL, [{ role: 'user', content: 'second' }]))
const pipeline = new RecipePipeline([first, second])
- expect(pipeline.run({ role: 'user' }, 'user')).toEqual([{ role: 'user', content: 'first-wins' }])
+ expect(pipeline.run({ role: 'user' }, 'user')).toEqual({
+ messages: [{ role: 'user', content: 'first-wins' }],
+ recognized: true,
+ })
})
- it('returns NO_MATCH when no rule matches', () => {
+ it('salvages input no recipe claims by stringifying it, reported as unrecognized', () => {
const pipeline = new RecipePipeline([recipe('none', new StubRule(MATCH_NONE, []))])
- expect(pipeline.run({ role: 'user' }, 'user')).toBe(NO_MATCH)
+ expect(pipeline.run({ weird: true }, 'user')).toEqual({
+ messages: [{ role: 'user', content: '{"weird":true}' }],
+ recognized: false,
+ })
+ })
+
+ it('salvages a string `content` field as-is rather than stringifying the wrapper', () => {
+ const pipeline = new RecipePipeline([recipe('none', new StubRule(MATCH_NONE, []))])
+ expect(pipeline.run({ content: 'hi', extra: 1 }, 'assistant')).toEqual({
+ messages: [{ role: 'assistant', content: 'hi' }],
+ recognized: false,
+ })
+ })
+
+ it('dispatch (delegation) salvages an unmatched child so it is not dropped', () => {
+ const pipeline = new RecipePipeline([recipe('none', new StubRule(MATCH_NONE, []))])
+ expect(pipeline.dispatch({ weird: true }, 'user', 0)).toEqual([{ role: 'user', content: '{"weird":true}' }])
+ })
+
+ it('dispatch (delegation) returns NO_MATCH for undefined so a delegating rule drops it', () => {
+ const pipeline = new RecipePipeline([recipe('none', new StubRule(MATCH_NONE, []))])
+ expect(pipeline.dispatch(undefined, 'user', 0)).toBe(NO_MATCH)
})
it('throws when recursion exceeds the max delegation depth', () => {
diff --git a/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.ts b/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.ts
index 36d661cdaea6..9b65eeb74f5d 100644
--- a/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.ts
+++ b/products/ai_observability/frontend/normalizer/recipe/runtime/pipeline.ts
@@ -1,5 +1,4 @@
-import posthog from 'posthog-js'
-
+import { CompatMessage } from '../../../types'
import { DispatchEngine, DispatchResult, NO_MATCH, Rule } from '../ast/rule'
import { Scope } from '../scope'
import { Recipe } from '../spec/recipe'
@@ -8,6 +7,11 @@ import { SlotCoercer } from './coercion'
export { NO_MATCH } from '../ast/rule'
export type { DispatchResult } from '../ast/rule'
+export interface RunOutcome {
+ messages: CompatMessage[]
+ recognized: boolean
+}
+
// Insurance against a recipe that delegates to a shape matching itself.
const MAX_DEPTH = 10
@@ -19,11 +23,23 @@ export class RecipePipeline implements DispatchEngine {
this.recipes = [...recipes]
}
- run(input: unknown, defaultRole: string): DispatchResult {
- return this.dispatch(input, defaultRole, 0)
+ run(input: unknown, defaultRole: string): RunOutcome {
+ const matched = this.matchRecipes(input, defaultRole, 0)
+ if (matched !== NO_MATCH) {
+ return { messages: matched, recognized: true }
+ }
+ const salvaged = this.salvage(input, defaultRole)
+ return { messages: salvaged === NO_MATCH ? [] : salvaged, recognized: false }
}
+ // Delegation (delegate/delegateEach) salvages unmatched children so nested
+ // fragments survive instead of being dropped.
dispatch(input: unknown, inheritedRole: string, depth: number): DispatchResult {
+ const matched = this.matchRecipes(input, inheritedRole, depth)
+ return matched !== NO_MATCH ? matched : this.salvage(input, inheritedRole)
+ }
+
+ private matchRecipes(input: unknown, inheritedRole: string, depth: number): DispatchResult {
if (depth > MAX_DEPTH) {
throw new Error(
`RecipeNormalizer: delegation exceeded max depth (${MAX_DEPTH}) — a recipe likely delegates to itself`
@@ -33,12 +49,6 @@ export class RecipePipeline implements DispatchEngine {
for (const rule of recipe.rules) {
const result = this.applyRule(rule, input, inheritedRole, depth)
if (result !== NO_MATCH) {
- if (recipe.capture) {
- posthog.capture(recipe.capture, {
- message_keys: typeof input === 'object' && input !== null ? Object.keys(input) : [],
- message_type: typeof input,
- })
- }
return result
}
}
@@ -46,6 +56,16 @@ export class RecipePipeline implements DispatchEngine {
return NO_MATCH
}
+ private salvage(input: unknown, inheritedRole: string): DispatchResult {
+ if (input === undefined) {
+ return NO_MATCH
+ }
+ const role = Scope.forNode(input, inheritedRole).role
+ const content =
+ isPlainObject(input) && typeof input.content === 'string' ? input.content : stringifyContent(input)
+ return [{ role, content }]
+ }
+
private applyRule(rule: Rule, input: unknown, inheritedRole: string, depth: number): DispatchResult {
if (!rule.on.matches(input)) {
return NO_MATCH
@@ -60,3 +80,21 @@ export class RecipePipeline implements DispatchEngine {
return [...primary, ...followups]
}
}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function stringifyContent(value: unknown): string {
+ if (value === null) {
+ return ''
+ }
+ if (typeof value === 'string') {
+ return value
+ }
+ try {
+ return JSON.stringify(value) ?? ''
+ } catch {
+ return String(value)
+ }
+}
diff --git a/products/ai_observability/frontend/normalizer/recipe/spec/recipe.ts b/products/ai_observability/frontend/normalizer/recipe/spec/recipe.ts
index 85a0ed10d89d..0fa4af5aa860 100644
--- a/products/ai_observability/frontend/normalizer/recipe/spec/recipe.ts
+++ b/products/ai_observability/frontend/normalizer/recipe/spec/recipe.ts
@@ -3,8 +3,4 @@ import type { Rule } from '../ast/rule'
export interface Recipe {
id: string
rules: Rule[]
- // Fires a PostHog capture on every dispatch match — including recursive
- // delegation, so only set it on a recipe that is never delegated into (a
- // terminal catch-all like cajole), or it fires more than once per message.
- capture?: string
}
diff --git a/products/ai_observability/frontend/searchUtils.ts b/products/ai_observability/frontend/searchUtils.ts
index 36031bfbae2d..1ae3fb45dff1 100644
--- a/products/ai_observability/frontend/searchUtils.ts
+++ b/products/ai_observability/frontend/searchUtils.ts
@@ -256,7 +256,7 @@ export function findSidebarOccurrences(
export function findMessageOccurrences(
events: Array<{ id: string; event?: string; properties: Record<string, any> }>,
query: string,
- normalizeMessages: (input: any, defaultRole: string, tools?: any) => any[]
+ normalizeMessages: (input: any, defaultRole: string, tools?: any) => { messages: any[] }
): SearchOccurrence[] {
if (!query.trim()) {
return []
@@ -279,7 +279,11 @@ export function findMessageOccurrences(
// Input messages
if (event.event === '$ai_generation') {
- const normalizedInput = normalizeMessages(event.properties.$ai_input, 'user', event.properties.$ai_tools)
+ const normalizedInput = normalizeMessages(
+ event.properties.$ai_input,
+ 'user',
+ event.properties.$ai_tools
+ ).messages
normalizedInput.forEach((msg, msgIndex) => {
// Content
const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content)
@@ -327,7 +331,7 @@ export function findMessageOccurrences(
// Output messages
if (event.event === '$ai_generation') {
const outputToNormalize = event.properties.$ai_output_choices ?? event.properties.$ai_output
- const normalizedOutput = normalizeMessages(outputToNormalize, 'assistant')
+ const normalizedOutput = normalizeMessages(outputToNormalize, 'assistant').messages
normalizedOutput.forEach((msg, msgIndex) => {
// Content
diff --git a/products/ai_observability/frontend/sessionTitle.ts b/products/ai_observability/frontend/sessionTitle.ts
index d5b0415f5e88..8c65d42410b8 100644
--- a/products/ai_observability/frontend/sessionTitle.ts
+++ b/products/ai_observability/frontend/sessionTitle.ts
@@ -89,7 +89,7 @@ function firstUserText(inputPayload: unknown): string | null {
Array.isArray((inputPayload as { messages?: unknown }).messages)
? (inputPayload as { messages: unknown[] }).messages
: inputPayload
- const normalized = normalizeMessages(messages, 'user')
+ const normalized = normalizeMessages(messages, 'user').messages
for (const message of normalized) {
if (message.role !== 'user') {
continue
diff --git a/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsx b/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsx
index b667a2e86a7d..0b796ade4165 100644
--- a/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsx
+++ b/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsx
@@ -44,7 +44,7 @@ function getMessageAtIndex(aiInput: unknown, index: number): CompatMessage | nul
if (!Array.isArray(parsed) || index < 0 || index >= parsed.length) {
return null
}
- const normalized = normalizeMessages([parsed[index]], 'user')
+ const normalized = normalizeMessages([parsed[index]], 'user').messages
return normalized[0] ?? null
} catch {
return null
diff --git a/products/ai_observability/frontend/traceExportUtils.ts b/products/ai_observability/frontend/traceExportUtils.ts
index 996edef45ef7..92f2e2a2c3d1 100644
--- a/products/ai_observability/frontend/traceExportUtils.ts
+++ b/products/ai_observability/frontend/traceExportUtils.ts
@@ -68,8 +68,8 @@ function buildEventExport(event: LLMTraceEvent, children?: EnrichedTraceTreeNode
// Handle input/output based on event type
if (isGeneration) {
// For generations, normalize messages without tools
- const inputMessages: CompatMessage[] = normalizeMessages(event.properties.$ai_input, 'user')
- const outputMessages: CompatMessage[] = normalizeMessages(readAiOutput(event.properties), 'assistant')
+ const inputMessages: CompatMessage[] = normalizeMessages(event.properties.$ai_input, 'user').messages
+ const outputMessages: CompatMessage[] = normalizeMessages(readAiOutput(event.properties), 'assistant').messages
const messages: CompatMessage[] = []
if (inputMessages.length > 0) {
diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.ts
index b5fa32d47b36..36ddc40225c6 100644
--- a/products/ai_observability/frontend/utils.test.ts
+++ b/products/ai_observability/frontend/utils.test.ts
@@ -30,8 +30,8 @@ const recipe = new RecipeNormalizer()
const IMPLS = [
{
name: 'recipe',
- normalizeMessage: (r: unknown, d: string) => recipe.normalizeMessage(r, d),
- normalizeMessages: (m: unknown, d: string, t?: unknown) => recipe.normalizeMessages(m, d, t),
+ normalizeMessage: (r: unknown, d: string) => recipe.normalizeMessage(r, d).messages,
+ normalizeMessages: (m: unknown, d: string, t?: unknown) => recipe.normalizeMessages(m, d, t).messages,
},
] as const