: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
chore(llma): remove legacy message normalizer and comparison layer (#61911)
Carlos Marchalc991f2ba3100
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex e9f580f450e7..636609756df9 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -323,6 +323,7 @@ export const FEATURE_FLAGS = {LIVESTREAM_TUI: 'livestream-tui', // owner: @rafaeelaudibert #team-growthLLM_ANALYTICS_CLUSTERING_ADMIN: 'llm-analytics-clustering-admin', // owner: #team-ai-observabilityLLM_ANALYTICS_CLUSTERS_TAB: 'llm-analytics-clusters-tab', // owner: #team-ai-observability+ LLM_ANALYTICS_CUSTOM_PARSERS: 'ai-observability-custom-parsers', // owner: #team-ai-observabilityLLM_ANALYTICS_DATASETS: 'llm-analytics-datasets', // owner: #team-ai-observability #team-posthog-aiLLM_ANALYTICS_DISCUSSIONS: 'llm-analytics-discussions', // owner: #team-ai-observabilityLLM_ANALYTICS_EARLY_ADOPTERS: 'llm-analytics-early-adopters', // owner: #team-ai-observability@@ -333,7 +334,6 @@ export const FEATURE_FLAGS = {LLM_ANALYTICS_EVALUATIONS_REPORTS: 'llm-analytics-evaluations-reports', // owner: #team-ai-observabilityLLM_ANALYTICS_EVALUATIONS_SUMMARY: 'llm-analytics-evaluations-summary', // owner: #team-ai-observabilityLLM_ANALYTICS_OFFLINE_EVALS: 'llm-analytics-offline-evals', // owner: #team-ai-observability- LLM_ANALYTICS_RECIPE_NORMALIZER: 'llm-analytics-recipe-normalizer', // owner: #team-ai-observabilityLLM_ANALYTICS_SENTIMENT: 'llm-analytics-sentiment', // owner: #team-ai-observabilityLLM_ANALYTICS_SENTIMENT_TAB: 'llm-analytics-sentiment-tab', // owner: #team-ai-observabilityLLM_ANALYTICS_SESSION_SUMMARIZATION: 'llm-analytics-session-summarization', // owner: #team-ai-observabilitydiff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 1d73bd89654e..36621d7de9c8 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -361,7 +361,7 @@ export const SETTINGS_MAP: SettingSection[] = [description:"Add recipes that normalize provider message shapes the built-in recipes don't cover. They apply when rendering traces.",component: <ParserRecipesSettings />,- flag: 'LLM_ANALYTICS_RECIPE_NORMALIZER',+ flag: 'LLM_ANALYTICS_CUSTOM_PARSERS',keywords: ['parser', 'recipe', 'normalize', 'trace', 'provider', 'custom parsing', 'content'],},],diff --git a/products/ai_observability/frontend/extractSessionTurns.test.ts b/products/ai_observability/frontend/extractSessionTurns.test.tsindex 7dd1e980566a..2d341c837061 100644--- a/products/ai_observability/frontend/extractSessionTurns.test.ts+++ b/products/ai_observability/frontend/extractSessionTurns.test.ts@@ -3,6 +3,7 @@ import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'import {buildInputSourceIndices,extractSessionTurns,+ getToolNamesCalled,pickUserVisibleTurn,SessionTurnError,} from './extractSessionTurns'@@ -793,3 +794,188 @@ describe('extractSessionTurns — real production shapes (anonymized)', () => {expect(() => extractSessionTurns([t1, t2], { t1, t2 })).not.toThrow()})})++describe('getToolNamesCalled', () => {+ const span = (id: string, createdAt: string, spanName?: string): LLMTraceEvent => ({+ id,+ event: '$ai_span',+ createdAt,+ properties: spanName ? { $ai_span_name: spanName } : {},+ })+ const generation = (id: string, createdAt: string, outputChoices: unknown): LLMTraceEvent => ({+ id,+ event: '$ai_generation',+ createdAt,+ properties: { $ai_output_choices: outputChoices },+ })++ it('returns [] for an empty event list', () => {+ expect(getToolNamesCalled([])).toEqual([])+ })++ it('returns `$ai_span_name` from instrumented span events', () => {+ const events = [span('s1', '2026-05-11T00:00:00.000Z', 'fetch_user')]+ expect(getToolNamesCalled(events)).toEqual(['fetch_user'])+ })++ it('skips span events without a `$ai_span_name`', () => {+ const events = [span('s1', '2026-05-11T00:00:00.000Z')]+ expect(getToolNamesCalled(events)).toEqual([])+ })++ it('skips event types other than `$ai_span` and `$ai_generation`', () => {+ const events: LLMTraceEvent[] = [+ {+ id: 'trace',+ event: '$ai_trace',+ createdAt: '2026-05-11T00:00:00.000Z',+ properties: { $ai_span_name: 'irrelevant' },+ },+ ]+ expect(getToolNamesCalled(events)).toEqual([])+ })++ // Covers every output shape `normalizeMessages` understands — adding a new+ // SDK shape there should bring it under this case table without further+ // changes here.+ it.each<[name: string, outputChoices: unknown, expected: string[]]>([+ [+ 'OpenAI Chat Completions `tool_calls`',+ [+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ { id: 'a', type: 'function', function: { name: 'get_weather', arguments: '{}' } },+ { id: 'b', type: 'function', function: { name: 'search_docs', arguments: '{}' } },+ ],+ },+ ],+ ['get_weather', 'search_docs'],+ ],+ [+ 'Anthropic `tool_use` typed parts',+ [+ {+ role: 'assistant',+ content: [+ { type: 'text', text: 'Looking it up.' },+ { type: 'tool_use', id: 'toolu_1', name: 'get_weather', input: { city: 'Berlin' } },+ { type: 'tool_use', id: 'toolu_2', name: 'search_docs', input: {} },+ ],+ },+ ],+ ['get_weather', 'search_docs'],+ ],+ [+ 'OpenAI Responses `function_call` items',+ [+ { type: 'function_call', call_id: 'c1', name: 'get_weather', arguments: '{}' },+ { type: 'function_call', call_id: 'c2', name: 'search_docs', arguments: '{}' },+ ],+ ['get_weather', 'search_docs'],+ ],+ [+ 'Vercel SDK `tool-call` items',+ [+ { type: 'tool-call', toolCallId: 'a', toolName: 'get_weather', input: { city: 'Berlin' } },+ { type: 'tool-call', toolCallId: 'b', toolName: 'search_docs', input: {} },+ ],+ ['get_weather', 'search_docs'],+ ],+ [+ 'OpenAI Responses built-in tool calls',+ [+ { id: 'ws1', type: 'web_search_call', status: 'completed' },+ { id: 'mcp1', type: 'mcp_call', name: 'list_dashboards', status: 'completed' },+ ],+ ['web_search_call', 'list_dashboards'],+ ],+ [+ 'LiteLLM-style {choices:[{message:{tool_calls}}]} wrapper',+ {+ choices: [+ {+ finish_reason: 'tool_calls',+ index: 0,+ message: {+ role: 'assistant',+ content: null,+ tool_calls: [+ {+ id: 'a',+ type: 'function',+ function: { name: 'get_weather', arguments: '{"city":"Berlin"}' },+ },+ {+ id: 'b',+ type: 'function',+ function: { name: 'search_docs', arguments: '{}' },+ },+ ],+ },+ },+ ],+ },+ ['get_weather', 'search_docs'],+ ],+ ])('returns tool names from %s in $ai_generation outputs', (_, outputChoices, expected) => {+ const events = [generation('g1', '2026-05-11T00:00:00.000Z', outputChoices)]+ expect(getToolNamesCalled(events)).toEqual(expected)+ })++ it('preserves duplicates in the raw call sequence — caller decides whether to dedupe', () => {+ // Three identical tool calls across span + generation events should all appear.+ // Dedup is a session-page concern, not part of "what tools were called".+ const events = [+ span('s1', '2026-05-11T00:00:00.000Z', 'fetch_user'),+ generation('g1', '2026-05-11T00:00:01.000Z', [+ {+ role: 'assistant',+ content: '',+ tool_calls: [{ id: 'a', type: 'function', function: { name: 'fetch_user', arguments: '{}' } }],+ },+ ]),+ span('s2', '2026-05-11T00:00:02.000Z', 'fetch_user'),+ ]+ expect(getToolNamesCalled(events)).toEqual(['fetch_user', 'fetch_user', 'fetch_user'])+ })++ it('orders names chronologically regardless of input order', () => {+ // Events come back from ClickHouse in whatever order the query produced.+ const events = [+ span('s3', '2026-05-11T00:00:02.000Z', 'send_email'),+ span('s1', '2026-05-11T00:00:00.000Z', 'fetch_user'),+ span('s2', '2026-05-11T00:00:01.000Z', 'subscription_lookup'),+ ]+ expect(getToolNamesCalled(events)).toEqual(['fetch_user', 'subscription_lookup', 'send_email'])+ })++ it('skips tool calls with missing or empty names', () => {+ const events = [+ generation('g1', '2026-05-11T00:00:00.000Z', [+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ { id: 'a', type: 'function', function: { name: '', arguments: '{}' } },+ { id: 'b', type: 'function', function: { name: 'real_tool', arguments: '{}' } },+ ],+ },+ ]),+ ]+ expect(getToolNamesCalled(events)).toEqual(['real_tool'])+ })++ it('returns [] when a generation has no $ai_output_choices', () => {+ const events: LLMTraceEvent[] = [+ {+ id: 'g1',+ event: '$ai_generation',+ createdAt: '2026-05-11T00:00:00.000Z',+ properties: {},+ },+ ]+ expect(getToolNamesCalled(events)).toEqual([])+ })+})diff --git a/products/ai_observability/frontend/extractSessionTurns.ts b/products/ai_observability/frontend/extractSessionTurns.tsindex 70cd56908738..b28be5923f58 100644--- a/products/ai_observability/frontend/extractSessionTurns.ts+++ b/products/ai_observability/frontend/extractSessionTurns.ts@@ -3,7 +3,7 @@ import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'import { normalizeMessage, normalizeMessages } from './messageNormalization'import { messageSignature } from './messageSignature'import { CompatMessage } from './types'-import { eventLabel, formatAiErrorForDisplay, getToolNamesCalled, readAiInput, readAiOutput } from './utils'+import { eventLabel, formatAiErrorForDisplay, readAiInput, readAiOutput } from './utils'// Heuristic mirrors the AI observability skill script `print_summary.py` at// `products/ai_observability/skills/exploring-llm-traces/scripts/` — keep in sync.@@ -94,6 +94,32 @@ export interface SessionTurn {errors: SessionTurnError[]}+// Returns the tool names invoked across events in chronological order (duplicates preserved)+export function getToolNamesCalled(events: LLMTraceEvent[]): string[] {+ const sorted = [...events].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())+ const names: string[] = []+ // Pulls from `$ai_span_name` on instrumented `$ai_span` events+ // and from `tool_calls[].function.name` on normalized `$ai_generation` outputs+ for (const event of sorted) {+ if (event.event === '$ai_span') {+ const spanName = event.properties.$ai_span_name+ if (typeof spanName === 'string' && spanName) {+ names.push(spanName)+ }+ } else if (event.event === '$ai_generation') {+ for (const msg of normalizeMessages(event.properties.$ai_output_choices, 'assistant')) {+ for (const tc of msg.tool_calls ?? []) {+ const name = tc.function?.name+ if (typeof name === 'string' && name) {+ names.push(name)+ }+ }+ }+ }+ }+ return names+}+function getToolNamesCalledUnique(events: LLMTraceEvent[]): string[] {// `Set` insertion order preserves first-appearancereturn Array.from(new Set(getToolNamesCalled(events)))diff --git a/products/ai_observability/frontend/messageNormalization.test.ts b/products/ai_observability/frontend/messageNormalization.test.tsindex b66f33fc6ccb..70225f42066e 100644--- a/products/ai_observability/frontend/messageNormalization.test.ts+++ b/products/ai_observability/frontend/messageNormalization.test.ts@@ -1,147 +1,21 @@-import posthog, { JsonType } from 'posthog-js'--import { CompatMessage } from './types'--const mockRecipeNormalizeMessage = jest.fn()-const mockRecipeNormalizeMessages = jest.fn()--jest.mock('./normalizer', () => ({- RecipeNormalizer: jest.fn().mockImplementation(() => ({- normalizeMessage: mockRecipeNormalizeMessage,- normalizeMessages: mockRecipeNormalizeMessages,- })),-}))--jest.mock('./utils', () => ({- normalizeMessage: jest.fn(),- normalizeMessages: jest.fn(),-}))-import { normalizeMessage, normalizeMessages } from './messageNormalization'-import { normalizeMessage as legacyNormalizeMessage, normalizeMessages as legacyNormalizeMessages } from './utils'-const LEGACY: CompatMessage[] = [{ role: 'user', content: 'legacy' }]-const RECIPE: CompatMessage[] = [{ role: 'user', content: 'recipe' }]--const legacy = jest.mocked(legacyNormalizeMessages)-const legacyOne = jest.mocked(legacyNormalizeMessage)-const getFeatureFlagResult = jest.mocked(posthog.getFeatureFlagResult)-const capture = jest.mocked(posthog.capture)--function mockFlag(enabled: boolean, payload?: JsonType): void {- getFeatureFlagResult.mockReturnValue({ key: 'recipe-normalizer', enabled, variant: undefined, payload })-}--beforeEach(() => {- jest.clearAllMocks()- legacy.mockReturnValue(LEGACY)- legacyOne.mockReturnValue(LEGACY)- mockRecipeNormalizeMessages.mockReturnValue(RECIPE)- mockRecipeNormalizeMessage.mockReturnValue(RECIPE)-})--describe('messageNormalization — switch (unsampled) path', () => {- beforeEach(() => jest.spyOn(Math, 'random').mockReturnValue(0.5))-- it('runs only the legacy implementation when the flag is off', () => {- mockFlag(false)- expect(normalizeMessages({ role: 'user' }, 'user')).toBe(LEGACY)- expect(mockRecipeNormalizeMessages).not.toHaveBeenCalled()- })-- it('runs only the recipe implementation when the flag is on', () => {- mockFlag(true)- expect(normalizeMessages({ role: 'user' }, 'user')).toBe(RECIPE)- expect(legacy).not.toHaveBeenCalled()- })-- it('falls back to legacy and reports when the recipe implementation throws', () => {- mockFlag(true)- mockRecipeNormalizeMessages.mockImplementation(() => {- throw new Error('no recipe matched')+describe('messageNormalization', () => {+ describe('delegates to the recipe normalizer', () => {+ it('normalizeMessage normalizes a single message', () => {+ expect(normalizeMessage({ role: 'assistant', content: 'hi' }, 'user')).toEqual([+ { role: 'assistant', content: 'hi' },+ ])})- expect(normalizeMessages({ role: 'user' }, 'user')).toBe(LEGACY)- expect(capture).toHaveBeenCalledWith('llma recipe normalization fell back', {- error: 'no recipe matched',- })- })- it('does not emit a timing event off the sampled path', () => {- mockFlag(false)- normalizeMessages({ role: 'user' }, 'user')- expect(capture).not.toHaveBeenCalledWith('llma normalization timed', expect.anything())- })-- it('honors a higher sample_rate from the flag payload to force the sampled path', () => {- mockFlag(true, { sample_rate: 1 })- normalizeMessages({ role: 'user' }, 'user')- expect(capture).toHaveBeenCalledWith('llma normalization timed', expect.anything())- })-})--describe('messageNormalization — shadow (sampled) path', () => {- beforeEach(() => jest.spyOn(Math, 'random').mockReturnValue(0))-- it('runs both implementations and captures a timing comparison', () => {- mockFlag(false)- normalizeMessages({ role: 'user' }, 'user', [{ name: 'search' }])- expect(legacy).toHaveBeenCalledTimes(1)- expect(mockRecipeNormalizeMessages).toHaveBeenCalledTimes(1)- expect(capture).toHaveBeenCalledWith(- 'llma normalization timed',- expect.objectContaining({- op: 'normalizeMessages',- active_implementation: 'legacy',- default_role: 'user',- has_tools: true,- recipe_errored: false,- outputs_match: false,- message_count: 1,- legacy_duration_ms: expect.any(Number),- recipe_duration_ms: expect.any(Number),- })- )- })-- it('reports outputs_match true when both implementations agree', () => {- mockFlag(true)- mockRecipeNormalizeMessages.mockReturnValue([{ role: 'user', content: 'legacy' }])- normalizeMessages({ role: 'user' }, 'user')- expect(capture).toHaveBeenCalledWith(- 'llma normalization timed',- expect.objectContaining({ outputs_match: true })- )- })-- it('returns the flag-selected recipe result while still timing legacy', () => {- mockFlag(true)- expect(normalizeMessages({ role: 'user' }, 'user')).toBe(RECIPE)- })-- it('records recipe_errored and returns legacy when the recipe throws', () => {- mockFlag(true)- mockRecipeNormalizeMessages.mockImplementation(() => {- throw new Error('boom')+ 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(normalizeMessages({ role: 'user' }, 'user')).toBe(LEGACY)- expect(capture).toHaveBeenCalledWith(- 'llma normalization timed',- expect.objectContaining({ recipe_errored: true, recipe_duration_ms: null, outputs_match: null })- )- })-- it('tags the singular normalizeMessage path with its op', () => {- mockFlag(false)- normalizeMessage({ role: 'user' }, 'user')- expect(capture).toHaveBeenCalledWith(- 'llma normalization timed',- expect.objectContaining({ op: 'normalizeMessage' })- )- })- it('honors a lower sample_rate from the flag payload to suppress timing', () => {- mockFlag(true, { sample_rate: 0 })- normalizeMessages({ role: 'user' }, 'user')- expect(capture).not.toHaveBeenCalledWith('llma normalization timed', expect.anything())+ it('normalizeMessages carries no message for nullish/scalar input', () => {+ expect(normalizeMessages(null, 'user')).toEqual([])+ expect(normalizeMessages(42, 'user')).toEqual([])+ })})})diff --git a/products/ai_observability/frontend/messageNormalization.ts b/products/ai_observability/frontend/messageNormalization.tsindex 7c4ad5d3a727..267089bfaa3a 100644--- a/products/ai_observability/frontend/messageNormalization.ts+++ b/products/ai_observability/frontend/messageNormalization.ts@@ -1,14 +1,8 @@-import posthog, { JsonType } from 'posthog-js'--import { FEATURE_FLAGS } from 'lib/constants'-import { objectsEqual, removeUndefinedAndNull } from 'lib/utils'-import { mergeRecipes, RecipeNormalizer, StoredRecipe } from './normalizer'import { CompatMessage } from './types'-import { normalizeMessage as legacyNormalizeMessage, normalizeMessages as legacyNormalizeMessages } from './utils'// Constructed once: the constructor compiles and sorts every recipe, so per-call-// construction would dwarf the work we're measuring.+// construction would be wasteful.const recipeNormalizer = new RecipeNormalizer()// Swap the live normalizer over to a team's custom recipe set. Called wherever traces@@ -22,113 +16,10 @@ export function applyTeamParserRecipes(stored: StoredRecipe[]): void {}}-// Normalization runs once per rendered message; sample so timing doesn't flood ingestion.-const DEFAULT_TIMING_SAMPLE_RATE = 0.01--function timingSampleRate(payload: JsonType | undefined): number {- if (payload && typeof payload === 'object' && 'sample_rate' in payload) {- const rate = Number(payload.sample_rate)- if (Number.isFinite(rate) && rate >= 0 && rate <= 1) {- return rate- }- }- return DEFAULT_TIMING_SAMPLE_RATE-}-export function normalizeMessage(input: unknown, defaultRole: string): CompatMessage[] {- return dispatch(- () => legacyNormalizeMessage(input, defaultRole),- () => recipeNormalizer.normalizeMessage(input, defaultRole),- { op: 'normalizeMessage', default_role: defaultRole }- )+ return recipeNormalizer.normalizeMessage(input, defaultRole)}export function normalizeMessages(input: unknown, defaultRole: string, tools?: unknown): CompatMessage[] {- return dispatch(- () => legacyNormalizeMessages(input, defaultRole, tools),- () => recipeNormalizer.normalizeMessages(input, defaultRole, tools),- { op: 'normalizeMessages', default_role: defaultRole, has_tools: tools != null }- )-}--function dispatch(- legacy: () => CompatMessage[],- recipe: () => CompatMessage[],- context: Record<string, unknown>-): CompatMessage[] {- const flag = posthog.getFeatureFlagResult(FEATURE_FLAGS.LLM_ANALYTICS_RECIPE_NORMALIZER)- const useRecipe = !!flag?.enabled-- if (Math.random() >= timingSampleRate(flag?.payload)) {- return useRecipe ? runRecipe(recipe, legacy) : legacy()- }- return shadow(legacy, recipe, useRecipe, context)-}--// The recipe normalizer throws on a coverage gap; fall back so a normalizer bug-// can never break trace rendering.-function runRecipe(recipe: () => CompatMessage[], legacy: () => CompatMessage[]): CompatMessage[] {- try {- return recipe()- } catch (error) {- posthog.capture('llma recipe normalization fell back', {- error: error instanceof Error ? error.message : String(error),- })- return legacy()- }-}--function shadow(- legacy: () => CompatMessage[],- recipe: () => CompatMessage[],- useRecipe: boolean,- context: Record<string, unknown>-): CompatMessage[] {- const legacyRun = time(legacy)- const recipeRun = timeSafe(recipe)- // Strip nullish-valued keys before comparing, so an explicit `undefined`- // field (e.g. legacy's `tool_call_id: undefined`) counts as equal to an- // absent one — smooths over quirks in the legacy implementation- const outputsMatch = recipeRun.ok- ? objectsEqual(removeUndefinedAndNull(legacyRun.result), removeUndefinedAndNull(recipeRun.result))- : null-- posthog.capture('llma normalization timed', {- ...context,- active_implementation: useRecipe ? 'recipe' : 'legacy',- legacy_duration_ms: legacyRun.durationMs,- recipe_duration_ms: recipeRun.ok ? recipeRun.durationMs : null,- recipe_errored: !recipeRun.ok,- outputs_match: outputsMatch,- message_count: legacyRun.result.length,- })-- return useRecipe && recipeRun.ok ? recipeRun.result : legacyRun.result-}--interface TimedRun {- result: CompatMessage[]- durationMs: number-}--type SafeRun = (TimedRun & { ok: true }) | { ok: false }--function time(fn: () => CompatMessage[]): TimedRun {- const start = performance.now()- const result = fn()- return { result, durationMs: roundMs(performance.now() - start) }-}--function timeSafe(fn: () => CompatMessage[]): SafeRun {- const start = performance.now()- try {- const result = fn()- return { ok: true, result, durationMs: roundMs(performance.now() - start) }- } catch {- return { ok: false }- }-}--function roundMs(ms: number): number {- return Math.round(ms * 1000) / 1000+ return recipeNormalizer.normalizeMessages(input, defaultRole, tools)}diff --git a/products/ai_observability/frontend/normalizer/coverageHarness.test.ts b/products/ai_observability/frontend/normalizer/coverageHarness.test.tsdeleted file mode 100644index 35c0c07664d7..000000000000--- a/products/ai_observability/frontend/normalizer/coverageHarness.test.ts+++ /dev/null@@ -1,194 +0,0 @@-// Empirical coverage harness: runs the legacy normalizer and the recipe-based-// `RecipeNormalizer` over a sample of REAL production payloads and reports where-// they diverge. This is how the known divergences in `../utils.test.ts` were-// found, and how to re-validate after changing a recipe.-//-// It is gated on the sample files existing, so it SKIPS in CI and in a normal-// `jest` run — it only does work when you've pulled a fresh sample locally.-//-// ── Reproducing ────────────────────────────────────────────────────────────-// 1. Authenticate (opens SSO in your browser, once per region):-// hogli metabase:login --region us-// hogli metabase:login --region eu-// 2. Find the ClickHouse data-tier DB id for each region:-// hogli metabase:databases --region us # e.g. "PostHog ClickHouse PROD US ONLINE"-// hogli metabase:databases --region eu # e.g. "PostHog ClickHouse PROD EU Data Tier"-// 3. Sample uniformly by team (so high-volume teams don't dominate) into the-// directory this harness reads (default /tmp/parser-coverage):-// hogli metabase:query --region us --database-id <ID> --save /tmp/parser-coverage/sample-us.tsv <<'SQL'-// SELECT team_id, toString(uuid) AS event_uuid, provider, model, input, output_choices-// FROM ai_events-// WHERE event = '$ai_generation'-// AND timestamp > now() - INTERVAL 6 HOUR-// AND cityHash64(toString(uuid)) % 500 = 0 -- ~0.2% prefilter, keeps the sort in memory-// AND (input != '' OR output_choices != '')-// LIMIT 3 BY team_id -- uniform: at most 3 events per team-// LIMIT 20000-// SETTINGS max_execution_time = 120-// SQL-// (repeat with --region eu and --save .../sample-eu.tsv)-// 4. Run this harness:-// RECIPE_COVERAGE_DIR=/tmp/parser-coverage pnpm --filter @posthog/frontend jest --testPathPattern=coverageHarness-// It writes <dir>/report.md (bucketed divergences) and logs a one-line summary.-//-// NEVER commit the sample TSVs or the report — they contain raw customer payloads.--import { existsSync, readFileSync, writeFileSync } from 'node:fs'-import { join } from 'node:path'--import type { CompatMessage } from '../types'-import * as legacy from '../utils'-import { RecipeNormalizer } from './index'--const DIR = process.env.RECIPE_COVERAGE_DIR ?? '/tmp/parser-coverage'-const REGIONS = ['us', 'eu'] as const-const samplePath = (region: string): string => join(DIR, `sample-${region}.tsv`)-const haveSamples = REGIONS.some((r) => existsSync(samplePath(r)))--interface Sample {- region: string- teamId: number- eventUuid: string- provider: string- column: 'input' | 'output_choices'- raw: string-}--function loadSamples(region: string): Sample[] {- if (!existsSync(samplePath(region))) {- return []- }- const lines = readFileSync(samplePath(region), 'utf8').split('\n').filter(Boolean)- const header = lines[0].split('\t')- const at = (cells: string[], name: string): string => cells[header.indexOf(name)]- const out: Sample[] = []- for (const line of lines.slice(1)) {- const cells = line.split('\t')- for (const column of ['input', 'output_choices'] as const) {- const raw = at(cells, column)- if (raw && raw !== '' && raw !== '\\N') {- out.push({- region,- teamId: Number(at(cells, 'team_id')),- eventUuid: at(cells, 'event_uuid'),- provider: at(cells, 'provider'),- column,- raw,- })- }- }- }- return out-}--// Order-insensitive deep equality, matching Jest's `toEqual`: object key order-// is not a behavioral difference, but array (message) order is. Treats a missing-// key and an explicit `undefined` as equal.-function deepEqual(a: unknown, b: unknown): boolean {- if (a === b) {- return true- }- if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') {- return false- }- if (Array.isArray(a) || Array.isArray(b)) {- return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => deepEqual(x, b[i]))- }- const ao = a as Record<string, unknown>- const bo = b as Record<string, unknown>- const keys = (o: Record<string, unknown>): string[] => Object.keys(o).filter((k) => o[k] !== undefined)- const ak = keys(ao)- return ak.length === keys(bo).length && ak.every((k) => k in bo && deepEqual(ao[k], bo[k]))-}--// A coarse structural fingerprint so divergences with the same shape group together.-function signature(value: unknown, depth = 0): string {- if (depth > 3) {- return '…'- }- if (value === null) {- return 'null'- }- if (Array.isArray(value)) {- const uniq = [...new Set(value.slice(0, 5).map((v) => signature(v, depth + 1)))]- return uniq.length === 1 ? `[${uniq[0]}*${value.length}]` : `[${uniq.join('|')}]`- }- if (typeof value === 'object') {- const obj = value as Record<string, unknown>- const tags = ['type', 'role']- .filter((k) => k in obj)- .map((k) => `${k}=${JSON.stringify(obj[k])}`)- .join(',')- const keys = Object.keys(obj).sort().join(',')- return tags ? `{${keys}|${tags}}` : `{${keys}}`- }- return typeof value-}--const describeOrSkip = haveSamples ? describe : describe.skip--describeOrSkip('recipe coverage vs legacy (empirical)', () => {- it('reports divergences over sampled production payloads', () => {- const recipe = new RecipeNormalizer()- const samples = REGIONS.flatMap(loadSamples)-- let match = 0- const buckets = new Map<string, { count: number; example: Sample; legacy: string; recipe: string }>()-- for (const s of samples) {- let parsed: unknown- try {- parsed = JSON.parse(s.raw)- } catch {- continue- }- const role = s.column === 'input' ? 'user' : 'assistant'- const run = (fn: () => CompatMessage[]): CompatMessage[] | { error: string } => {- try {- return fn()- } catch (err) {- return { error: err instanceof Error ? err.message : String(err) }- }- }- const a = run(() => legacy.normalizeMessages(parsed, role))- const b = run(() => recipe.normalizeMessages(parsed, role))- if (deepEqual(a, b)) {- match++- continue- }- const sig = signature(parsed)- const existing = buckets.get(sig)- if (existing) {- existing.count++- } else {- buckets.set(sig, { count: 1, example: s, legacy: JSON.stringify(a), recipe: JSON.stringify(b) })- }- }-- const diverge = samples.length - match- const lines = [- `# Recipe coverage vs legacy`,- '',- `- samples: ${samples.length} across ${new Set(samples.map((s) => s.teamId)).size} teams`,- `- match: ${match} (${((match / samples.length) * 100).toFixed(1)}%)`,- `- diverge: ${diverge} (${((diverge / samples.length) * 100).toFixed(1)}%)`,- '',- '## Divergences by shape',- '',- ]- for (const [sig, info] of [...buckets].sort((x, y) => y[1].count - x[1].count)) {- lines.push(`### ${info.count}× \`${sig}\``)- lines.push(- `- example: team ${info.example.teamId} (${info.example.region}), \`${info.example.provider}\`, ${info.example.column}, uuid \`${info.example.eventUuid}\``- )- lines.push(`- legacy: \`${info.legacy.slice(0, 300).replace(/`/g, "'")}\``)- lines.push(`- recipe: \`${info.recipe.slice(0, 300).replace(/`/g, "'")}\``)- lines.push('')- }- writeFileSync(join(DIR, 'report.md'), lines.join('\n'))- // eslint-disable-next-line no-console- console.warn(- `[coverage] ${samples.length} samples · ${match} match · ${diverge} diverge · report → ${join(DIR, 'report.md')}`- )- }, 120000)-})diff --git a/products/ai_observability/frontend/searchUtils.test.ts b/products/ai_observability/frontend/searchUtils.test.tsindex 09499b648da2..ce09f3a168e2 100644--- a/products/ai_observability/frontend/searchUtils.test.ts+++ b/products/ai_observability/frontend/searchUtils.test.ts@@ -1,6 +1,7 @@import { LLMTraceEvent } from '~/queries/schema/schema-general'import { findEventWithParents } from './aiObservabilityTraceDataLogic'+import { normalizeMessages } from './messageNormalization'import type { SearchMatch } from './searchUtils'import {containsSearchQuery,@@ -12,7 +13,6 @@ import {findSidebarOccurrences,findTraceOccurrences,} from './searchUtils'-import { normalizeMessages } from './utils'describe('searchUtils', () => {describe('findSearchMatches', () => {diff --git a/products/ai_observability/frontend/settings/parserRecipesLogic.test.ts b/products/ai_observability/frontend/settings/parserRecipesLogic.test.tsindex b37b4700d3c1..f0bbecd4230c 100644--- a/products/ai_observability/frontend/settings/parserRecipesLogic.test.ts+++ b/products/ai_observability/frontend/settings/parserRecipesLogic.test.ts@@ -23,7 +23,7 @@ const mockList = llmAnalyticsParserRecipesList as jest.MockedFunction<typeof llmconst mockCreate = llmAnalyticsParserRecipesCreate as jest.MockedFunction<typeof llmAnalyticsParserRecipesCreate>const mockDestroy = llmAnalyticsParserRecipesDestroy as jest.MockedFunction<typeof llmAnalyticsParserRecipesDestroy>-const FLAG = FEATURE_FLAGS.LLM_ANALYTICS_RECIPE_NORMALIZER+const FLAG = FEATURE_FLAGS.LLM_ANALYTICS_CUSTOM_PARSERSdescribe('parserRecipesLogic', () => {let logic: ReturnType<typeof parserRecipesLogic.build>diff --git a/products/ai_observability/frontend/settings/parserRecipesLogic.ts b/products/ai_observability/frontend/settings/parserRecipesLogic.tsindex 49253f00a99d..7a9c34342863 100644--- a/products/ai_observability/frontend/settings/parserRecipesLogic.ts+++ b/products/ai_observability/frontend/settings/parserRecipesLogic.ts@@ -66,7 +66,7 @@ export const parserRecipesLogic = kea<parserRecipesLogicType>([[] as ParserRecipeApi[],{loadRecipes: async () => {- if (!values.featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_RECIPE_NORMALIZER]) {+ if (!values.featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_CUSTOM_PARSERS]) {return []}return (await llmAnalyticsParserRecipesList(String(values.currentTeamId), { limit: 1000 })).results@@ -113,7 +113,7 @@ export const parserRecipesLogic = kea<parserRecipesLogicType>([loadKey: [(s) => [s.currentTeamId, s.featureFlags],(currentTeamId, featureFlags): number | null =>- featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_RECIPE_NORMALIZER] ? currentTeamId : null,+ featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_CUSTOM_PARSERS] ? currentTeamId : null,],}),subscriptions(({ actions }) => ({diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.tsindex dc89a9910d52..b5fa32d47b36 100644--- a/products/ai_observability/frontend/utils.test.ts+++ b/products/ai_observability/frontend/utils.test.ts@@ -11,32 +11,23 @@ import {getInternalTagName,getSessionID,getSessionStartTimestamp,- getToolNamesCalled,hasCostBreakdown,hasStringContentField,isEmptyJSONStructure,isInternalToolResultUserMessage,- isLangChainMessage,isInternalTagMessage,isTextContentItem,isToolResult,isToolStepItem,looksLikeXml,- parseOpenAIToolCalls,parsePartialJSON,parseToolArgumentsForDisplay,sanitizeTraceUrlSearchParams,} from './utils'-import * as legacy from './utils'-// Parameterized suite: the canonical `normalizeMessage`/`normalizeMessages`-// in `./utils` stays untouched and is the production code path; the-// recipe-based wrapper in `./normalizer` exposes the same shape and we run-// the entire suite against it too. Any divergence shows up as a failure on-// only one column.+// The recipe-based `RecipeNormalizer` in `./normalizer` is the production code path.const recipe = new RecipeNormalizer()const IMPLS = [- { name: 'legacy', normalizeMessage: legacy.normalizeMessage, normalizeMessages: legacy.normalizeMessages },{name: 'recipe',normalizeMessage: (r: unknown, d: string) => recipe.normalizeMessage(r, d),@@ -44,7 +35,7 @@ const IMPLS = [},] as const-describe.each(IMPLS)('AI observability utils [$name]', ({ name, normalizeMessage, normalizeMessages }) => {+describe.each(IMPLS)('AI observability utils [$name]', ({ normalizeMessage, normalizeMessages }) => {beforeEach(() => {console.warn = jest.fn()})@@ -1765,17 +1756,6 @@ describe.each(IMPLS)('AI observability utils [$name]', ({ name, normalizeMessage})describe('LangChain/LangGraph format', () => {- it.each([- ['human type', { type: 'human', content: 'Hello' }, true],- ['ai type', { type: 'ai', content: 'Hi there', tool_calls: [] }, true],- ['tool type', { type: 'tool', content: 'result', tool_call_id: 'toolu_123' }, true],- ['context type', { type: 'context', content: '<system_reminder>...' }, true],- ['rejects messages with role field', { role: 'user', type: 'human', content: 'Hello' }, false],- ['rejects unknown types', { type: 'text', content: 'Hello' }, false],- ])('isLangChainMessage: %s', (_, input, expected) => {- expect(isLangChainMessage(input)).toBe(expected)- })-it('normalizeMessage maps human type to user role', () => {const message = { type: 'human', content: 'Hello', id: 'msg-1' }const result = normalizeMessage(message, 'assistant')@@ -1826,103 +1806,6 @@ describe.each(IMPLS)('AI observability utils [$name]', ({ name, normalizeMessage})})- describe('parseOpenAIToolCalls', () => {- it('should parse valid JSON arguments in tool calls', () => {- const toolCalls = [- {- type: 'function' as const,- id: 'call-123',- function: {- name: 'test_function',- arguments: '{"key": "value", "number": 42}',- },- },- ]-- const result = parseOpenAIToolCalls(toolCalls)-- expect(result).toEqual([- {- type: 'function',- id: 'call-123',- function: {- name: 'test_function',- arguments: { key: 'value', number: 42 },- },- },- ])- })-- it('should handle malformed JSON arguments gracefully', () => {- const toolCalls = [- {- type: 'function' as const,- id: 'call-456',- function: {- name: 'test_function',- arguments: 'invalid json {not valid}',- },- },- ]-- const result = parseOpenAIToolCalls(toolCalls)-- // Should keep the original string if parsing fails- expect(result).toEqual([- {- type: 'function',- id: 'call-456',- function: {- name: 'test_function',- arguments: 'invalid json {not valid}',- },- },- ])- })-- it('should handle mixed valid and invalid JSON in multiple tool calls', () => {- const toolCalls = [- {- type: 'function' as const,- id: 'call-1',- function: {- name: 'func1',- arguments: '{"valid": "json"}',- },- },- {- type: 'function' as const,- id: 'call-2',- function: {- name: 'func2',- arguments: 'not valid json',- },- },- ]-- const result = parseOpenAIToolCalls(toolCalls)-- expect(result).toEqual([- {- type: 'function',- id: 'call-1',- function: {- name: 'func1',- arguments: { valid: 'json' },- },- },- {- type: 'function',- id: 'call-2',- function: {- name: 'func2',- arguments: 'not valid json',- },- },- ])- })- })-describe('OTel parts format', () => {it('normalizes a single text part into a string content', () => {const message = {@@ -2560,194 +2443,8 @@ describe.each(IMPLS)('AI observability utils [$name]', ({ name, normalizeMessage})})- describe('getToolNamesCalled', () => {- const span = (id: string, createdAt: string, spanName?: string): LLMTraceEvent => ({- id,- event: '$ai_span',- createdAt,- properties: spanName ? { $ai_span_name: spanName } : {},- })- const generation = (id: string, createdAt: string, outputChoices: unknown): LLMTraceEvent => ({- id,- event: '$ai_generation',- createdAt,- properties: { $ai_output_choices: outputChoices },- })-- it('returns [] for an empty event list', () => {- expect(getToolNamesCalled([])).toEqual([])- })-- it('returns `$ai_span_name` from instrumented span events', () => {- const events = [span('s1', '2026-05-11T00:00:00.000Z', 'fetch_user')]- expect(getToolNamesCalled(events)).toEqual(['fetch_user'])- })-- it('skips span events without a `$ai_span_name`', () => {- const events = [span('s1', '2026-05-11T00:00:00.000Z')]- expect(getToolNamesCalled(events)).toEqual([])- })-- it('skips event types other than `$ai_span` and `$ai_generation`', () => {- const events: LLMTraceEvent[] = [- {- id: 'trace',- event: '$ai_trace',- createdAt: '2026-05-11T00:00:00.000Z',- properties: { $ai_span_name: 'irrelevant' },- },- ]- expect(getToolNamesCalled(events)).toEqual([])- })-- // Covers every output shape `normalizeMessages` understands — adding a new- // SDK shape there should bring it under this case table without further- // changes here.- it.each<[name: string, outputChoices: unknown, expected: string[]]>([- [- 'OpenAI Chat Completions `tool_calls`',- [- {- role: 'assistant',- content: '',- tool_calls: [- { id: 'a', type: 'function', function: { name: 'get_weather', arguments: '{}' } },- { id: 'b', type: 'function', function: { name: 'search_docs', arguments: '{}' } },- ],- },- ],- ['get_weather', 'search_docs'],- ],- [- 'Anthropic `tool_use` typed parts',- [- {- role: 'assistant',- content: [- { type: 'text', text: 'Looking it up.' },- { type: 'tool_use', id: 'toolu_1', name: 'get_weather', input: { city: 'Berlin' } },- { type: 'tool_use', id: 'toolu_2', name: 'search_docs', input: {} },- ],- },- ],- ['get_weather', 'search_docs'],- ],- [- 'OpenAI Responses `function_call` items',- [- { type: 'function_call', call_id: 'c1', name: 'get_weather', arguments: '{}' },- { type: 'function_call', call_id: 'c2', name: 'search_docs', arguments: '{}' },- ],- ['get_weather', 'search_docs'],- ],- [- 'Vercel SDK `tool-call` items',- [- { type: 'tool-call', toolCallId: 'a', toolName: 'get_weather', input: { city: 'Berlin' } },- { type: 'tool-call', toolCallId: 'b', toolName: 'search_docs', input: {} },- ],- ['get_weather', 'search_docs'],- ],- [- 'OpenAI Responses built-in tool calls',- [- { id: 'ws1', type: 'web_search_call', status: 'completed' },- { id: 'mcp1', type: 'mcp_call', name: 'list_dashboards', status: 'completed' },- ],- ['web_search_call', 'list_dashboards'],- ],- [- 'LiteLLM-style {choices:[{message:{tool_calls}}]} wrapper',- {- choices: [- {- finish_reason: 'tool_calls',- index: 0,- message: {- role: 'assistant',- content: null,- tool_calls: [- {- id: 'a',- type: 'function',- function: { name: 'get_weather', arguments: '{"city":"Berlin"}' },- },- {- id: 'b',- type: 'function',- function: { name: 'search_docs', arguments: '{}' },- },- ],- },- },- ],- },- ['get_weather', 'search_docs'],- ],- ])('returns tool names from %s in $ai_generation outputs', (_, outputChoices, expected) => {- const events = [generation('g1', '2026-05-11T00:00:00.000Z', outputChoices)]- expect(getToolNamesCalled(events)).toEqual(expected)- })-- it('preserves duplicates in the raw call sequence — caller decides whether to dedupe', () => {- // Three identical tool calls across span + generation events should all appear.- // Dedup is a session-page concern, not part of "what tools were called".- const events = [- span('s1', '2026-05-11T00:00:00.000Z', 'fetch_user'),- generation('g1', '2026-05-11T00:00:01.000Z', [- {- role: 'assistant',- content: '',- tool_calls: [{ id: 'a', type: 'function', function: { name: 'fetch_user', arguments: '{}' } }],- },- ]),- span('s2', '2026-05-11T00:00:02.000Z', 'fetch_user'),- ]- expect(getToolNamesCalled(events)).toEqual(['fetch_user', 'fetch_user', 'fetch_user'])- })-- it('orders names chronologically regardless of input order', () => {- // Events come back from ClickHouse in whatever order the query produced.- const events = [- span('s3', '2026-05-11T00:00:02.000Z', 'send_email'),- span('s1', '2026-05-11T00:00:00.000Z', 'fetch_user'),- span('s2', '2026-05-11T00:00:01.000Z', 'subscription_lookup'),- ]- expect(getToolNamesCalled(events)).toEqual(['fetch_user', 'subscription_lookup', 'send_email'])- })-- it('skips tool calls with missing or empty names', () => {- const events = [- generation('g1', '2026-05-11T00:00:00.000Z', [- {- role: 'assistant',- content: '',- tool_calls: [- { id: 'a', type: 'function', function: { name: '', arguments: '{}' } },- { id: 'b', type: 'function', function: { name: 'real_tool', arguments: '{}' } },- ],- },- ]),- ]- expect(getToolNamesCalled(events)).toEqual(['real_tool'])- })-- it('returns [] when a generation has no $ai_output_choices', () => {- const events: LLMTraceEvent[] = [- {- id: 'g1',- event: '$ai_generation',- createdAt: '2026-05-11T00:00:00.000Z',- properties: {},- },- ]- expect(getToolNamesCalled(events)).toEqual([])- })- })-- // Regressions found by sampling real production payloads across teams (see- // normalizer/coverageHarness.test.ts). These shapes were mishandled by the- // recipe pipeline; both implementations must agree on them.+ // Regressions found by sampling real production payloads across teams. These+ // shapes were mishandled at some point by the recipe pipeline.describe('production payload regressions', () => {it('null input carries no message', () => {// Recipe used to salvage `null` into a spurious empty user message.@@ -2790,39 +2487,24 @@ describe.each(IMPLS)('AI observability utils [$name]', ({ name, normalizeMessage})})- // Cases where the recipe pipeline deliberately IMPROVES on legacy. The legacy- // path retires once the recipe pipeline is the default, at which point these- // collapse to a single assertion. Until then each documents both behaviors.- describe('accepted divergences (recipe improvements)', () => {- const expectByImpl = (input: unknown, role: string, legacyOut: unknown, recipeOut: unknown): void => {- expect(normalizeMessages(input, role)).toEqual(name === 'recipe' ? recipeOut : legacyOut)+ // Structured content the recipe pipeline surfaces as canonical messages.+ describe('recipe normalization improvements', () => {+ const expectRecipe = (input: unknown, role: string, expected: unknown): void => {+ expect(normalizeMessages(input, role)).toEqual(expected)}it('extracts single-field {text}/{message} wrappers instead of stringifying them', () => {- // legacy stringifies the whole object; recipe surfaces the inner text.- expectByImpl(- { text: 'hello' },- 'assistant',- [{ role: 'assistant', content: '{"text":"hello"}' }],- [{ role: 'assistant', content: 'hello' }]- )- })-- it('empties null content instead of preserving it', () => {- // legacy keeps content:null (and the empty tool_calls); recipe- // normalizes content to '' (renderers expect a string) and drops the- // empty tool_calls.- expectByImpl(- { role: 'assistant', content: null, tool_calls: [] },- 'assistant',- [{ role: 'assistant', content: null, tool_calls: [] }],- [{ role: 'assistant', content: '' }]- )- })-- it('preserves and canonicalizes a tool_call that legacy drops', () => {- // The tool_call lacks the `type: "function"` marker, so legacy's- // strict guard rejects the whole array and loses the call. Recipe+ expectRecipe({ text: 'hello' }, 'assistant', [{ role: 'assistant', content: 'hello' }])+ })++ it('empties null content and drops an empty tool_calls array', () => {+ // content is normalized to '' (renderers expect a string).+ expectRecipe({ role: 'assistant', content: null, tool_calls: [] }, 'assistant', [+ { role: 'assistant', content: '' },+ ])+ })++ it('preserves and canonicalizes a tool_call lacking the type marker', () => {// canonicalizes it to {type, id, function:{name, parsed args}}.const input = {role: 'assistant',@@ -2836,78 +2518,54 @@ describe.each(IMPLS)('AI observability utils [$name]', ({ name, normalizeMessage},],}- expectByImpl(- input,- 'assistant',- [{ role: 'assistant', content: null }],- [- {- role: 'assistant',- content: '',- tool_calls: [- {- type: 'function',- id: 'call_1',- function: { name: 'send_email', arguments: { to: '[email protected]' } },- },- ],- },- ]- )+ expectRecipe(input, 'assistant', [+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ type: 'function',+ id: 'call_1',+ function: { name: 'send_email', arguments: { to: '[email protected]' } },+ },+ ],+ },+ ])})it('flattens a doubly-nested message array instead of stringifying it', () => {- // legacy stringifies the inner array as one user message; recipe flattens.const input = [[{ role: 'system', content: 'a' },{ role: 'user', content: 'b' },],]- expectByImpl(- input,- 'user',- [{ role: 'user', content: '[{"role":"system","content":"a"},{"role":"user","content":"b"}]' }],- [- { role: 'system', content: 'a' },- { role: 'user', content: 'b' },- ]- )+ expectRecipe(input, 'user', [+ { role: 'system', content: 'a' },+ { role: 'user', content: 'b' },+ ])})- it('parses typed agent items (tool_call/tool_result) legacy stringifies or drops', () => {+ it('parses typed agent items (tool_call/tool_result) into real tool messages', () => {// Flat type-discriminated agent stream (OpenAI Agents SDK and similar).- // legacy stringifies the tool_call and drops the tool_result's output;- // recipe produces a real tool call and tool message.const input = [{ type: 'tool_call', callId: 'c1', name: 'getWeather', arguments: { city: 'NYC' } },{ type: 'tool_result', callId: 'c1', name: 'getWeather', output: { tempF: 71 } },]- expectByImpl(- input,- 'user',- [- {- role: 'user',- content: '{"type":"tool_call","callId":"c1","name":"getWeather","arguments":{"city":"NYC"}}',- },- { role: 'assistant (tool result)' },- ],- [- {- role: 'assistant',- content: '',- tool_calls: [- {- type: 'function',- id: 'c1',- function: { name: 'getWeather', arguments: { city: 'NYC' } },- },- ],- },- { role: 'tool', content: '{"tempF":71}', tool_call_id: 'c1' },- ]- )+ expectRecipe(input, 'user', [+ {+ role: 'assistant',+ content: '',+ tool_calls: [+ {+ type: 'function',+ id: 'c1',+ function: { name: 'getWeather', arguments: { city: 'NYC' } },+ },+ ],+ },+ { role: 'tool', content: '{"tempF":71}', tool_call_id: 'c1' },+ ])})})})diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.tsindex 0cdc46522f16..9e835ca70d65 100644--- a/products/ai_observability/frontend/utils.ts+++ b/products/ai_observability/frontend/utils.ts@@ -1,5 +1,4 @@import * as PartialJSON from 'partial-json'-import posthog from 'posthog-js'import api from 'lib/api'import { dayjs } from 'lib/dayjs'@@ -14,38 +13,26 @@ import type { EvaluationRun } from './evaluations/types'import {AnthropicDocumentMessage,AnthropicImageMessage,- AnthropicInputMessage,- AnthropicTextMessage,- AnthropicThinkingMessage,AnthropicToolCallMessage,AnthropicToolResultMessage,CompatMessage,- CompatToolCall,GeminiAudioMessage,GeminiDocumentMessage,GeminiImageMessage,- LiteLLMChoice,- LiteLLMResponse,OpenAIAudioMessage,- OpenAICompletionMessage,OpenAIFileMessage,OpenAIImageURLMessage,OpenAIResponsesBuiltinToolCall,OpenAIResponsesFunctionCall,OpenAIResponsesFunctionCallOutput,- OpenAIResponsesReasoning,- OpenAIToolCall,StringContentObject,TextContentItem,- VercelSDKImageMessage,- VercelSDKInputImageMessage,VercelSDKInputTextMessage,VercelSDKTextMessage,VercelSDKToolCallFunctionMessage,VercelSDKToolCallMessage,VercelSDKToolCallToolNameMessage,VercelSDKToolResultMessage,- MultiModalContentItem,} from './types'export interface PagedSearchOrderFilters {@@ -363,77 +350,10 @@ export function getRecordingStatus(event: LLMTrace | LLMTraceEvent): string | nureturn event.events.find((e) => e.properties.$recording_status !== null)?.properties.$recording_status || null}-export function isOpenAICompatToolCall(input: unknown): input is OpenAIToolCall {- return (- input !== null &&- typeof input === 'object' &&- 'type' in input &&- 'function' in input &&- input.type === 'function' &&- typeof input.function === 'object' &&- input.function !== null- )-}--export function isOpenAICompatToolCallsArray(input: any): input is OpenAIToolCall[] {- return Array.isArray(input) && input.every(isOpenAICompatToolCall)-}--export function isOpenAICompatMessage(output: unknown): output is OpenAICompletionMessage {- return (- !!output &&- typeof output === 'object' &&- 'role' in output &&- 'content' in output &&- (typeof output.content === 'string' || output.content === null)- )-}--function parseToolArguments(args: string | Record<string, unknown>): Record<string, unknown> | string {- if (typeof args === 'string') {- try {- return JSON.parse(args)- } catch {- return args- }- }- return args-}--export function parseOpenAIToolCalls(toolCalls: OpenAIToolCall[]): CompatToolCall[] {- const toolsWithParsedArguments = toolCalls.map((toolCall) => {- let parsedArguments = toolCall.function.arguments-- if (typeof toolCall.function.arguments === 'string') {- try {- parsedArguments = JSON.parse(toolCall.function.arguments)- } catch (e) {- console.warn('Failed to parse tool call arguments as JSON:', toolCall.function.arguments, e)- // Keep the original string if parsing fails- parsedArguments = toolCall.function.arguments- }- }-- return {- ...toolCall,- function: {- ...toolCall.function,- arguments: parsedArguments,- },- }- })-- return toolsWithParsedArguments-}-export function isTextContentItem(item: unknown): item is TextContentItem {return !!item && typeof item === 'object' && 'type' in item && item.type === 'text' && 'text' in item}-export function isAnthropicTextMessage(output: unknown): output is AnthropicTextMessage {- return isTextContentItem(output)-}-export function hasStringContentField(value: unknown): value is StringContentObject {return typeof value === 'object' && value !== null && 'content' in value && isString(value.content)}@@ -605,48 +525,10 @@ export function isToolStepItem(item: unknown): boolean {)}-export function isAnthropicThinkingMessage(output: unknown): output is AnthropicThinkingMessage {- return !!output && typeof output === 'object' && 'type' in output && output.type === 'thinking'-}-export function isAnthropicToolResultMessage(output: unknown): output is AnthropicToolResultMessage {return !!output && typeof output === 'object' && 'type' in output && output.type === 'tool_result'}-export function isAnthropicRoleBasedMessage(input: unknown): input is AnthropicInputMessage {- return (- !!input &&- typeof input === 'object' &&- 'role' in input &&- 'content' in input &&- (typeof input.content === 'string' || Array.isArray(input.content))- )-}--// LangChain/LangGraph type guard-// LangChain messages use `type` (human, ai, tool, system, context) instead of `role`-const LANGCHAIN_MESSAGE_TYPES = new Set(['human', 'ai', 'tool', 'system', 'context'])--interface LangChainMessage {- type: string- content: unknown- tool_calls?: unknown- tool_call_id?: string- [key: string]: unknown-}--export function isLangChainMessage(input: unknown): input is LangChainMessage {- return (- !!input &&- typeof input === 'object' &&- !('role' in input) &&- 'type' in input &&- typeof input.type === 'string' &&- LANGCHAIN_MESSAGE_TYPES.has(input.type) &&- 'content' in input- )-}-// OpenAI Responses API type guardsconst OPENAI_RESPONSES_BUILTIN_TOOL_TYPES = new Set(['web_search_call',@@ -689,10 +571,6 @@ export function isOpenAIResponsesBuiltinToolCall(input: unknown): input is OpenA)}-export function isOpenAIResponsesReasoning(input: unknown): input is OpenAIResponsesReasoning {- return !!input && typeof input === 'object' && 'type' in input && input.type === 'reasoning'-}-export function isVercelSDKTextMessage(input: unknown): input is VercelSDKTextMessage {return (!!input &&@@ -704,31 +582,6 @@ export function isVercelSDKTextMessage(input: unknown): input is VercelSDKTextMe)}-export function isVercelSDKImageMessage(input: unknown): input is VercelSDKImageMessage {- return (- !!input &&- typeof input === 'object' &&- 'type' in input &&- input.type === 'image' &&- 'content' in input &&- typeof input.content === 'object' &&- input.content !== null &&- 'image' in input.content &&- typeof input.content.image === 'string'- )-}--export function isVercelSDKInputImageMessage(input: unknown): input is VercelSDKInputImageMessage {- return (- !!input &&- typeof input === 'object' &&- 'type' in input &&- input.type === 'input_image' &&- 'image_url' in input &&- typeof input.image_url === 'string'- )-}-export function isVercelSDKInputTextMessage(input: unknown): input is VercelSDKInputTextMessage {return (!!input &&@@ -950,99 +803,6 @@ export function isOTelPartsMessage(input: unknown): input is OTelPartsMessage {)}-function parseOTelToolCallArguments(args: unknown): Record<string, unknown> | string {- if (typeof args === 'string') {- try {- return JSON.parse(args)- } catch {- return args- }- }- return (args ?? {}) as Record<string, unknown>-}--function normalizeOTelPartsMessage(message: OTelPartsMessage, role: string): CompatMessage[] {- const { role: _role, parts, ...rest } = message-- const textParts: string[] = []- const toolCalls: CompatToolCall[] = []- const toolResponses: CompatMessage[] = []-- for (const part of parts) {- if (part.type === 'text' && typeof part.content === 'string') {- textParts.push(part.content)- } else if (part.type === 'tool_call' && typeof part.name === 'string') {- toolCalls.push({- type: 'function',- id: typeof part.id === 'string' ? part.id : undefined,- function: {- name: part.name,- arguments: parseOTelToolCallArguments(part.arguments),- },- })- } else if (part.type === 'tool_call_response') {- let resultContent: string- if (typeof part.result === 'string') {- resultContent = part.result- } else {- try {- resultContent = JSON.stringify(part.result)- } catch {- resultContent = String(part.result)- }- }- toolResponses.push({- role: 'tool',- content: resultContent,- tool_call_id: typeof part.id === 'string' ? part.id : undefined,- })- }- }-- if (textParts.length === 0 && toolCalls.length === 0 && toolResponses.length > 0) {- return toolResponses- }-- const content: CompatMessage['content'] =- textParts.length === 1- ? textParts[0]- : textParts.length > 1- ? textParts.map((text) => ({ type: 'text' as const, text }))- : ''-- return [- {- ...rest,- role,- content,- ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),- },- ...toolResponses,- ]-}--export function isLiteLLMChoice(input: unknown): input is LiteLLMChoice {- return (- !!input &&- typeof input === 'object' &&- 'finish_reason' in input &&- 'index' in input &&- 'message' in input &&- typeof input.message === 'object' &&- input.message !== null- )-}--export function isLiteLLMResponse(input: unknown): input is LiteLLMResponse {- return (- !!input &&- typeof input === 'object' &&- 'choices' in input &&- Array.isArray(input.choices) &&- input.choices.every(isLiteLLMChoice)- )-}-export const roleMap: Record<string, string> = {user: 'user',human: 'user',@@ -1065,541 +825,12 @@ export function normalizeRole(rawRole: unknown, fallback: string): string {return roleMap[lowercased] || lowercased}-const STRUCTURED_CONTENT_TYPES = new Set([- 'text',- 'output_text',- 'input_text',- 'function',- 'image',- 'input_image',- 'image_url',- 'file',- 'audio',- 'document',-])--function parseStringifiedStructuredContent(content: string): string | MultiModalContentItem[] {- const trimmed = content.trim()- if (!trimmed.startsWith('[')) {- return content- }-- try {- const parsed = JSON.parse(trimmed)- if (- Array.isArray(parsed) &&- (parsed.length === 0 ||- parsed.every(- (item) =>- item &&- typeof item === 'object' &&- 'type' in item &&- typeof item.type === 'string' &&- STRUCTURED_CONTENT_TYPES.has(item.type)- ))- ) {- return parsed as MultiModalContentItem[]- }- } catch {- // Keep the original text when it's not valid JSON.- }-- return content-}--/**- * Normalizes a message from an LLM provider into a format that is compatible with the PostHog AI observability schema.- *- * @param rawMessage - Original message from an LLM provider.- * @param defaultRole - The default role to use if the message doesn't have one.- * @returns The normalized message.- */-export function normalizeMessage(rawMessage: unknown, defaultRole: string): CompatMessage[] {- // Extract the role from the message if it exists, otherwise use defaultRole- // This ensures we preserve roles when recursing into nested content- const roleToUse =- rawMessage && typeof rawMessage === 'object' && 'role' in rawMessage && typeof rawMessage.role === 'string'- ? normalizeRole(rawMessage.role, defaultRole)- : rawMessage &&- typeof rawMessage === 'object' &&- 'type' in rawMessage &&- typeof rawMessage.type === 'string' &&- Object.hasOwn(roleMap, rawMessage.type)- ? normalizeRole(rawMessage.type, defaultRole)- : defaultRole-- // Handle new array-based content format (unified format with structured objects)- // Only apply this if the array contains objects with 'type' field (not Anthropic-specific formats)- // Supported types include: text, output_text, input_text, function, image, input_image, document- if (- rawMessage &&- typeof rawMessage === 'object' &&- 'role' in rawMessage &&- 'content' in rawMessage &&- typeof rawMessage.role === 'string' &&- Array.isArray(rawMessage.content) &&- rawMessage.content.length > 0 &&- rawMessage.content.every(- (item) =>- item &&- typeof item === 'object' &&- 'type' in item &&- (item.type === 'text' ||- item.type === 'output_text' ||- item.type === 'input_text' ||- item.type === 'function' ||- item.type === 'image' ||- item.type === 'input_image' ||- item.type === 'image_url' ||- item.type === 'file' ||- item.type === 'audio' ||- item.type === 'document')- )- ) {- const toolCalls: CompatToolCall[] = []- const remainingContent: MultiModalContentItem[] = []- for (const item of rawMessage.content) {- if (- item &&- typeof item === 'object' &&- 'type' in item &&- item.type === 'function' &&- 'function' in item &&- item.function &&- typeof item.function === 'object' &&- 'name' in item.function &&- typeof item.function.name === 'string'- ) {- const fn = item.function as { name: string; arguments?: string | Record<string, unknown> }- toolCalls.push({- type: 'function',- id: 'id' in item && typeof item.id === 'string' ? item.id : undefined,- function: {- name: fn.name,- arguments: parseToolArguments(fn.arguments ?? {}),- },- })- } else {- remainingContent.push(item as MultiModalContentItem)- }- }-- if (toolCalls.length > 0) {- return [- {- role: roleToUse,- content: remainingContent.length > 0 ? remainingContent : '',- tool_calls: toolCalls,- },- ]- }-- return [- {- role: roleToUse,- content: rawMessage.content,- },- ]- }-- if (isLiteLLMChoice(rawMessage)) {- return normalizeMessage(rawMessage.message, roleToUse)- }-- // Vercel SDK- if (isVercelSDKTextMessage(rawMessage)) {- return [- {- role: roleToUse,- content: rawMessage.content,- },- ]- }-- // Vercel SDK Input Image- if (isVercelSDKInputImageMessage(rawMessage)) {- return [- {- role: roleToUse,- content: [- {- type: 'image',- image: rawMessage.image_url,- },- ],- },- ]- }-- // Vercel SDK Input Text- if (isVercelSDKInputTextMessage(rawMessage)) {- return [- {- role: roleToUse,- content: rawMessage.text,- },- ]- }-- // OpenAI- if (isOpenAICompatMessage(rawMessage)) {- return [- {- ...rawMessage,- role: roleToUse,- content:- typeof rawMessage.content === 'string'- ? parseStringifiedStructuredContent(rawMessage.content)- : rawMessage.content,- tool_calls: isOpenAICompatToolCallsArray(rawMessage.tool_calls)- ? parseOpenAIToolCalls(rawMessage.tool_calls)- : undefined,- tool_call_id: rawMessage.tool_call_id,- },- ]- }-- // Anthropic- // Text object- if (isAnthropicTextMessage(rawMessage)) {- return [- {- role: roleToUse,- content: rawMessage.text,- },- ]- }- // Tool call completion- if (isAnthropicToolCallMessage(rawMessage)) {- return [- {- role: roleToUse,- content: '',- tool_calls: [- {- type: 'function',- id: rawMessage.id,- function: {- name: rawMessage.name,- arguments: rawMessage.input,- },- },- ],- },- ]- }- // Thinking- if (isAnthropicThinkingMessage(rawMessage)) {- return [- {- role: normalizeRole(INTERNAL_THINKING_ROLE, roleToUse),- content: rawMessage.thinking,- },- ]- }- // Tool result completion- if (isAnthropicToolResultMessage(rawMessage)) {- const toolResultRole = normalizeRole(INTERNAL_TOOL_RESULT_ROLE, roleToUse)- if (Array.isArray(rawMessage.content)) {- return rawMessage.content- .map((content) => normalizeMessage(content, toolResultRole))- .flat()- .map((msg) => ({- ...msg,- tool_call_id: rawMessage.tool_use_id,- }))- }- return [- {- role: toolResultRole,- content: rawMessage.content,- tool_call_id: rawMessage.tool_use_id,- },- ]- }-- // OpenAI Responses API- // Function call (role-less, uses `type` instead)- if (isOpenAIResponsesFunctionCall(rawMessage)) {- return [- {- role: 'assistant',- content: '',- tool_calls: [- {- type: 'function',- id: rawMessage.call_id,- function: {- name: rawMessage.name,- arguments: parseToolArguments(rawMessage.arguments),- },- },- ],- },- ]- }- // Function call output- if (isOpenAIResponsesFunctionCallOutput(rawMessage)) {- return [- {- role: normalizeRole(INTERNAL_TOOL_RESULT_ROLE, roleToUse),- content: rawMessage.output,- tool_call_id: rawMessage.call_id,- },- ]- }- // Reasoning- if (isOpenAIResponsesReasoning(rawMessage)) {- let summaryText = ''- if (Array.isArray(rawMessage.summary)) {- summaryText = rawMessage.summary.map((s) => s.text).join('\n')- } else if (typeof rawMessage.text === 'string') {- summaryText = rawMessage.text- }- return [- {- role: normalizeRole(INTERNAL_THINKING_ROLE, roleToUse),- content: summaryText,- },- ]- }- // Vercel AI SDK tool call (function variant)- if (isVercelSDKToolCallFunctionMessage(rawMessage)) {- return [- {- role: roleToUse,- content: '',- tool_calls: [- {- type: 'function',- id: rawMessage.id,- function: {- name: rawMessage.function.name,- arguments: parseToolArguments(rawMessage.function.arguments),- },- },- ],- },- ]- }- // Vercel AI SDK tool call (toolName variant)- if (isVercelSDKToolCallToolNameMessage(rawMessage)) {- return [- {- role: roleToUse,- content: '',- tool_calls: [- {- type: 'function',- id: rawMessage.toolCallId,- function: {- name: rawMessage.toolName,- arguments: parseToolArguments(rawMessage.input ?? {}),- },- },- ],- },- ]- }- // Vercel AI SDK tool result- if (isVercelSDKToolResultMessage(rawMessage)) {- let content = ''- if (typeof rawMessage.output === 'string') {- content = rawMessage.output- } else if (rawMessage.output !== undefined) {- try {- content = JSON.stringify(rawMessage.output)- } catch {- content = String(rawMessage.output)- }- }- return [- {- role: normalizeRole(INTERNAL_TOOL_RESULT_ROLE, roleToUse),- content,- tool_call_id: rawMessage.toolCallId,- },- ]- }- // Built-in tool calls (web_search_call, code_interpreter_call, etc.)- if (isOpenAIResponsesBuiltinToolCall(rawMessage)) {- // Prefer an explicit name (e.g. mcp_call.name), fall back to the item type.- const name =- 'name' in rawMessage && typeof rawMessage.name === 'string' && rawMessage.name- ? rawMessage.name- : rawMessage.type-- let functionArguments: Record<string, unknown> | string- if ('arguments' in rawMessage && rawMessage.arguments !== undefined && rawMessage.arguments !== null) {- const rawArgs = rawMessage.arguments- if (typeof rawArgs === 'string' || (typeof rawArgs === 'object' && !Array.isArray(rawArgs))) {- functionArguments = parseToolArguments(rawArgs as string | Record<string, unknown>)- } else {- functionArguments = { arguments: rawArgs }- }- } else {- // Strip `arguments` too in case it's explicitly null — it would otherwise leak into rest.- const { id: _id, type: _type, status: _status, name: _name, arguments: _args, ...rest } = rawMessage- functionArguments = rest- }-- return [- {- role: 'assistant',- content: '',- tool_calls: [- {- type: 'function',- id: rawMessage.id,- function: {- name,- arguments: functionArguments,- },- },- ],- },- ]- }-- // Input message- if (isAnthropicRoleBasedMessage(rawMessage)) {- // Check for top-level tool_calls (already normalized by SDK)- const topLevelToolCalls =- 'tool_calls' in rawMessage && isOpenAICompatToolCallsArray(rawMessage.tool_calls)- ? parseOpenAIToolCalls(rawMessage.tool_calls)- : undefined-- if (Array.isArray(rawMessage.content)) {- // If we have top-level tool_calls, skip tool_use blocks in content (they're duplicates with incomplete data)- const contentToProcess = topLevelToolCalls- ? rawMessage.content.filter((item) => !isAnthropicToolCallMessage(item))- : rawMessage.content-- const contentMessages = contentToProcess.map((content) => normalizeMessage(content, roleToUse)).flat()-- if (topLevelToolCalls && topLevelToolCalls.length > 0) {- contentMessages.push({- role: roleToUse,- content: '',- tool_calls: topLevelToolCalls,- })- }-- return contentMessages- }-- return [- {- role: roleToUse,- content: rawMessage.content,- },- ]- }- // OTel parts format (from OpenTelemetry AI semantic conventions)- if (isOTelPartsMessage(rawMessage)) {- return normalizeOTelPartsMessage(rawMessage, roleToUse)- }-- // LangChain/LangGraph format: uses `type` (human, ai, tool, system, context) instead of `role`- if (isLangChainMessage(rawMessage)) {- return [- {- role: roleToUse,- content:- typeof rawMessage.content === 'string' ? rawMessage.content : JSON.stringify(rawMessage.content),- tool_calls:- 'tool_calls' in rawMessage && isOpenAICompatToolCallsArray(rawMessage.tool_calls)- ? parseOpenAIToolCalls(rawMessage.tool_calls)- : undefined,- tool_call_id:- 'tool_call_id' in rawMessage && typeof rawMessage.tool_call_id === 'string'- ? rawMessage.tool_call_id- : undefined,- },- ]- }-- // Unsupported message — log at debug level to avoid flooding the console-- posthog.capture('llma message normalization failed', {- message_keys: typeof rawMessage === 'object' && rawMessage !== null ? Object.keys(rawMessage) : [],- message_type: typeof rawMessage,- })- let cajoledContent: string // Let's do what we can- if (typeof rawMessage === 'string') {- cajoledContent = rawMessage- } else if (hasStringContentField(rawMessage)) {- cajoledContent = rawMessage.content- } else {- cajoledContent = JSON.stringify(rawMessage)- }- return [{ role: roleToUse, content: cajoledContent }]-}--// Synthetic role used by `normalizeMessages` to surface the `$ai_tools` payload-// as a pseudo-message+// Synthetic role used to surface the `$ai_tools` payload as a pseudo-messageexport const AVAILABLE_TOOLS_ROLE = 'available tools'export const INTERNAL_THINKING_ROLE = 'assistant (thinking)'export const INTERNAL_TOOL_RESULT_ROLE = 'assistant (tool result)'-// Returns the tool names invoked across events in chronological order (duplicates preserved)-export function getToolNamesCalled(events: LLMTraceEvent[]): string[] {- const sorted = [...events].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())- const names: string[] = []- // Pulls from `$ai_span_name` on instrumented `$ai_span` events- // and from `tool_calls[].function.name` on normalized `$ai_generation` outputs- for (const event of sorted) {- if (event.event === '$ai_span') {- const spanName = event.properties.$ai_span_name- if (typeof spanName === 'string' && spanName) {- names.push(spanName)- }- } else if (event.event === '$ai_generation') {- for (const msg of normalizeMessages(event.properties.$ai_output_choices, 'assistant')) {- for (const tc of msg.tool_calls ?? []) {- const name = tc.function?.name- if (typeof name === 'string' && name) {- names.push(name)- }- }- }- }- }- return names-}--export function normalizeMessages(messages: unknown, defaultRole: string, tools?: unknown): CompatMessage[] {- const normalizedMessages: CompatMessage[] = []-- if (tools) {- normalizedMessages.push({- role: AVAILABLE_TOOLS_ROLE,- content: '',- tools,- })- }-- if (Array.isArray(messages)) {- normalizedMessages.push(...messages.map((message) => normalizeMessage(message, defaultRole)).flat())- } else if (isLiteLLMResponse(messages)) {- normalizedMessages.push(- ...(messages.choices || []).map((choice) => normalizeMessage(choice, defaultRole)).flat()- )- } else if (typeof messages === 'object' && messages && 'choices' in messages && Array.isArray(messages.choices)) {- normalizedMessages.push(...messages.choices.map((message) => normalizeMessage(message, defaultRole)).flat())- } else if (typeof messages === 'string') {- normalizedMessages.push({- role: defaultRole,- content: messages,- })- } else if (typeof messages === 'object' && messages !== null) {- normalizedMessages.push(...normalizeMessage(messages, defaultRole))- }-- return normalizedMessages-}-const JSON_PREVIEW_LENGTH = 300// We are deliberately cutting off the JSON instead of the parsed final content