Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(aio): remove sentiment from the generations table (#96458)

posthog[bot]1495541a2e00
diff --git a/products/ai_observability/frontend/AIObservabilityScene.tsx b/products/ai_observability/frontend/AIObservabilityScene.tsx
index 0e463d73a501..5deee0ea2d52 100644
--- a/products/ai_observability/frontend/AIObservabilityScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityScene.tsx
@@ -51,7 +51,6 @@ import { useSortableColumns } from './hooks/useSortableColumns'
import { InstrumentationChecklistCard } from './instrumentationChecklist/InstrumentationChecklistCard'
import { llmPersonsLazyLoaderLogic } from './llmPersonsLazyLoaderLogic'
import { AIObservabilitySelfDriving } from './selfDriving/AIObservabilitySelfDriving'
-import { GENERATION_SENTIMENT_SELECT } from './sentimentResults'
import { aiObservabilityDashboardLogic } from './tabs/aiObservabilityDashboardLogic'
import { aiObservabilityErrorsLogic } from './tabs/aiObservabilityErrorsLogic'
import { getDefaultGenerationsColumns, aiObservabilityGenerationsLogic } from './tabs/aiObservabilityGenerationsLogic'
@@ -317,7 +316,6 @@ function AIObservabilityGenerations(): JSX.Element {
),
},
person: aiObservabilityColumnRenderers.person,
- [GENERATION_SENTIMENT_SELECT]: aiObservabilityColumnRenderers[GENERATION_SENTIMENT_SELECT],
'properties.$ai_tools_called': aiObservabilityColumnRenderers['properties.$ai_tools_called'],
"f'{properties.$ai_model}' -- Model": {
renderTitle: () => renderSortableColumnTitle('properties.$ai_model', 'Model'),
diff --git a/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx b/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx
index 8d82f37b6feb..3c3b101fa3f3 100644
--- a/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx
+++ b/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx
@@ -20,11 +20,8 @@ import { AIDataLoading } from './components/AIDataLoading'
import { SentimentBar } from './components/SentimentTag'
import { LLMMessageDisplay } from './ConversationDisplay/ConversationMessagesDisplay'
import { EventData, useAIData } from './hooks/useAIData'
-import { llmGenerationSentimentLazyLoaderLogic } from './llmGenerationSentimentLazyLoaderLogic'
import { llmPersonsLazyLoaderLogic } from './llmPersonsLazyLoaderLogic'
import { normalizeMessages } from './messageNormalization'
-import type { GenerationSentimentLookup } from './sentimentQueries'
-import { GENERATION_SENTIMENT_SELECT } from './sentimentResults'
import { traceReviewsLazyLoaderLogic } from './traceReviews/traceReviewsLazyLoaderLogic'
import { TraceReviewValue } from './traceReviews/TraceReviewValue'
import { CompatMessage } from './types'
@@ -215,70 +212,6 @@ export function LazyPersonAvatar({ distinctId }: { distinctId: string }): JSX.El
)
}
-function getStringColumnValue(record: unknown[], columns: string[], column: string): string | null {
- const index = columns.findIndex((col) => col === column)
- if (index < 0) {
- return null
- }
-
- const value = record[index]
- return typeof value === 'string' && value ? value : null
-}
-
-function getGenerationSentimentLookup(record: unknown, query: DataTableNode): GenerationSentimentLookup | null {
- if (!Array.isArray(record) || !isEventsQuery(query.source)) {
- return null
- }
-
- const columns = query.source.select ?? []
- const eventId = getStringColumnValue(record, columns, 'uuid')
- const traceId = getStringColumnValue(record, columns, 'properties.$ai_trace_id')
-
- if (!eventId || !traceId) {
- return null
- }
-
- const generationId = getStringColumnValue(record, columns, 'properties.$ai_generation_id')
- const generationIds = generationId && generationId !== eventId ? [eventId, generationId] : [eventId]
-
- return {
- key: eventId,
- traceId,
- generationIds,
- }
-}
-
-function LazyGenerationSentimentCell({ lookup }: { lookup: GenerationSentimentLookup }): JSX.Element {
- const { getGenerationSentiment, isGenerationLoading } = useValues(llmGenerationSentimentLazyLoaderLogic)
- const { ensureGenerationSentimentLoaded } = useActions(llmGenerationSentimentLazyLoaderLogic)
-
- const lookupKey = lookup.key
- const lookupTraceId = lookup.traceId
- const lookupGenerationIdsKey = lookup.generationIds.join('\0')
- const cached = getGenerationSentiment(lookupKey)
- const loading = isGenerationLoading(lookupKey)
-
- useEffect(() => {
- if (cached === undefined && !loading) {
- ensureGenerationSentimentLoaded({
- key: lookupKey,
- traceId: lookupTraceId,
- generationIds: lookupGenerationIdsKey ? lookupGenerationIdsKey.split('\0') : [],
- })
- }
- }, [cached, ensureGenerationSentimentLoaded, loading, lookupGenerationIdsKey, lookupKey, lookupTraceId])
-
- if (loading || cached === undefined) {
- return <AIDataLoading variant="inline" />
- }
-
- if (cached === null) {
- return <>–</>
- }
-
- return <SentimentBar label={cached.label} score={cached.score} size="full" messages={cached.messages} />
-}
-
function LazyTraceReviewColumnCell({ traceId }: { traceId: string }): JSX.Element {
const { getTraceReview, isTraceLoading, didTraceReviewLoadFail } = useValues(traceReviewsLazyLoaderLogic)
const { ensureReviewsLoaded } = useActions(traceReviewsLazyLoaderLogic)
@@ -549,17 +482,6 @@ export const aiObservabilityColumnRenderers: Record<string, QueryContextColumn>
)
},
},
- [GENERATION_SENTIMENT_SELECT]: {
- title: 'Sentiment',
- render: ({ record, query }) => {
- if (!isDataTableNode(query)) {
- return <>–</>
- }
-
- const lookup = getGenerationSentimentLookup(record, query)
- return lookup ? <LazyGenerationSentimentCell lookup={lookup} /> : <>–</>
- },
- },
'properties.$ai_tools_called': {
title: 'Tools',
render: ({ value }) => {
diff --git a/products/ai_observability/frontend/aiObservabilityLogic.test.ts b/products/ai_observability/frontend/aiObservabilityLogic.test.ts
index 7d58afa845a3..d0802577b0cf 100644
--- a/products/ai_observability/frontend/aiObservabilityLogic.test.ts
+++ b/products/ai_observability/frontend/aiObservabilityLogic.test.ts
@@ -12,7 +12,7 @@ import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { productRedirects } from '~/products'
-import { isTracesQuery } from '~/queries/utils'
+import { isEventsQuery, isTracesQuery } from '~/queries/utils'
import { initKeaTests } from '~/test/init'
import { PropertyFilterType, PropertyOperator } from '~/types'
@@ -581,20 +581,38 @@ describe('AI observability persisted preferences', () => {
sharedLogic.unmount()
})
- it('persists generation column preferences across remount', () => {
- const columns = ['uuid', 'timestamp']
- const firstLogic = aiObservabilityGenerationsLogic()
- firstLogic.mount()
- firstLogic.actions.setGenerationsColumns(columns)
- firstLogic.unmount()
+ it.each([[['uuid', 'timestamp']], [['uuid', "'' -- Sentiment", 'timestamp']]])(
+ 'preserves generation column preferences while excluding retired sentiment (%j)',
+ (columns) => {
+ const firstLogic = aiObservabilityGenerationsLogic()
+ firstLogic.mount()
+ firstLogic.actions.setGenerationsColumns(columns)
+ firstLogic.unmount()
- const secondLogic = aiObservabilityGenerationsLogic()
- secondLogic.mount()
+ const secondLogic = aiObservabilityGenerationsLogic()
+ secondLogic.mount()
- expect(secondLogic.values.generationsColumns).toEqual(columns)
+ expect(secondLogic.values.generationsColumns).toEqual(columns)
- secondLogic.unmount()
- })
+ const query = secondLogic.values.generationsQuery
+ if (!isEventsQuery(query.source)) {
+ throw new Error('Expected an EventsQuery')
+ }
+ expect(query.source.select).toEqual(['uuid', 'timestamp'])
+
+ secondLogic.actions.setGenerationsQuery({
+ ...query,
+ source: { ...query.source, select: columns },
+ })
+ const overriddenQuery = secondLogic.values.generationsQuery
+ expect(isEventsQuery(overriddenQuery.source) && overriddenQuery.source.select).toEqual([
+ 'uuid',
+ 'timestamp',
+ ])
+
+ secondLogic.unmount()
+ }
+ )
it('persists traces table preferences across remount', () => {
const firstLogic = aiObservabilityTracesTabLogic()
diff --git a/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.test.ts b/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.test.ts
deleted file mode 100644
index e645aac9b67e..000000000000
--- a/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.test.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import { initKeaTests } from '~/test/init'
-
-import { llmGenerationSentimentLazyLoaderLogic } from './llmGenerationSentimentLazyLoaderLogic'
-import type { GenerationSentiment } from './sentimentResults'
-
-describe('llmGenerationSentimentLazyLoaderLogic', () => {
- let logic: ReturnType<typeof llmGenerationSentimentLazyLoaderLogic.build>
-
- const sentiment: GenerationSentiment = {
- label: 'positive',
- score: 0.9,
- scores: { positive: 0.9, neutral: 0.08, negative: 0.02 },
- messages: {},
- message_count: 1,
- }
-
- beforeEach(() => {
- initKeaTests()
- logic = llmGenerationSentimentLazyLoaderLogic()
- logic.mount()
- })
-
- afterEach(() => {
- logic.unmount()
- })
-
- it('starts with an empty cache and loading set', () => {
- expect(logic.values.sentimentByGenerationKey).toEqual({})
- expect(logic.values.loadingGenerationKeys).toEqual(new Set())
- })
-
- it('marks a generation as loading when queued', async () => {
- await expectLogic(logic, () => {
- logic.actions.ensureGenerationSentimentLoaded({
- key: 'event-uuid-1',
- traceId: 'trace-1',
- generationIds: ['event-uuid-1'],
- })
- }).toMatchValues({
- loadingGenerationKeys: new Set(['event-uuid-1']),
- })
- })
-
- it('stores successful sentiment results by lookup key', async () => {
- await expectLogic(logic, () => {
- logic.actions.loadGenerationSentimentBatchSuccess({ 'event-uuid-1': sentiment }, ['event-uuid-1'])
- }).toMatchValues({
- sentimentByGenerationKey: {
- 'event-uuid-1': sentiment,
- },
- })
- })
-
- it('stores null for requested generations without results', async () => {
- await expectLogic(logic, () => {
- logic.actions.loadGenerationSentimentBatchSuccess({}, ['event-uuid-1', 'event-uuid-2'])
- }).toMatchValues({
- sentimentByGenerationKey: {
- 'event-uuid-1': null,
- 'event-uuid-2': null,
- },
- })
- })
-
- it('clears loading keys after failures', async () => {
- logic.actions.ensureGenerationSentimentLoaded({
- key: 'event-uuid-1',
- traceId: 'trace-1',
- generationIds: ['event-uuid-1'],
- })
-
- await expectLogic(logic, () => {
- logic.actions.loadGenerationSentimentBatchFailure(['event-uuid-1'])
- }).toMatchValues({
- loadingGenerationKeys: new Set(),
- sentimentByGenerationKey: {
- 'event-uuid-1': null,
- },
- })
- })
-
- it('returns cached sentiment through the selector', () => {
- logic.actions.loadGenerationSentimentBatchSuccess({ 'event-uuid-1': sentiment }, ['event-uuid-1'])
-
- expect(logic.values.getGenerationSentiment('event-uuid-1')).toEqual(sentiment)
- expect(logic.values.getGenerationSentiment('event-uuid-2')).toBeUndefined()
- })
-})
diff --git a/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.ts b/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.ts
deleted file mode 100644
index 755d22cb9d7c..000000000000
--- a/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.ts
+++ /dev/null
@@ -1,210 +0,0 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
-
-import { chunk } from 'lib/utils/arrays'
-import { teamLogic } from 'scenes/teamLogic'
-
-import type { LLMSentimentResult } from '../../../frontend/src/queries/schema/schema-general'
-import { fetchStoredGenerationSentiments, type GenerationSentimentLookup } from './sentimentQueries'
-import type { GenerationSentiment } from './sentimentResults'
-import { runWithConcurrency } from './utils'
-
-const BATCH_MAX_SIZE = 100
-const MAX_CONCURRENT_BATCHES = 2
-const BATCH_TIMER_DISPOSABLE_KEY = 'generationSentimentBatchTimer'
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface llmGenerationSentimentLazyLoaderLogicValues {
- currentTeamId: number | null // teamLogic
- getGenerationSentiment: (key: string) => GenerationSentiment | null | undefined
- isGenerationLoading: (key: string) => boolean
- loadingGenerationKeys: Set<string>
- sentimentByGenerationKey: Record<string, GenerationSentiment | null>
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface llmGenerationSentimentLazyLoaderLogicActions {
- clearLoadingGeneration: (key: string) => {
- key: string
- }
- ensureGenerationSentimentLoaded: (lookup: GenerationSentimentLookup) => {
- lookup: GenerationSentimentLookup
- }
- loadGenerationSentimentBatchFailure: (requestedKeys: string[]) => {
- requestedKeys: string[]
- }
- loadGenerationSentimentBatchSuccess: (
- results: Record<string, GenerationSentiment | null>,
- requestedKeys: string[]
- ) => {
- requestedKeys: string[]
- results: Record<string, LLMSentimentResult | null>
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface llmGenerationSentimentLazyLoaderLogicMeta {
- __keaTypeGenInternalSelectorTypes: {
- isGenerationLoading: (loadingGenerationKeys: Set<string>) => (key: string) => boolean
- getGenerationSentiment: (
- sentimentByGenerationKey: Record<string, LLMSentimentResult | null>
- ) => (key: string) => GenerationSentiment | null | undefined
- }
-}
-
-export type llmGenerationSentimentLazyLoaderLogicType = MakeLogicType<
- llmGenerationSentimentLazyLoaderLogicValues,
- llmGenerationSentimentLazyLoaderLogicActions,
- Record<string, any>,
- llmGenerationSentimentLazyLoaderLogicMeta
->
-
-export const llmGenerationSentimentLazyLoaderLogic = kea<llmGenerationSentimentLazyLoaderLogicType>([
- path(['products', 'ai_observability', 'frontend', 'llmGenerationSentimentLazyLoaderLogic']),
-
- connect({
- values: [teamLogic, ['currentTeamId']],
- }),
-
- actions({
- ensureGenerationSentimentLoaded: (lookup: GenerationSentimentLookup) => ({ lookup }),
- loadGenerationSentimentBatchSuccess: (
- results: Record<string, GenerationSentiment | null>,
- requestedKeys: string[]
- ) => ({ results, requestedKeys }),
- loadGenerationSentimentBatchFailure: (requestedKeys: string[]) => ({ requestedKeys }),
- clearLoadingGeneration: (key: string) => ({ key }),
- }),
-
- reducers({
- sentimentByGenerationKey: [
- {} as Record<string, GenerationSentiment | null>,
- {
- loadGenerationSentimentBatchSuccess: (state, { results, requestedKeys }) => {
- const next = { ...state }
-
- for (const key of requestedKeys) {
- next[key] = results[key] ?? null
- }
-
- return next
- },
- loadGenerationSentimentBatchFailure: (state, { requestedKeys }) => {
- const next = { ...state }
-
- for (const key of requestedKeys) {
- next[key] = null
- }
-
- return next
- },
- },
- ],
-
- loadingGenerationKeys: [
- new Set<string>(),
- {
- ensureGenerationSentimentLoaded: (state, { lookup }) => {
- if (state.has(lookup.key)) {
- return state
- }
-
- const next = new Set(state)
- next.add(lookup.key)
- return next
- },
- loadGenerationSentimentBatchSuccess: (state, { requestedKeys }) => {
- const next = new Set(state)
-
- for (const key of requestedKeys) {
- next.delete(key)
- }
-
- return next
- },
- loadGenerationSentimentBatchFailure: (state, { requestedKeys }) => {
- const next = new Set(state)
-
- for (const key of requestedKeys) {
- next.delete(key)
- }
-
- return next
- },
- clearLoadingGeneration: (state, { key }) => {
- if (!state.has(key)) {
- return state
- }
-
- const next = new Set(state)
- next.delete(key)
- return next
- },
- },
- ],
- }),
-
- selectors({
- isGenerationLoading: [
- (s) => [s.loadingGenerationKeys],
- (loadingGenerationKeys: Set<string>): ((key: string) => boolean) => {
- return (key: string) => loadingGenerationKeys.has(key)
- },
- ],
- getGenerationSentiment: [
- (s) => [s.sentimentByGenerationKey],
- (
- sentimentByGenerationKey: Record<string, GenerationSentiment | null>
- ): ((key: string) => GenerationSentiment | null | undefined) => {
- return (key: string) => sentimentByGenerationKey[key]
- },
- ],
- }),
-
- listeners(({ values, actions, cache }) => {
- return {
- ensureGenerationSentimentLoaded: ({ lookup }) => {
- if (values.sentimentByGenerationKey[lookup.key] !== undefined) {
- actions.clearLoadingGeneration(lookup.key)
- return
- }
-
- const pendingLookups = (cache.pendingLookups ??= new Map<string, GenerationSentimentLookup>()) as Map<
- string,
- GenerationSentimentLookup
- >
- pendingLookups.set(lookup.key, lookup)
-
- cache.disposables.add(() => {
- const batchTimer = setTimeout(() => {
- cache.disposables.dispose(BATCH_TIMER_DISPOSABLE_KEY)
- void (async () => {
- const pendingLookups = cache.pendingLookups as Map<string, GenerationSentimentLookup>
- const allLookups = Array.from(pendingLookups.values())
- cache.pendingLookups = new Map<string, GenerationSentimentLookup>()
-
- if (!values.currentTeamId || allLookups.length === 0) {
- actions.loadGenerationSentimentBatchFailure(allLookups.map((lookup) => lookup.key))
- return
- }
-
- const chunks = chunk(allLookups, BATCH_MAX_SIZE)
-
- await runWithConcurrency(chunks, MAX_CONCURRENT_BATCHES, async (batch) => {
- const requestedKeys = batch.map((lookup) => lookup.key)
-
- try {
- const results = await fetchStoredGenerationSentiments(batch)
- actions.loadGenerationSentimentBatchSuccess(results, requestedKeys)
- } catch {
- actions.loadGenerationSentimentBatchFailure(requestedKeys)
- }
- })
- })()
- }, 0)
-
- return () => clearTimeout(batchTimer)
- }, BATCH_TIMER_DISPOSABLE_KEY)
- },
- }
- }),
-])
diff --git a/products/ai_observability/frontend/sentimentQueries.test.ts b/products/ai_observability/frontend/sentimentQueries.test.ts
index 944cb94e659f..f5193b580fb8 100644
--- a/products/ai_observability/frontend/sentimentQueries.test.ts
+++ b/products/ai_observability/frontend/sentimentQueries.test.ts
@@ -2,7 +2,6 @@ import api from 'lib/api'
import {
fetchSentimentGenerationsPage,
- fetchStoredGenerationSentiments,
type SentimentCategory,
type SentimentGenerationsQueryValues,
} from './sentimentQueries'
@@ -11,16 +10,6 @@ jest.mock('lib/api')
const mockApi = api as jest.Mocked<typeof api>
-const storedSentimentColumns = [
- 'trace_id',
- 'generation_id',
- 'label',
- 'score',
- 'scores',
- 'messages',
- 'message_count',
- 'evaluation_timestamp',
-]
const candidateColumns = ['evaluation_id', 'trace_id', 'generation_id']
const generationColumns = [
'uuid',
@@ -79,94 +68,6 @@ describe('sentimentQueries', () => {
jest.resetAllMocks()
})
- it('reads stored generation sentiment from ai_events first', async () => {
- mockApi.queryHogQL.mockResolvedValueOnce({
- columns: storedSentimentColumns,
- results: [
- [
- 'trace-1',
- 'generation-uuid',
- 'positive',
- '0.91',
- { positive: 0.91, neutral: 0.08, negative: 0.01 },
- {
- '0': {
- label: 'positive',
- score: 0.91,
- scores: { positive: 0.91, neutral: 0.08, negative: 0.01 },
- },
- },
- 1,
- '2026-06-23T10:00:00Z',
- ],
- ],
- })
-
- const results = await fetchStoredGenerationSentiments([
- {
- key: 'generation-uuid',
- traceId: 'trace-1',
- generationIds: ['generation-uuid'],
- },
- ])
-
- expect(results['generation-uuid']).toMatchObject({
- label: 'positive',
- score: 0.91,
- message_count: 1,
- })
- expect(mockApi.queryHogQL).toHaveBeenCalledTimes(1)
- const sentimentQuery = mockApi.queryHogQL.mock.calls[0][0]
- expect(sentimentQuery).toContain('FROM posthog.ai_events AS ai_events')
- expect(sentimentQuery).toContain("properties.$ai_evaluation_runtime = 'sentiment'")
- expect(sentimentQuery).toContain('properties.$ai_target_event_id')
- expect(sentimentQuery).not.toContain('properties.$ai_target_id')
- expect(sentimentQuery).not.toContain('properties.$ai_evaluation_result_type')
- })
-
- it('falls back to events when stored generation sentiment is missing from ai_events', async () => {
- mockApi.queryHogQL
- .mockResolvedValueOnce({ columns: storedSentimentColumns, results: [] })
- .mockResolvedValueOnce({
- columns: storedSentimentColumns,
- results: [
- [
- 'trace-1',
- 'generation-uuid',
- 'positive',
- '0.91',
- { positive: 0.91, neutral: 0.08, negative: 0.01 },
- {
- '0': {
- label: 'positive',
- score: 0.91,
- scores: { positive: 0.91, neutral: 0.08, negative: 0.01 },
- },
- },
- 1,
- '2026-06-23T10:00:00Z',
- ],
- ],
- })
-
- const results = await fetchStoredGenerationSentiments([
- {
- key: 'generation-uuid',
- traceId: 'trace-1',
- generationIds: ['generation-uuid'],
- },
- ])
-
- expect(results['generation-uuid']).toMatchObject({
- label: 'positive',
- score: 0.91,
- message_count: 1,
- })
- expect(mockApi.queryHogQL).toHaveBeenCalledTimes(2)
- expect(mockApi.queryHogQL.mock.calls[0][0]).toContain('FROM posthog.ai_events AS ai_events')
- expect(mockApi.queryHogQL.mock.calls[1][0]).toContain('FROM events')
- })
-
it.each<[string, boolean]>([
['excluding test accounts', true],
['including test accounts', false],
diff --git a/products/ai_observability/frontend/sentimentQueries.ts b/products/ai_observability/frontend/sentimentQueries.ts
index 26dd77a39b49..f02d4334f25a 100644
--- a/products/ai_observability/frontend/sentimentQueries.ts
+++ b/products/ai_observability/frontend/sentimentQueries.ts
@@ -26,16 +26,6 @@ const EVALUATION_TARGET_ID_SELECT = `
ifNull(nullIf(nullIf(toString(properties.$ai_target_event_id), ''), 'null'), '')
`
-const STORED_SENTIMENT_COLUMNS = [
- 'trace_id',
- 'generation_id',
- 'label',
- 'score',
- 'scores',
- 'messages',
- 'message_count',
-] as const
-
const SENTIMENT_EVALUATION_CANDIDATE_COLUMNS = ['evaluation_id', 'trace_id', 'generation_id'] as const
const SENTIMENT_GENERATION_COLUMNS = [
@@ -53,33 +43,12 @@ const SENTIMENT_GENERATION_COLUMNS = [
'message_count',
] as const
-interface SentimentQuerySource {
- from: string
- traceIdExpression: string
-}
-
-const AI_EVENTS_SOURCE: SentimentQuerySource = {
- from: 'posthog.ai_events AS ai_events',
- traceIdExpression: 'trace_id',
-}
-
-const EVENTS_SOURCE: SentimentQuerySource = {
- from: 'events',
- traceIdExpression: 'properties.$ai_trace_id',
-}
-
interface SentimentEvaluationCandidate {
evaluationId: string
traceId: string
generationId: string
}
-export interface GenerationSentimentLookup {
- key: string
- traceId: string
- generationIds: string[]
-}
-
export interface SentimentGeneration {
uuid: string
traceId: string
@@ -155,123 +124,6 @@ function hasUsableInput(value: unknown): boolean {
return value !== null && value !== undefined && value !== '' && value !== 'null'
}
-async function queryStoredGenerationSentiments(
- normalizedLookups: GenerationSentimentLookup[],
- source: SentimentQuerySource
-): Promise<Map<string, GenerationSentiment>> {
- const traceIds = uniqueNonEmpty(normalizedLookups.map((lookup) => lookup.traceId))
- const generationIds = uniqueNonEmpty(normalizedLookups.flatMap((lookup) => lookup.generationIds))
-
- if (traceIds.length === 0 || generationIds.length === 0) {
- return new Map()
- }
-
- const response = await api.queryHogQL<unknown[][]>(
- hogql`
- SELECT
- trace_id,
- generation_id,
- argMax(label, timestamp) AS label,
- argMax(score, timestamp) AS score,
- argMax(scores, timestamp) AS scores,
- argMax(messages, timestamp) AS messages,
- argMax(message_count, timestamp) AS message_count,
- max(timestamp) AS evaluation_timestamp
- FROM (
- SELECT
- ${hogql.raw(source.traceIdExpression)} AS trace_id,
- ${hogql.raw(EVALUATION_TARGET_ID_SELECT)} AS generation_id,
- timestamp,
- toString(properties.$ai_sentiment_label) AS label,
- toString(properties.$ai_sentiment_score) AS score,
- properties.$ai_sentiment_scores AS scores,
- properties.$ai_sentiment_messages AS messages,
- toString(properties.$ai_sentiment_message_count) AS message_count
- FROM ${hogql.raw(source.from)}
- WHERE event = '$ai_evaluation'
- AND properties.$ai_evaluation_runtime = 'sentiment'
- AND ${hogql.raw(source.traceIdExpression)} IN ${traceIds}
- )
- WHERE length(generation_id) > 0
- AND generation_id IN ${generationIds}
- GROUP BY trace_id, generation_id
- LIMIT ${Math.max(generationIds.length, 1)}
- `,
- { ...SENTIMENT_QUERY_TAGS, name: 'ai_observability_generation_sentiment_lookup' }
- )
-
- const columnIndexes = buildQueryColumnIndexes(response.columns, STORED_SENTIMENT_COLUMNS)
- const sentimentByTargetId = new Map<string, GenerationSentiment>()
- for (const row of response.results) {
- const generationId = normalizeString(queryColumnValue(row, columnIndexes, 'generation_id'))
- const normalized = normalizeSentimentResult({
- label: queryColumnValue(row, columnIndexes, 'label'),
- score: queryColumnValue(row, columnIndexes, 'score'),
- scores: queryColumnValue(row, columnIndexes, 'scores'),
- messages: queryColumnValue(row, columnIndexes, 'messages'),
- message_count: queryColumnValue(row, columnIndexes, 'message_count'),
- })
-
- if (generationId) {
- sentimentByTargetId.set(generationId, normalized)
- }
- }
-
- return sentimentByTargetId
-}
-
-function getUnresolvedLookups(
- lookups: GenerationSentimentLookup[],
- sentimentByTargetId: Map<string, GenerationSentiment>
-): GenerationSentimentLookup[] {
- return lookups.filter(
- (lookup) => !lookup.generationIds.some((generationId) => sentimentByTargetId.has(generationId))
- )
-}
-
-export async function fetchStoredGenerationSentiments(
- lookups: GenerationSentimentLookup[]
-): Promise<Record<string, GenerationSentiment | null>> {
- const normalizedLookups = lookups
- .map((lookup) => ({
- key: lookup.key,
- traceId: lookup.traceId,
- generationIds: uniqueNonEmpty(lookup.generationIds),
- }))
- .filter((lookup) => lookup.key && lookup.traceId && lookup.generationIds.length > 0)
-
- const results: Record<string, GenerationSentiment | null> = {}
- for (const lookup of normalizedLookups) {
- results[lookup.key] = null
- }
-
- if (normalizedLookups.length === 0) {
- return results
- }
-
- const sentimentByTargetId = await queryStoredGenerationSentiments(normalizedLookups, AI_EVENTS_SOURCE)
- const fallbackLookups = getUnresolvedLookups(normalizedLookups, sentimentByTargetId)
-
- if (fallbackLookups.length > 0) {
- const fallbackResults = await queryStoredGenerationSentiments(fallbackLookups, EVENTS_SOURCE)
- for (const [generationId, sentiment] of fallbackResults) {
- sentimentByTargetId.set(generationId, sentiment)
- }
- }
-
- for (const lookup of normalizedLookups) {
- for (const generationId of lookup.generationIds) {
- const sentiment = sentimentByTargetId.get(generationId)
- if (sentiment) {
- results[lookup.key] = sentiment
- break
- }
- }
- }
-
- return results
-}
-
async function fetchSentimentEvaluationCandidates(
values: SentimentGenerationsQueryValues,
offset: number,
diff --git a/products/ai_observability/frontend/sentimentResults.ts b/products/ai_observability/frontend/sentimentResults.ts
index ffc1961eb234..db07d56b1362 100644
--- a/products/ai_observability/frontend/sentimentResults.ts
+++ b/products/ai_observability/frontend/sentimentResults.ts
@@ -3,8 +3,6 @@ import { LLMSentimentMessage, LLMSentimentResult } from '~/queries/schema/schema
export type MessageSentiment = LLMSentimentMessage
export type GenerationSentiment = LLMSentimentResult
-export const GENERATION_SENTIMENT_SELECT = "'' -- Sentiment"
-
const SENTIMENT_LABELS = new Set(['positive', 'neutral', 'negative'])
export function normalizeSentimentResult(value: Record<string, unknown>): GenerationSentiment
diff --git a/products/ai_observability/frontend/tabs/aiObservabilityGenerationsLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilityGenerationsLogic.ts
index f47b026ed88a..df4f0ece4b01 100644
--- a/products/ai_observability/frontend/tabs/aiObservabilityGenerationsLogic.ts
+++ b/products/ai_observability/frontend/tabs/aiObservabilityGenerationsLogic.ts
@@ -5,12 +5,12 @@ import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { groupsModel } from '~/models/groupsModel'
import { DataTableNode, LLMTrace, NodeKind, TraceQuery } from '~/queries/schema/schema-general'
+import { isEventsQuery } from '~/queries/utils'
import type { AnyPropertyFilter } from '../../../../frontend/src/types'
import { SortDirection, SortState, aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'
import type { ApplyUrlStatePayload } from '../aiObservabilitySharedLogic'
import { buildAiObservabilityStorageConfig } from '../preferenceStorage'
-import { GENERATION_SENTIMENT_SELECT } from '../sentimentResults'
export type AIObservabilityGenerationsLogicProps = Record<string, never>
@@ -19,7 +19,6 @@ export function getDefaultGenerationsColumns(): string[] {
'uuid',
'properties.$ai_trace_id',
'person',
- GENERATION_SENTIMENT_SELECT,
"f'{properties.$ai_model}' -- Model",
'properties.$ai_tools_called',
"if(properties.$ai_is_error = 'true', '❌', '') -- Error",
@@ -246,7 +245,21 @@ export const aiObservabilityGenerationsLogic = kea<aiObservabilityGenerationsLog
selectors({
generationsQuery: [
(s) => [s.generationsQueryOverride, s.defaultGenerationsQuery],
- (override: DataTableNode | null, defQuery: DataTableNode) => override || defQuery,
+ (override: DataTableNode | null, defQuery: DataTableNode): DataTableNode => {
+ const query = override || defQuery
+ if (!isEventsQuery(query.source)) {
+ return query
+ }
+
+ return {
+ ...query,
+ source: {
+ ...query.source,
+ // Saved column selections can still contain the retired sentiment placeholder.
+ select: query.source.select?.filter((column) => column !== "'' -- Sentiment"),
+ },
+ }
+ },
],
defaultGenerationsQuery: [