: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(llma): show tags on LLM generation traces and event panels (5/5) (#54592)
Andrew Maguire447ca1ec5427
diff --git a/frontend/src/lib/components/EventPropertyTabs/EventPropertyTabs.tsx b/frontend/src/lib/components/EventPropertyTabs/EventPropertyTabs.tsxindex 9078d0f8c097..82f8f08c041b 100644--- a/frontend/src/lib/components/EventPropertyTabs/EventPropertyTabs.tsx+++ b/frontend/src/lib/components/EventPropertyTabs/EventPropertyTabs.tsx@@ -34,6 +34,7 @@ type EventPropertyTabKey =| 'raw'| 'conversation'| 'evaluation'+ | 'tag'| 'exception_properties'| 'error_display'| 'debug_properties'@@ -55,6 +56,7 @@ export const EventPropertyTabs = ({const isAIGenerationEvent = event.event === '$ai_generation'const isAIConversationEvent = isAIGenerationEvent || event.event === '$ai_span' || event.event === '$ai_trace'const isAIEvaluationEvent = event.event === '$ai_evaluation'+ const isAITagEvent = event.event === '$ai_tag'const isErrorEvent = event.event === '$exception'const isSurveyResponseEvent = event.event === 'survey sent'@@ -68,13 +70,15 @@ export const EventPropertyTabs = ({? 'conversation': isAIEvaluationEvent? 'evaluation'- : isErrorEvent- ? 'error_display'- : isSurveyResponseEvent- ? 'survey_response'- : isMcpEvent- ? 'mcp'- : 'properties'+ : isAITagEvent+ ? 'tag'+ : isErrorEvent+ ? 'error_display'+ : isSurveyResponseEvent+ ? 'survey_response'+ : isMcpEvent+ ? 'mcp'+ : 'properties')const promotedKeys = isKeyOf(event.event, POSTHOG_EVENT_PROMOTED_PROPERTIES)@@ -140,6 +144,13 @@ export const EventPropertyTabs = ({content: tabContentComponentFn({ event, properties: event.properties, tabKey: 'evaluation' }),}: null,+ isAITagEvent+ ? {+ key: 'tag',+ label: 'Tag',+ content: tabContentComponentFn({ event, properties: event.properties, tabKey: 'tag' }),+ }+ : null,{key: 'properties',label: 'Properties',diff --git a/frontend/src/scenes/activity/explore/EventDetails.tsx b/frontend/src/scenes/activity/explore/EventDetails.tsxindex aa0cf2e85165..3d1ff2f0368c 100644--- a/frontend/src/scenes/activity/explore/EventDetails.tsx+++ b/frontend/src/scenes/activity/explore/EventDetails.tsx@@ -18,6 +18,7 @@ import { PropertyDefinitionType } from '~/types'import { ConversationDisplay } from 'products/ai_observability/frontend/ConversationDisplay/ConversationDisplay'import { EvaluationDisplay } from 'products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay'+import { TagDisplay } from 'products/ai_observability/frontend/ConversationDisplay/TagDisplay'import { MCPEventView } from './MCPEventView'@@ -91,6 +92,12 @@ export function EventDetails({ event, tableProps }: EventDetailsProps): JSX.Elem<EvaluationDisplay eventProperties={properties} /></div>)+ case 'tag':+ return (+ <div className="mx-3 -mt-2 mb-2">+ <TagDisplay eventProperties={properties} />+ </div>+ )case 'error_display':return (<div className="mx-3">diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsxindex 1e7575d16e34..327a1e3615ce 100644--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx@@ -73,6 +73,7 @@ import { FeedbackTag } from './components/FeedbackTag'import { JSONValueDisplay } from './components/JSONValueDisplay'import { MetricTag } from './components/MetricTag'import { SentimentBar } from './components/SentimentTag'+import { TagsTabContent } from './components/TagsTabContent'import {ConversationDisplayOption,ConversationMessagesDisplay,@@ -1474,6 +1475,16 @@ const EventContent = React.memo(const showSaveToDatasetButton = featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_DATASETS]const showEvalsTab = effectiveGenerationEvent && !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS]+ const showTagsTab = effectiveGenerationEvent && !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_TAGS]++ // If the user is viewing the Tags tab but it's no longer available (flag off or+ // they moved off a generation event), fall back to the default view so the panel+ // doesn't render blank.+ useEffect(() => {+ if (viewMode === TraceViewMode.Tags && !showTagsTab) {+ setViewMode(TraceViewMode.Conversation)+ }+ }, [viewMode, showTagsTab, setViewMode])const showSummaryTab =featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_SUMMARIZATION] ||@@ -1782,6 +1793,16 @@ const EventContent = React.memo(},]: []),+ ...(showTagsTab+ ? [+ {+ key: TraceViewMode.Tags,+ label: 'Tags',+ 'data-attr': 'llma-trace-tags-tab',+ content: <TagsTabContent generationEventId={event.id} />,+ },+ ]+ : []),{key: TraceViewMode.Clusters,label: 'Clusters',diff --git a/products/ai_observability/frontend/ConversationDisplay/TagDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/TagDisplay.tsxnew file mode 100644index 000000000000..d6f90a538e88--- /dev/null+++ b/products/ai_observability/frontend/ConversationDisplay/TagDisplay.tsx@@ -0,0 +1,67 @@+import { LemonTag, Link } from '@posthog/lemon-ui'++import { lowercaseFirstLetter } from 'lib/utils'+import { urls } from 'scenes/urls'++import { EventType } from '~/types'++import { MetadataTag } from '../components/MetadataTag'+import { parseTagsCell } from '../generationTagRunsLogic'++export function TagDisplay({ eventProperties }: { eventProperties: EventType['properties'] }): JSX.Element {+ // Reuse the loader's JSON-string defense so a stringified $ai_tags property+ // doesn't end up iterated character-by-character here.+ const tags: string[] = parseTagsCell(eventProperties.$ai_tags)+ const reasoning = eventProperties.$ai_tag_reasoning+ const taggerName = eventProperties.$ai_tagger_name+ const model = eventProperties.$ai_model+ const traceId = eventProperties.$ai_trace_id+ const targetEventId = eventProperties.$ai_target_event_id+ const tagCount = eventProperties.$ai_tag_count++ return (+ <div className="space-y-4">+ <div className="flex flex-wrap gap-2">+ {tags.length > 0 ? (+ tags.map((tag: string) => (+ <LemonTag key={tag} type="highlight">+ {tag}+ </LemonTag>+ ))+ ) : (+ <LemonTag type="muted">No tags</LemonTag>+ )}+ </div>++ <div className="flex flex-wrap gap-2">+ {taggerName && (+ <MetadataTag label="Tagger" textToCopy={taggerName}>+ {taggerName}+ </MetadataTag>+ )}+ {model && (+ <MetadataTag label="Model" textToCopy={lowercaseFirstLetter(model)}>+ {lowercaseFirstLetter(model)}+ </MetadataTag>+ )}+ {tagCount !== undefined && tagCount !== null && (+ <MetadataTag label="Tag count">{String(tagCount)}</MetadataTag>+ )}+ {traceId && targetEventId && (+ <MetadataTag label="Target event">+ <Link to={urls.aiObservabilityTrace(traceId, { event: targetEventId })}>+ {targetEventId.slice(0, 12)}...+ </Link>+ </MetadataTag>+ )}+ </div>++ {reasoning && (+ <div className="p-3 border rounded bg-surface-primary">+ <div className="font-medium text-xs text-muted mb-1.5">REASONING</div>+ <div className="text-sm whitespace-pre-wrap">{reasoning}</div>+ </div>+ )}+ </div>+ )+}diff --git a/products/ai_observability/frontend/aiObservabilityTraceLogic.ts b/products/ai_observability/frontend/aiObservabilityTraceLogic.tsindex d7103a923202..6c0a4da09d91 100644--- a/products/ai_observability/frontend/aiObservabilityTraceLogic.ts+++ b/products/ai_observability/frontend/aiObservabilityTraceLogic.ts@@ -47,6 +47,7 @@ export enum TraceViewMode {Raw = 'raw',Summary = 'summary',Evals = 'evals',+ Tags = 'tags',Clusters = 'clusters',Feedback = 'feedback',}@@ -149,6 +150,9 @@ export const aiObservabilityTraceLogic = kea<aiObservabilityTraceLogicType>([if (tab === 'clusters') {return TraceViewMode.Clusters}+ if (tab === 'tags') {+ return TraceViewMode.Tags+ }if (tab === 'feedback') {return TraceViewMode.Feedback}diff --git a/products/ai_observability/frontend/components/TagsTabContent.tsx b/products/ai_observability/frontend/components/TagsTabContent.tsxnew file mode 100644index 000000000000..50350821f8ce--- /dev/null+++ b/products/ai_observability/frontend/components/TagsTabContent.tsx@@ -0,0 +1,96 @@+import { useActions, useValues } from 'kea'++import { IconRefresh } from '@posthog/icons'+import { LemonButton, LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { urls } from 'scenes/urls'++import { generationTagRunsLogic } from '../generationTagRunsLogic'+import { TagRun } from '../tags/llmTaggerLogic'++export function TagsTabContent({ generationEventId }: { generationEventId: string }): JSX.Element {+ const logic = generationTagRunsLogic({ generationEventId })+ const { generationTagRuns, generationTagRunsLoading } = useValues(logic)+ const { loadGenerationTagRuns } = useActions(logic)++ const columns: LemonTableColumns<TagRun> = [+ {+ title: 'Tagger',+ key: 'tagger_name',+ render: (_, run) =>+ run.tagger_id ? (+ <Link to={urls.aiObservabilityTag(run.tagger_id)} className="font-medium">+ {run.tagger_name || run.tagger_id.slice(0, 12)}+ </Link>+ ) : (+ <span className="font-medium">{run.tagger_name || '-'}</span>+ ),+ },+ {+ title: 'Tags',+ key: 'tags',+ render: (_, run) => (+ <div className="flex flex-wrap gap-1">+ {run.tags.length > 0 ? (+ run.tags.map((tag: string) => (+ <LemonTag key={tag} type="highlight">+ {tag}+ </LemonTag>+ ))+ ) : (+ <span className="text-muted text-sm">No tags</span>+ )}+ </div>+ ),+ },+ {+ title: 'Reasoning',+ key: 'reasoning',+ render: (_, run) =>+ run.reasoning ? (+ <Tooltip title={run.reasoning} placement="top">+ <div className="max-w-md text-sm truncate cursor-default">{run.reasoning}</div>+ </Tooltip>+ ) : (+ <span className="text-muted text-sm">-</span>+ ),+ },+ {+ title: 'Timestamp',+ key: 'timestamp',+ render: (_, run) => <TZLabel time={run.timestamp} />,+ },+ ]++ return (+ <div className="py-4">+ <div className="flex justify-between items-center mb-4">+ <p className="text-muted text-sm m-0">Tags applied to this generation by your taggers.</p>+ <LemonButton+ type="secondary"+ icon={<IconRefresh />}+ onClick={loadGenerationTagRuns}+ loading={generationTagRunsLoading}+ size="small"+ >+ Refresh+ </LemonButton>+ </div>+ <LemonTable+ columns={columns}+ dataSource={generationTagRuns}+ loading={generationTagRunsLoading}+ rowKey={(run) => run.uuid ?? `${run.tagger_id}-${run.timestamp}`}+ nouns={['tag run', 'tag runs']}+ emptyState={+ <div className="text-center py-8 text-muted">+ No tags applied to this generation yet.{' '}+ <Link to={urls.aiObservabilityTags()}>Enable a tagger</Link> to start tagging.+ </div>+ }+ />+ </div>+ )+}diff --git a/products/ai_observability/frontend/generationTagRunsLogic.ts b/products/ai_observability/frontend/generationTagRunsLogic.tsnew file mode 100644index 000000000000..c60d33ee8dd1--- /dev/null+++ b/products/ai_observability/frontend/generationTagRunsLogic.ts@@ -0,0 +1,88 @@+import { afterMount, kea, key, path, props } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'++import { HogQLQuery, NodeKind } from '~/queries/schema/schema-general'++import type { generationTagRunsLogicType } from './generationTagRunsLogicType'+import { TagRun } from './tags/llmTaggerLogic'++export interface GenerationTagRunsLogicProps {+ generationEventId: string+}++// Shared by the trace tags tab (this loader) and the event-panel TagDisplay so+// the JSON-string defense lives in one place — see TagDisplay.tsx.+export function parseTagsCell(raw: unknown): string[] {+ if (Array.isArray(raw)) {+ return raw as string[]+ }+ if (typeof raw !== 'string') {+ return []+ }+ try {+ const parsed = JSON.parse(raw)+ return Array.isArray(parsed) ? parsed : []+ } catch {+ // One malformed tags cell shouldn't discard the whole result set —+ // just drop this row's tags and keep everything else.+ return []+ }+}++export const generationTagRunsLogic = kea<generationTagRunsLogicType>([+ path(['products', 'llm_analytics', 'frontend', 'generationTagRunsLogic']),+ props({} as GenerationTagRunsLogicProps),+ key((props) => props.generationEventId),++ loaders(({ props }) => ({+ generationTagRuns: [+ [] as TagRun[],+ {+ loadGenerationTagRuns: async () => {+ // Bind the event id as a HogQL parameter instead of interpolating the+ // prop into the query string — the id is ultimately URL-derived and+ // must not be concatenated into HogQL.+ const query: HogQLQuery = {+ kind: NodeKind.HogQLQuery,+ query: `+ SELECT+ uuid,+ timestamp,+ properties.$ai_tags as tags,+ properties.$ai_tag_reasoning as reasoning,+ properties.$ai_trace_id as trace_id,+ properties.$ai_target_event_id as target_event_id,+ properties.$ai_tagger_id as tagger_id,+ properties.$ai_tagger_name as tagger_name+ FROM events+ WHERE event = '$ai_tag'+ AND properties.$ai_target_event_id = {generation_event_id}+ ORDER BY timestamp DESC+ LIMIT 50+ `,+ values: { generation_event_id: props.generationEventId },+ }+ // Let kea-loaders surface failures: a swallowed catch here would render+ // empty-state for both "no tags" and "query broke", masking real errors.+ const response = await api.query(query)+ return (response.results || []).map((row: any[]) => ({+ uuid: row[0],+ timestamp: row[1],+ tags: parseTagsCell(row[2]),+ reasoning: row[3] || '',+ trace_id: row[4] || '',+ target_event_id: row[5] || '',+ tagger_id: row[6] || '',+ tagger_name: row[7] || '',+ }))+ },+ },+ ],+ })),++ afterMount(({ actions }) => {+ actions.loadGenerationTagRuns()+ }),+])diff --git a/products/ai_observability/frontend/tags/llmTaggerLogic.ts b/products/ai_observability/frontend/tags/llmTaggerLogic.tsindex 69c7a75a5671..4440bbf6d754 100644--- a/products/ai_observability/frontend/tags/llmTaggerLogic.ts+++ b/products/ai_observability/frontend/tags/llmTaggerLogic.ts@@ -36,6 +36,10 @@ export interface HogTestResult {}export interface TagRun {+ // Optional because the tagger detail page's loader (in this file) doesn't+ // select uuid — only the per-generation loader does, where it's needed+ // for collision-free row keys in the trace Tags tab.+ uuid?: stringtimestamp: stringtags: string[]reasoning: string