:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(aio): explain empty generation output when tokens were billed (#90159)
Bernat Torres06f5b4daaeda
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 0c4ee5aa1905..3261e87ba912 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5708,6 +5708,22 @@ snapshots:hash: v1.k794b7964.9ea11684de93cf0bf2fabc01d05a7b4fed8d0e540084b01ec27ab8a29d0f3823.vJCRxMCRSHVE9xVry1hOYTeYimJdH1PyeD0guOSQu4kscenes-app-ai-observability-conversation-display--basic--light:hash: v1.k794b7964.3cb142d720e0576d3b92310d75f791cf42452f5f32d38674f79d434790589239.7q-Lw22M7R633hrsN-ZnuIgkAWP9l4i9iRbu5jpnOG8+ scenes-app-ai-observability-conversation-display--empty-output-blocked-by-provider--dark:+ hash: v1.k794b7964.05125a80c55c9ad20c8edcc84bf05e1f58ff673ca1a2abbef34ced9ec3552b9d.mah6RylH_kokmN1fnEjxZQD4Ps3QUaffSekfCz5N6i4+ scenes-app-ai-observability-conversation-display--empty-output-blocked-by-provider--light:+ hash: v1.k794b7964.1f86f5ba9536b50c817ca0a3c0d55548c14b8f4a8ff13b504c3f7b150e012ada.4ZWD_3VA2AijSiEbq-_jE96K3tcgkw3HHuu_Ux3IFfQ+ scenes-app-ai-observability-conversation-display--empty-output-hit-token-limit--dark:+ hash: v1.k794b7964.b2548b108edc6f8c958940e1fc0209b999b98438e0a6b6c095f3ac42a4cdd9f1.-411C02o_BaVwQeYWxv1oPT5d_J-6pawteYt4V80BAA+ scenes-app-ai-observability-conversation-display--empty-output-hit-token-limit--light:+ hash: v1.k794b7964.f8d093d6d02c6f147e06a6fbff6cbac04aa9cc29e7b1780a67c59b26681869c8.j7EwfprpifYVQrbjfTqvFjMSCeqtwfxhgfeLQQ_2lFk+ scenes-app-ai-observability-conversation-display--empty-output-with-billed-tokens--dark:+ hash: v1.k794b7964.42eeaa8552683109e50304840c0fe8907c4c0825b622ecd1d9745bc4f895d955.HGZ_kprIGe14sglkYwj1wNpS3hLSkGbZKw3tuUJTz5s+ scenes-app-ai-observability-conversation-display--empty-output-with-billed-tokens--light:+ hash: v1.k794b7964.b9e3adecf8f05139d76126faf07998b0a915fec481915e6a8bad3a97992dae68.4UFV8PthL3Y5pbeU3axDaPZIep6ixfatWlrzqW4JKm0+ scenes-app-ai-observability-conversation-display--empty-output-with-reasoning-tokens--dark:+ hash: v1.k794b7964.9f1da3403eb752b5499e096ed36633d7c8fff2e69b7ba3696354e664bde897ff.N7wmsys9CZDuETYl1x-hqLouyIimaxUWLRWc9DZYgjY+ scenes-app-ai-observability-conversation-display--empty-output-with-reasoning-tokens--light:+ hash: v1.k794b7964.34eabfa265ecc45640d754647a5ad836ef95a3d32c1885391c94af7865d2fe18.N2i_3GzO4MpTXxY30ebKa5IiVNEIBVSbDgGepsfm4RIscenes-app-ai-observability-conversation-display--error--dark:hash: v1.k794b7964.477b40a99b407806f5a85839a94004a899be31370ea6861518dd11cf5c883c45.EQEZzP2enfzFprXAhyqSbD8Um6pvTD1cGa3yq6qn4VUscenes-app-ai-observability-conversation-display--error--light:diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/AIEventItems.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/AIEventItems.tsxindex e68761744962..94427a411b9b 100644--- a/frontend/src/scenes/session-recordings/player/inspector/components/AIEventItems.tsx+++ b/frontend/src/scenes/session-recordings/player/inspector/components/AIEventItems.tsx@@ -8,12 +8,13 @@ import { ConversationMessagesDisplay } from 'products/ai_observability/frontend/import { useAIData } from 'products/ai_observability/frontend/hooks/useAIData'import { LLMInputOutput } from 'products/ai_observability/frontend/LLMInputOutput'import { normalizeMessages } from 'products/ai_observability/frontend/messageNormalization'+import { selectAiValue } from 'products/ai_observability/frontend/utils'export function AIEventExpanded({ event }: { event: Record<string, any> }): JSX.Element {const { input, output, tools, isLoading } = useAIData({uuid: event.uuid,input: event.properties?.$ai_input,- output: event.properties?.$ai_output_choices,+ output: selectAiValue(event.properties?.$ai_output_choices, event.properties?.$ai_output),tools: event.properties?.$ai_tools,traceId: event.properties?.$ai_trace_id,timestamp: event.timestamp,@@ -35,6 +36,10 @@ export function AIEventExpanded({ event }: { event: Record<string, any> }): JSX.errorData={event.properties.$ai_error}httpStatus={event.properties.$ai_http_status}raisedError={raisedError}+ outputTokens={event.properties.$ai_output_tokens}+ reasoningTokens={event.properties.$ai_reasoning_tokens}+ textOutputTokens={event.properties.$ai_text_output_tokens}+ stopReason={event.properties.$ai_stop_reason}traceId={event.properties.$ai_trace_id}/>) : (diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsxindex b0904aa25e6b..8ef6a7a1756a 100644--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx@@ -123,6 +123,7 @@ import {isLLMEvent,removeMilliseconds,sanitizeTraceUrlSearchParams,+ selectAiValue,} from './utils'interface TraceQueueContext {@@ -1777,14 +1778,20 @@ const EventContent = React.memo(traceId={trace.id}timestamp={event.createdAt}rawInput={event.properties.$ai_input}- rawOutput={- event.properties.$ai_output_choices ??+ rawOutput={selectAiValue(+ event.properties.$ai_output_choices,event.properties.$ai_output- }+ )}tools={event.properties.$ai_tools}errorData={event.properties.$ai_error}httpStatus={event.properties.$ai_http_status}raisedError={event.properties.$ai_is_error}+ outputTokens={event.properties.$ai_output_tokens}+ reasoningTokens={event.properties.$ai_reasoning_tokens}+ textOutputTokens={+ event.properties.$ai_text_output_tokens+ }+ stopReason={event.properties.$ai_stop_reason}searchQuery={searchQuery}displayOption={displayOption}highlightMessageIndex={highlightMessageIndex}diff --git a/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.stories.tsx b/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.stories.tsxindex f551de26a848..e9122ec562b3 100644--- a/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.stories.tsx+++ b/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.stories.tsx@@ -170,6 +170,75 @@ export const Error: Story = {},}+export const EmptyOutputWithBilledTokens: Story = {+ args: {+ eventProperties: {+ $ai_input: [+ { role: 'system', content: 'You are a good bot.' },+ { role: 'user', content: 'Write me a long essay about bots.' },+ ],+ $ai_output_choices: [],+ $ai_input_tokens: 120,+ $ai_output_tokens: 512,+ $ai_latency: 8.4,+ $ai_model: 'gpt-9',+ $ai_http_status: 200,+ },+ },+}++export const EmptyOutputWithReasoningTokens: Story = {+ args: {+ eventProperties: {+ $ai_input: [+ { role: 'system', content: 'You are a good bot.' },+ { role: 'user', content: 'Write me a long essay about bots.' },+ ],+ $ai_output_choices: [],+ $ai_input_tokens: 120,+ $ai_reasoning_tokens: 442,+ $ai_latency: 8.4,+ $ai_model: 'gpt-9',+ $ai_http_status: 200,+ },+ },+}++export const EmptyOutputHitTokenLimit: Story = {+ args: {+ eventProperties: {+ $ai_input: [+ { role: 'system', content: 'You are a good bot.' },+ { role: 'user', content: 'Write me a long essay about bots.' },+ ],+ $ai_output_choices: [],+ $ai_input_tokens: 120,+ $ai_output_tokens: 2048,+ $ai_stop_reason: 'MAX_TOKENS',+ $ai_latency: 8.4,+ $ai_model: 'gpt-9',+ $ai_http_status: 200,+ },+ },+}++export const EmptyOutputBlockedByProvider: Story = {+ args: {+ eventProperties: {+ $ai_input: [+ { role: 'system', content: 'You are a good bot.' },+ { role: 'user', content: 'Write me a long essay about bots.' },+ ],+ $ai_output_choices: [],+ $ai_input_tokens: 120,+ $ai_stop_reason: 'PROHIBITED_CONTENT',+ $ai_latency: 0.4,+ $ai_model: 'gpt-9',+ $ai_http_status: 200,+ },+ },+}+export const Anthropic: Story = {args: {eventProperties: {diff --git a/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.test.tsx b/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.test.tsxindex 08506d133f3a..8ea491ab0de2 100644--- a/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.test.tsx+++ b/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.test.tsx@@ -68,6 +68,37 @@ describe('ConversationDisplay', () => {output: 'plain output',},],+ [+ '$ai_generation whose $ai_output_choices is an empty container',+ '$ai_generation',+ {+ $ai_input: [{ role: 'user', content: 'generation input' }],+ $ai_output_choices: [],+ $ai_output: [{ role: 'assistant', content: 'real output' }],+ $ai_tools: [{ function: { name: 'search' } }],+ $ai_trace_id: 'trace-1',+ },+ {+ input: [{ role: 'user', content: 'generation input' }],+ output: [{ role: 'assistant', content: 'real output' }],+ },+ ],+ [+ '$ai_generation whose output is genuinely empty',+ '$ai_generation',+ {+ $ai_input: [{ role: 'user', content: 'generation input' }],+ $ai_output_choices: [],+ $ai_tools: [{ function: { name: 'search' } }],+ $ai_trace_id: 'trace-1',+ },+ {+ input: [{ role: 'user', content: 'generation input' }],+ // The empty container still counts as arrived. Passing undefined instead would make+ // useAIData run the heavy-prop lookup for a generation this PR's notice explains.+ output: [],+ },+ ],['$ai_embedding','$ai_embedding',diff --git a/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.tsxindex 96f97955d7d0..abe886db111a 100644--- a/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.tsx+++ b/products/ai_observability/frontend/ConversationDisplay/ConversationDisplay.tsx@@ -10,7 +10,7 @@ import { buildInputSourceIndices } from '../extractSessionTurns'import { useAIData } from '../hooks/useAIData'import { normalizeMessages } from '../messageNormalization'import { openInPlayground } from '../playground/llmPlaygroundPromptsLogic'-import { costContextFromProperties } from '../utils'+import { costContextFromProperties, selectAiValue } from '../utils'import { ConversationMessagesDisplay } from './ConversationMessagesDisplay'import { MetadataHeader } from './MetadataHeader'@@ -34,7 +34,7 @@ export function ConversationDisplay({: eventProperties.$ai_input_stateconst rawOutput =eventName === '$ai_generation'- ? (eventProperties.$ai_output_choices ?? eventProperties.$ai_output)+ ? selectAiValue(eventProperties.$ai_output_choices, eventProperties.$ai_output): eventName === '$ai_embedding'? 'Embedding vector generated': eventProperties.$ai_output_state@@ -100,6 +100,10 @@ export function ConversationDisplay({errorData={eventProperties.$ai_error}httpStatus={eventProperties.$ai_http_status}raisedError={eventProperties.$ai_is_error}+ outputTokens={eventProperties.$ai_output_tokens}+ reasoningTokens={eventProperties.$ai_reasoning_tokens}+ textOutputTokens={eventProperties.$ai_text_output_tokens}+ stopReason={eventProperties.$ai_stop_reason}borderedtraceId={eventProperties.$ai_trace_id}generationEventId={eventId}diff --git a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.test.tsx b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.test.tsxindex 95be1cfce4e3..8877ff12deac 100644--- a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.test.tsx+++ b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.test.tsx@@ -470,6 +470,154 @@ describe('ConversationMessagesDisplay', () => {expect(screen.queryByText(text)).not.toBeInTheDocument()}})++ it.each<[string, unknown, unknown, unknown, unknown, string | null]>([+ [+ 'only output tokens were billed',+ 2048,+ undefined,+ undefined,+ undefined,+ 'The provider reported 2,048 output tokens but no content was captured. The response may have been cut short, or the SDK may not have captured it.',+ ],+ [+ 'only reasoning tokens were billed',+ undefined,+ 442,+ undefined,+ undefined,+ 'The provider reported 442 reasoning tokens but no content was captured. The model may have spent its budget on reasoning.',+ ],+ [+ 'reasoning matches the billed output exactly',+ 442,+ 442,+ undefined,+ undefined,+ 'The provider reported 442 output tokens but no content was captured. All of them may have been reasoning.',+ ],+ [+ 'reasoning exceeds the output count, so the output is missing content',+ 400,+ 500,+ undefined,+ undefined,+ 'The provider reported 400 output tokens and 500 reasoning tokens but no content was captured. The response may have been cut short, or the SDK may not have captured it.',+ ],+ [+ 'a provider reported the count as a string',+ '512',+ undefined,+ undefined,+ undefined,+ 'The provider reported 512 output tokens but no content was captured. The response may have been cut short, or the SDK may not have captured it.',+ ],+ [+ 'a provider spelled the token limit in upper case',+ 2048,+ undefined,+ undefined,+ 'MAX_TOKENS',+ 'The provider reported 2,048 output tokens but no content was captured. The response hit its token limit.',+ ],+ [+ 'the stop reason outranks the reasoning-token guess',+ undefined,+ 442,+ undefined,+ 'length',+ 'The provider reported 442 reasoning tokens but no content was captured. The response hit its token limit.',+ ],+ [+ 'the provider blocked the response without billing anything',+ 0,+ 0,+ undefined,+ 'PROHIBITED_CONTENT',+ 'The provider blocked the response.',+ ],+ [+ 'the stop reason describes a normal ending',+ 2048,+ undefined,+ undefined,+ 'end_turn',+ 'The provider reported 2,048 output tokens but no content was captured. The response may have been cut short, or the SDK may not have captured it.',+ ],+ [+ 'reasoning is only a fraction of the billed output',+ 2048,+ 12,+ undefined,+ undefined,+ 'The provider reported 2,048 output tokens and 12 reasoning tokens but no content was captured. The response may have been cut short, or the SDK may not have captured it.',+ ],+ [+ 'the text-token split says none of the output was text',+ 169,+ 56,+ 0,+ undefined,+ 'The provider reported 169 output tokens and 56 reasoning tokens but no content was captured. None of them were text.',+ ],+ [+ 'the text-token split says text was billed too',+ 442,+ 442,+ 113,+ undefined,+ 'The provider reported 442 output tokens and 442 reasoning tokens but no content was captured. The response may have been cut short, or the SDK may not have captured it.',+ ],+ [+ 'a provider hyphenated the stop reason',+ 2048,+ undefined,+ undefined,+ 'content-filter',+ 'The provider reported 2,048 output tokens but no content was captured. The provider blocked the response.',+ ],+ [+ 'an older SDK sent the count as an object',+ { total: 10585, noCache: 10585, cacheRead: 0 },+ undefined,+ undefined,+ undefined,+ 'The provider reported 10,585 output tokens but no content was captured. The response may have been cut short, or the SDK may not have captured it.',+ ],+ ['the provider billed nothing', 0, 0, undefined, undefined, null],+ ['no token counts arrived', undefined, undefined, undefined, undefined, null],+ ])(+ 'empty output explains the gap when %s',+ (_label, outputTokens, reasoningTokens, textOutputTokens, stopReason, expected) => {+ const { container } = render(+ <Provider>+ <ConversationMessagesDisplay+ inputNormalized={inputNormalized}+ outputNormalized={[]}+ errorData={null}+ raisedError={false}+ outputTokens={outputTokens}+ reasoningTokens={reasoningTokens}+ textOutputTokens={textOutputTokens}+ stopReason={stopReason}+ />+ </Provider>+ )++ expect(screen.getByText('No output')).toBeInTheDocument()+ const explanation = container.querySelector('[data-attr="ai-empty-output-explanation"]')+ if (expected !== null) {+ expect(explanation).toHaveTextContent(expected)+ // The notice names a cause and the link carries the fix. A typo'd anchor dead-ends there.+ expect(explanation!.querySelector('a')).toHaveAttribute(+ 'href',+ 'https://posthog.com/docs/ai-observability/troubleshooting#why-does-my-generation-show-no-output'+ )+ } else {+ expect(explanation).toBeNull()+ }+ }+ )})describe('ImageMessageDisplay', () => {diff --git a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsxindex 876422802f56..6c388a3a5cb5 100644--- a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx+++ b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx@@ -3,13 +3,14 @@ import { useValues } from 'kea'import React from 'react'import { IconCode, IconEye, IconMarkdown, IconMarkdownFilled, IconWrench } from '@posthog/icons'-import { LemonButton } from '@posthog/lemon-ui'+import { LemonButton, Link } from '@posthog/lemon-ui'import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'import { HighlightedJSONViewer } from 'lib/components/HighlightedJSONViewer'import { IconExclamation, IconEyeHidden } from 'lib/lemon-ui/icons'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { isObject } from 'lib/utils/guards'+import { humanFriendlyNumber } from 'lib/utils/numbers'import { teamLogic } from 'scenes/teamLogic'import { aiBlobRenderHandlers, resolveAiBlobUrl, resolveDataUri } from '../aiBlob'@@ -22,6 +23,8 @@ import { containsSearchQuery } from '../searchUtils'import type { GenerationSentiment } from '../sentimentResults'import { CompatMessage, MultiModalContentItem, VercelSDKImageMessage } from '../types'import {+ aiTokenCount,+ describeStopReason,getGeminiInlineData,hasStringContentField,isAnthropicDocumentMessage,@@ -71,6 +74,59 @@ function getInitialMessageShowStates(return { input: inputStates, output: outputStates }}+function billedTokenCount(value: unknown): number | null {+ const count = aiTokenCount(value)+ return count !== null && count > 0 ? count : null+}++// Explains a generation that rendered no content. `$ai_stop_reason` is the provider's own account of+// why it stopped, so it outranks anything inferred from token counts. Providers disagree on whether+// reasoning tokens sit inside the output count or beside it, so name each count that is present+// rather than deriving one from the other.+function describeEmptyOutput(+ outputTokens: unknown,+ reasoningTokens: unknown,+ textOutputTokens: unknown,+ stopReason: unknown+): string | null {+ const output = billedTokenCount(outputTokens)+ const reasoning = billedTokenCount(reasoningTokens)+ const namedCause = describeStopReason(stopReason)+ const textOutput = aiTokenCount(textOutputTokens)++ // Providers disagree on where reasoning tokens are counted. OpenAI-style providers count them+ // inside the output total, so reasoning can never exceed output there, and matching counts mean+ // the whole output was reasoning. Gemini-style providers count them separately, so a reasoning+ // count above a nonzero output count can only come from that style, which means the output+ // tokens are real content that went missing. `$ai_text_output_tokens` is the provider's own+ // split and needs no inference: zero means nothing textual was generated, under either style.+ const providerSaysNoText = textOutput === 0 && output !== null+ const reasoningMatchesOutput = textOutput === null && output !== null && reasoning !== null && reasoning === output++ const counts = [+ output !== null ? `${humanFriendlyNumber(output)} output tokens` : null,+ // When the counts match, listing both reads as two amounts. One number, one claim about it.+ reasoning !== null && !reasoningMatchesOutput ? `${humanFriendlyNumber(reasoning)} reasoning tokens` : null,+ ].filter(Boolean)++ // A provider can block a response before billing anything, so a known cause stands on its own.+ if (counts.length === 0) {+ return namedCause+ }++ const cause =+ namedCause ??+ (providerSaysNoText+ ? 'None of them were text.'+ : reasoningMatchesOutput+ ? 'All of them may have been reasoning.'+ : output === null && reasoning !== null+ ? 'The model may have spent its budget on reasoning.'+ : 'The response may have been cut short, or the SDK may not have captured it.')++ return `The provider reported ${counts.join(' and ')} but no content was captured. ${cause}`+}+export function ConversationMessagesDisplay({inputNormalized,outputNormalized,@@ -78,6 +134,10 @@ export function ConversationMessagesDisplay({errorData,httpStatus,raisedError,+ outputTokens,+ reasoningTokens,+ textOutputTokens,+ stopReason,bordered = false,searchQuery,displayOption,@@ -92,6 +152,14 @@ export function ConversationMessagesDisplay({errorData: anyhttpStatus?: numberraisedError?: boolean+ /** `$ai_output_tokens`, used to explain an output the provider billed for but never sent. */+ outputTokens?: unknown+ /** `$ai_reasoning_tokens`. Some providers bill only these, so they alone can explain an empty output. */+ reasoningTokens?: unknown+ /** `$ai_text_output_tokens`. An explicit zero says every billed output token was reasoning. */+ textOutputTokens?: unknown+ /** `$ai_stop_reason`. The provider's own account of why it stopped, so it outranks any inference. */+ stopReason?: unknownbordered?: booleansearchQuery?: stringdisplayOption?: ConversationDisplayOption@@ -282,6 +350,14 @@ export function ConversationMessagesDisplay({const showOutputSection = outputNormalized.length > 0 || !raisedError+ // Nothing to render means the provider either charged for work whose content never reached the+ // event, or told us why it stopped. Name that, so an empty box isn't mistaken for a provider+ // that said nothing.+ const emptyOutputExplanation =+ outputNormalized.length === 0+ ? describeEmptyOutput(outputTokens, reasoningTokens, textOutputTokens, stopReason)+ : null+return (<><LLMInputOutput@@ -305,8 +381,19 @@ export function ConversationMessagesDisplay({/>))) : (- <div className="rounded border text-default p-2 italic bg-[var(--bg-fill-error-tertiary)]">- No output+ <div className="rounded border text-default p-2 bg-[var(--bg-fill-error-tertiary)]">+ <div className="italic">No output</div>+ {emptyOutputExplanation && (+ <div className="mt-1 text-xs" data-attr="ai-empty-output-explanation">+ {emptyOutputExplanation}{' '}+ <Link+ to="https://posthog.com/docs/ai-observability/troubleshooting#why-does-my-generation-show-no-output"+ target="_blank"+ >+ Learn more+ </Link>+ </div>+ )}</div>)) : nulldiff --git a/products/ai_observability/frontend/ConversationDisplay/MetadataHeader.test.tsx b/products/ai_observability/frontend/ConversationDisplay/MetadataHeader.test.tsxindex be340e0d6f70..ad9af7243610 100644--- a/products/ai_observability/frontend/ConversationDisplay/MetadataHeader.test.tsx+++ b/products/ai_observability/frontend/ConversationDisplay/MetadataHeader.test.tsx@@ -26,6 +26,21 @@ describe('MetadataHeader', () => {expect(screen.getByText('GPT-4o')).toBeInTheDocument()})+ const lenientTokenCounts: [string, unknown, unknown][] = [+ ['string counts', '12', '512'],+ ['an object-shaped output count', 12, { total: 512, noCache: 512, cacheRead: 0 }],+ ]++ it.each(lenientTokenCounts)('renders token usage for %s', (_label, inputTokens, outputTokens) => {+ render(+ <Provider>+ <MetadataHeader inputTokens={inputTokens} outputTokens={outputTokens} />+ </Provider>+ )++ expect(screen.getByText('12 prompt tokens → 512 completion tokens (∑ 524)')).toBeInTheDocument()+ })+const nonStringModels: [string, unknown][] = [['number', 4],['boolean', true],diff --git a/products/ai_observability/frontend/ConversationDisplay/MetadataHeader.tsx b/products/ai_observability/frontend/ConversationDisplay/MetadataHeader.tsxindex aa19b338f72c..7d238fa04abd 100644--- a/products/ai_observability/frontend/ConversationDisplay/MetadataHeader.tsx+++ b/products/ai_observability/frontend/ConversationDisplay/MetadataHeader.tsx@@ -7,7 +7,7 @@ import { lowercaseFirstLetter } from 'lib/utils/strings'import { CostBreakdownTooltip } from '../components/CostBreakdownTooltip'import { MetadataTag } from '../components/MetadataTag'-import { CostContext, formatLLMCost, hasCostBreakdown } from '../utils'+import { CostContext, aiTokenCount, formatLLMCost, hasCostBreakdown } from '../utils'export function MetadataHeader({inputTokens,@@ -23,10 +23,11 @@ export function MetadataHeader({timeToFirstToken,isStreaming,}: {- inputTokens?: number- outputTokens?: number- cacheReadTokens?: number- cacheWriteTokens?: number+ /** Token props read leniently, so a string or `{ total, … }` count still renders its tag. */+ inputTokens?: unknown+ outputTokens?: unknown+ cacheReadTokens?: unknown+ cacheWriteTokens?: unknowncostContext?: CostContextmodel?: stringlatency?: number@@ -36,6 +37,11 @@ export function MetadataHeader({timeToFirstToken?: numberisStreaming?: boolean}): JSX.Element {+ const inputTokenCount = aiTokenCount(inputTokens)+ const outputTokenCount = aiTokenCount(outputTokens)+ const cacheReadTokenCount = aiTokenCount(cacheReadTokens)+ const cacheWriteTokenCount = aiTokenCount(cacheWriteTokens)+return (<div className={clsx('flex flex-wrap gap-2', className)}>{isError && <LemonTag type="danger">Error</LemonTag>}@@ -56,27 +62,27 @@ export function MetadataHeader({</MetadataTag>)}{timestamp && <MetadataTag label="Timestamp">{dayjs(timestamp).format('MMM D, YYYY h:mm A')}</MetadataTag>}- {typeof inputTokens === 'number' && typeof outputTokens === 'number' && (+ {inputTokenCount !== null && outputTokenCount !== null && (<MetadataTaglabel="Token usage"tooltipContent="Input and output tokens consumed by this generation call.">- {`${inputTokens} prompt tokens → ${outputTokens} completion tokens (∑ ${- inputTokens + outputTokens+ {`${inputTokenCount} prompt tokens → ${outputTokenCount} completion tokens (∑ ${+ inputTokenCount + outputTokenCount})`}</MetadataTag>)}- {typeof cacheReadTokens === 'number' && cacheReadTokens > 0 && (+ {cacheReadTokenCount !== null && cacheReadTokenCount > 0 && (<MetadataTaglabel="Cache read"tooltipContent="Prompt tokens served from the provider's cache (cheaper, faster)."- >{`${cacheReadTokens} cache read tokens`}</MetadataTag>+ >{`${cacheReadTokenCount} cache read tokens`}</MetadataTag>)}- {typeof cacheWriteTokens === 'number' && cacheWriteTokens > 0 && (+ {cacheWriteTokenCount !== null && cacheWriteTokenCount > 0 && (<MetadataTaglabel="Cache write"tooltipContent="Prompt tokens written to the provider's cache for reuse on subsequent calls."- >{`${cacheWriteTokens} cache write tokens`}</MetadataTag>+ >{`${cacheWriteTokenCount} cache write tokens`}</MetadataTag>)}{typeof model === 'string' && model && (<MetadataTag label="Model" textToCopy={lowercaseFirstLetter(model)}>diff --git a/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts b/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.tsindex 3cec97c4c5ec..4996e8ac2b0b 100644--- a/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts+++ b/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts@@ -132,6 +132,47 @@ describe('aiObservabilityAIDataLogic', () => {expect(mockApi.queryHogQL.mock.calls[1][0]).toContain('FROM events')})+ it('prefers populated input_state over an empty input array and keeps an empty output as arrived', async () => {+ jest.spyOn(mockApi, 'queryHogQL').mockResolvedValue({+ results: [+ [+ '[]',+ null,+ '[]',+ JSON.stringify({ messages: [{ type: 'human', content: 'state input' }] }),+ null,+ null,+ ],+ ],+ } as any)++ const logic = aiObservabilityAIDataLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.loadAIDataForEvent({+ eventId: 'event-1',+ input: undefined,+ output: undefined,+ tools: undefined,+ traceId: 'trace-1',+ timestamp: '2026-04-30T10:00:00Z',+ })+ })+ .toFinishAllListeners()+ .toMatchValues({+ aiDataCache: {+ 'event-1': {+ input: { messages: [{ type: 'human', content: 'state input' }] },+ output: [],+ tools: undefined,+ },+ },+ })++ expect(mockApi.queryHogQL).toHaveBeenCalledTimes(1)+ })+it('parses fetched heavy props in full instead of collapsing them into a truncated preview', async () => {const fullInput = [{ role: 'system', content: `You are a data extraction specialist. ${'detail '.repeat(60)}` },diff --git a/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts b/products/ai_observability/frontend/aiObservabilityAIDataLogic.tsindex 98032e280409..2c317c15bfd4 100644--- a/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts+++ b/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts@@ -7,7 +7,7 @@ import { dayjs } from 'lib/dayjs'import { ProductKey } from '~/queries/schema/schema-general'import { hogql } from '~/queries/utils'-import { parsePartialJSON } from './utils'+import { parsePartialJSON, selectAiValue } from './utils'const AI_DATA_QUERY_TAGS = {productKey: ProductKey.AI_OBSERVABILITY,@@ -88,21 +88,18 @@ function parseHeavyValue(value: unknown): unknown {}}-function firstUsableValue(...values: unknown[]): unknown {- for (const value of values) {- const parsed = parseHeavyValue(value)- if (isUsableValue(parsed)) {- return parsed- }- }- return undefined+// A column can hold an empty container while a sibling holds the response, so prefer content over+// mere presence — but keep a present-but-empty container, so the caller sees the value arrived and+// the loader does not fall through to the next, slower query for a row it already has.+function selectHeavyValue(...values: unknown[]): unknown {+ return selectAiValue(...values.map(parseHeavyValue))}function mapAIDataQueryRow(row: AIDataQueryRow): AIData {const [input, output, outputChoices, inputState, outputState, tools] = rowreturn {- input: firstUsableValue(input, inputState),- output: firstUsableValue(outputChoices, outputState, output),+ input: selectHeavyValue(input, inputState),+ output: selectHeavyValue(outputChoices, outputState, output),tools: parseHeavyValue(tools),}}diff --git a/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx b/products/ai_observability/frontend/components/EventContentWithAsyncData.tsxindex 6dd959cfb660..d52dfce0b9ac 100644--- a/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx+++ b/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx@@ -26,6 +26,10 @@ interface EventContentConversationProps {errorData?: unknownhttpStatus?: unknownraisedError?: boolean+ outputTokens?: unknown+ reasoningTokens?: unknown+ textOutputTokens?: unknown+ stopReason?: unknownsearchQuery?: stringdisplayOption?: ConversationDisplayOption/** Original $ai_input index to auto-expand (e.g. from sentiment tab deep link) */@@ -48,6 +52,10 @@ export function EventContentConversation({errorData,httpStatus,raisedError,+ outputTokens,+ reasoningTokens,+ textOutputTokens,+ stopReason,searchQuery,displayOption,highlightMessageIndex,@@ -139,6 +147,10 @@ export function EventContentConversation({errorData={errorData}httpStatus={typeof httpStatus === 'number' ? httpStatus : undefined}raisedError={raisedError}+ outputTokens={outputTokens}+ reasoningTokens={reasoningTokens}+ textOutputTokens={textOutputTokens}+ stopReason={stopReason}searchQuery={searchQuery}displayOption={displayOption}traceId={traceId}diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.tsindex c3f5c19b1551..459888554bfb 100644--- a/products/ai_observability/frontend/utils.ts+++ b/products/ai_observability/frontend/utils.ts@@ -107,6 +107,72 @@ function formatUsage(inputTokens: number, outputTokens?: number | null): stringreturn `${inputTokens} → ${outputTokens || 0} (∑ ${inputTokens + (outputTokens || 0)})`}+/** Whether an AI content property holds anything to render. An empty container holds nothing. */+export function hasAiContent(value: unknown): boolean {+ if (value === null || value === undefined || value === '') {+ return false+ }+ if (Array.isArray(value)) {+ return value.length > 0+ }+ if (typeof value === 'object') {+ return Object.keys(value).length > 0+ }+ return true+}++/**+ * Picks the AI value to render or pass on: the first that carries content, else the first that is+ * present at all. Content first, because a generation can send an empty `$ai_output_choices` while+ * `$ai_output` holds the response, and a nullish check would keep the empty container. Presence as+ * the fallback, because `useAIData` runs the heavy-property lookup when a side is nullish — a+ * generation whose output genuinely is empty must render its notice, not fire that query.+ */+export function selectAiValue(...values: unknown[]): unknown {+ return values.find(hasAiContent) ?? values.find((value) => value !== null && value !== undefined)+}++// Token counts arrive straight off untyped event properties, so a provider that reports one as a+// string still has to be readable. posthog-ai below 7.3.0 sent them as `{ total, noCache, cacheRead }`.+// Ingestion normalizes that now, but events captured before it still hold the object shape.+export function aiTokenCount(value: unknown): number | null {+ const unwrapped =+ value !== null && typeof value === 'object' && !Array.isArray(value) && 'total' in value+ ? (value as { total: unknown }).total+ : value+ const parsed = typeof unwrapped === 'string' ? Number(unwrapped) : unwrapped+ return typeof parsed === 'number' && Number.isFinite(parsed) ? parsed : null+}++// Stop reasons that explain an empty output. Each provider spells the same outcome its own way, and+// the OTel middlewares pass the value through verbatim. `max_tokens`, `MAX_TOKENS`, and `length` all+// mean the response ran out of room, so match a normalized set rather than one literal.+const TRUNCATED_STOP_REASONS = new Set(['max_tokens', 'max_output_tokens', 'length', 'model_length'])+const BLOCKED_STOP_REASONS = new Set([+ 'prohibited_content',+ 'content_filter',+ 'content_filtered',+ 'safety',+ 'recitation',+ 'blocklist',+])++/** Maps an `$ai_stop_reason` value to what it means for the user, or null for a normal ending. */+export function describeStopReason(value: unknown): string | null {+ if (typeof value !== 'string') {+ return null+ }+ // The Vercel AI SDK hyphenates its values, so `content-filter` has to reach the same entry.+ const normalized = value.trim().toLowerCase().replace(/-/g, '_')+ if (TRUNCATED_STOP_REASONS.has(normalized)) {+ return 'The response hit its token limit.'+ }+ if (BLOCKED_STOP_REASONS.has(normalized)) {+ return 'The provider blocked the response.'+ }+ return null+}+export function formatLLMUsage(trace_or_event_or_aggregation: LLMTrace | LLMTraceEvent | SpanAggregation): string | null {