: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): filter sentiment tab results in the query (#79718)
Radu Raiceaf4653c96b71c
diff --git a/products/ai_observability/frontend/AIObservabilityScene.tsx b/products/ai_observability/frontend/AIObservabilityScene.tsxindex a2fb0c5de97b..39cb3908abc6 100644--- a/products/ai_observability/frontend/AIObservabilityScene.tsx+++ b/products/ai_observability/frontend/AIObservabilityScene.tsx@@ -94,21 +94,15 @@ const Filters = ({ hidePropertyFilters = false }: { hidePropertyFilters?: booleashowCustomRangeOptions={activeTab !== 'sentiment'}/>{!hidePropertyFilters && (- <>- <PropertyFilters- propertyFilters={propertyFilters}- taxonomicGroupTypes={generationsQuery.showPropertyFilter as TaxonomicFilterGroupType[]}- onChange={setPropertyFilters}- pageKey="llm-analytics"- />- <div className="flex-1" />- <TestAccountFilterSwitch- checked={shouldFilterTestAccounts}- onChange={setShouldFilterTestAccounts}- />- </>+ <PropertyFilters+ propertyFilters={propertyFilters}+ taxonomicGroupTypes={generationsQuery.showPropertyFilter as TaxonomicFilterGroupType[]}+ onChange={setPropertyFilters}+ pageKey="llm-analytics"+ />)}- {hidePropertyFilters && <div className="flex-1" />}+ <div className="flex-1" />+ <TestAccountFilterSwitch checked={shouldFilterTestAccounts} onChange={setShouldFilterTestAccounts} />{activeTab === 'dashboard' && selectedDashboardId && (<AccessControlActionresourceType={AccessControlResourceType.LlmAnalytics}@@ -562,7 +556,8 @@ function AIObservabilitySceneContent(): JSX.Element {label: 'Sentiment',content: (<>- <Filters />+ {/* Sentiment filters evaluation results, not generations, so the generation property filters don't apply */}+ <Filters hidePropertyFilters /><AIObservabilitySentiment /></>),diff --git a/products/ai_observability/frontend/sentimentEvaluationAvailabilityLogic.ts b/products/ai_observability/frontend/sentimentEvaluationAvailabilityLogic.tsindex 35460a1fcea3..3bc708dea245 100644--- a/products/ai_observability/frontend/sentimentEvaluationAvailabilityLogic.ts+++ b/products/ai_observability/frontend/sentimentEvaluationAvailabilityLogic.ts@@ -6,6 +6,10 @@ import { getCurrentTeamId } from '~/lib/utils/getAppContext'import { evaluationsList } from './generated/api'import type { EvaluationApi } from './generated/api.schemas'+const SENTIMENT_EVALUATIONS_PAGE_SIZE = 100+/** Backstop so a runaway pager can't spin forever */+const SENTIMENT_EVALUATIONS_MAX = 1000+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface sentimentEvaluationAvailabilityLogicValues {hasLoadedSentimentEvaluations: boolean@@ -55,11 +59,26 @@ export const sentimentEvaluationAvailabilityLogic = kea<sentimentEvaluationAvail[] as EvaluationApi[],{loadSentimentEvaluations: async () => {- const response = await evaluationsList(String(getCurrentTeamId()), {- evaluation_type: 'sentiment',- limit: 1,- })- return response.results || []+ const teamId = String(getCurrentTeamId())+ const evaluations: EvaluationApi[] = []++ // Page through so the picker lists every evaluation, not just the first page.+ // The list endpoint already excludes soft-deleted ones.+ while (evaluations.length < SENTIMENT_EVALUATIONS_MAX) {+ const response = await evaluationsList(teamId, {+ evaluation_type: 'sentiment',+ limit: SENTIMENT_EVALUATIONS_PAGE_SIZE,+ offset: evaluations.length,+ order_by: ['name'],+ })+ const results = response.results || []+ evaluations.push(...results)+ if (!response.next || results.length === 0) {+ break+ }+ }++ return evaluations},},],diff --git a/products/ai_observability/frontend/sentimentQueries.test.ts b/products/ai_observability/frontend/sentimentQueries.test.tsindex d885e55b8528..050e2a36d11b 100644--- a/products/ai_observability/frontend/sentimentQueries.test.ts+++ b/products/ai_observability/frontend/sentimentQueries.test.ts@@ -1,6 +1,11 @@import api from 'lib/api'-import { fetchSentimentGenerationsPage, fetchStoredGenerationSentiments } from './sentimentQueries'+import {+ fetchSentimentGenerationsPage,+ fetchStoredGenerationSentiments,+ type SentimentCategory,+ type SentimentGenerationsQueryValues,+} from './sentimentQueries'jest.mock('lib/api')@@ -32,10 +37,11 @@ const generationColumns = ['message_count',]-const queryValues = {+const queryValues: SentimentGenerationsQueryValues = {dateFilter: { dateFrom: '-7d', dateTo: null },shouldFilterTestAccounts: false,- propertyFilters: [],+ activeFilters: new Set<SentimentCategory>(['negative', 'positive']),+ evaluationId: null,}function candidateRows(count: number, start: number = 0): unknown[][] {@@ -199,10 +205,51 @@ describe('sentimentQueries', () => {const [, , hydrationOptions] = mockApi.queryHogQL.mock.calls[1]expect(hydrationOptions?.queryParams?.filters).toEqual({filterTestAccounts: false,- properties: [],})})+ it('restricts the candidate query to a single evaluation when one is selected', async () => {+ mockApi.queryHogQL+ .mockResolvedValueOnce({ columns: candidateColumns, results: [] })+ .mockResolvedValueOnce({ columns: generationColumns, results: [] })++ await fetchSentimentGenerationsPage({ ...queryValues, evaluationId: 'eval-uuid' }, 0)++ expect(mockApi.queryHogQL.mock.calls[0][0]).toContain("AND properties.$ai_evaluation_id = 'eval-uuid'")+ })++ it.each<[string, SentimentCategory[], string, string]>([+ ['negative only', ['negative'], "label IN ['negative']", "ORDER BY JSONExtractFloat(scores, 'negative') DESC"],+ ['positive only', ['positive'], "label IN ['positive']", "ORDER BY JSONExtractFloat(scores, 'positive') DESC"],+ ])('restricts the candidate query to the selected categories (%s)', async (_, categories, labelClause, order) => {+ mockApi.queryHogQL+ .mockResolvedValueOnce({ columns: candidateColumns, results: [] })+ .mockResolvedValueOnce({ columns: generationColumns, results: [] })++ await fetchSentimentGenerationsPage({ ...queryValues, activeFilters: new Set(categories) }, 0)++ const candidateQuery = mockApi.queryHogQL.mock.calls[0][0]+ expect(candidateQuery).toContain(labelClause)+ expect(candidateQuery).toContain(order)+ })++ it.each<[string, boolean, string | undefined]>([+ ['reuses the cache by default', false, undefined],+ ['forces a recalculation on reload', true, 'force_blocking'],+ ])('%s', async (_, forceRefresh, expectedRefresh) => {+ mockApi.queryHogQL+ .mockResolvedValueOnce({+ columns: candidateColumns,+ results: [['evaluation-0', 'trace-0', 'generation-0']],+ })+ .mockResolvedValueOnce({ columns: generationColumns, results: [generationRow(0)] })++ await fetchSentimentGenerationsPage(queryValues, 0, forceRefresh)++ expect(mockApi.queryHogQL.mock.calls[0][2]?.refresh).toBe(expectedRefresh)+ expect(mockApi.queryHogQL.mock.calls[1][2]?.refresh).toBe(expectedRefresh)+ })+it('does not fall back to events when ai_events no longer retains a generation input', async () => {mockApi.queryHogQL.mockResolvedValueOnce({diff --git a/products/ai_observability/frontend/sentimentQueries.ts b/products/ai_observability/frontend/sentimentQueries.tsindex c95ae3b6fe5b..97df17e5facb 100644--- a/products/ai_observability/frontend/sentimentQueries.ts+++ b/products/ai_observability/frontend/sentimentQueries.ts@@ -1,13 +1,22 @@import api from 'lib/api'-import { ProductKey } from '~/queries/schema/schema-general'-import { hogql } from '~/queries/utils'-import { AnyPropertyFilter } from '~/types'+import { ProductKey, type RefreshType } from '~/queries/schema/schema-general'+import { escapeHogQLString, hogql } from '~/queries/utils'import { normalizeSentimentResult, type GenerationSentiment } from './sentimentResults'export const GENERATIONS_PAGE_SIZE = 200+export type SentimentCategory = 'negative' | 'positive'++const SENTIMENT_CATEGORIES: readonly SentimentCategory[] = ['negative', 'positive']++/** The categories the query should select, falling back to all of them if nothing is active */+function resolveActiveCategories(activeFilters: Set<SentimentCategory> | undefined): SentimentCategory[] {+ const active = SENTIMENT_CATEGORIES.filter((category) => activeFilters?.has(category))+ return active.length > 0 ? active : [...SENTIMENT_CATEGORIES]+}+const SENTIMENT_QUERY_TAGS = {productKey: ProductKey.AI_OBSERVABILITY,scene: 'ai_observability_sentiment',@@ -87,7 +96,9 @@ export interface SentimentGeneration {export interface SentimentGenerationsQueryValues {dateFilter: { dateFrom: string | null; dateTo: string | null }shouldFilterTestAccounts: boolean- propertyFilters: AnyPropertyFilter[]+ activeFilters: Set<SentimentCategory>+ /** Restrict results to one sentiment evaluation, or null for all of them */+ evaluationId: string | null}export interface SentimentGenerationsPage {@@ -263,8 +274,18 @@ export async function fetchStoredGenerationSentiments(async function fetchSentimentEvaluationCandidates(values: SentimentGenerationsQueryValues,- offset: number+ offset: number,+ refresh?: RefreshType): Promise<SentimentEvaluationCandidate[]> {+ const categories = resolveActiveCategories(values.activeFilters)+ const categoryScores = categories.map((category) => `JSONExtractFloat(scores, '${category}')`)+ // Rank by the strongest score among the selected categories only, so a deselected+ // category can't push a generation to the top of the page+ const rankingExpression = categoryScores.length > 1 ? `greatest(${categoryScores.join(', ')})` : categoryScores[0]+ const evaluationClause = values.evaluationId+ ? `AND properties.$ai_evaluation_id = ${escapeHogQLString(values.evaluationId)}`+ : ''+const response = await api.queryHogQL<unknown[][]>(hogql`SELECT@@ -284,23 +305,22 @@ async function fetchSentimentEvaluationCandidates(WHERE event = '$ai_evaluation'AND properties.$ai_evaluation_runtime = 'sentiment'AND timestamp >= now() - INTERVAL 30 DAY+ ${hogql.raw(evaluationClause)}AND {filters}GROUP BY trace_id, generation_id)WHERE length(evaluation_id) > 0AND length(trace_id) > 0AND length(generation_id) > 0- AND label IN ('positive', 'negative', 'neutral')+ AND label IN ${categories}AND toIntOrZero(message_count) > 0- ORDER BY greatest(- JSONExtractFloat(scores, 'positive'),- JSONExtractFloat(scores, 'negative')- ) DESC, evaluation_timestamp DESC, generation_id DESC+ ORDER BY ${hogql.raw(rankingExpression)} DESC, evaluation_timestamp DESC, generation_id DESCLIMIT ${GENERATIONS_PAGE_SIZE}OFFSET ${Math.max(0, Math.trunc(offset))}`,{ ...SENTIMENT_QUERY_TAGS, name: 'ai_observability_sentiment_evaluations' },{+ refresh,queryParams: {filters: {dateRange: {@@ -328,7 +348,8 @@ async function fetchSentimentEvaluationCandidates(async function hydrateSentimentGenerations(candidates: SentimentEvaluationCandidate[],- values: SentimentGenerationsQueryValues+ values: SentimentGenerationsQueryValues,+ refresh?: RefreshType): Promise<Map<string, SentimentGeneration>> {const traceIds = uniqueNonEmpty(candidates.map((candidate) => candidate.traceId))const generationIds = uniqueNonEmpty(candidates.map((candidate) => candidate.generationId))@@ -392,10 +413,10 @@ async function hydrateSentimentGenerations(`,{ ...SENTIMENT_QUERY_TAGS, name: 'ai_observability_sentiment_generation_hydration' },{+ refresh,queryParams: {filters: {filterTestAccounts: values.shouldFilterTestAccounts,- properties: values.propertyFilters,},},}@@ -440,21 +461,27 @@ async function hydrateSentimentGenerations(return generationById}+/**+ * Results are ranked by strongest score and rarely change between visits, so a page load reuses+ * whatever the query cache holds. Pass `forceRefresh` to recompute — that's the Reload button.+ */export async function fetchSentimentGenerationsPage(values: SentimentGenerationsQueryValues,- offset: number+ offset: number,+ forceRefresh: boolean = false): Promise<SentimentGenerationsPage> {+ const refresh: RefreshType | undefined = forceRefresh ? 'force_blocking' : undefinedconst generations: SentimentGeneration[] = []let rawCount = 0let hasMore = falsewhile (generations.length < GENERATIONS_PAGE_SIZE) {- const candidates = await fetchSentimentEvaluationCandidates(values, offset + rawCount)+ const candidates = await fetchSentimentEvaluationCandidates(values, offset + rawCount, refresh)if (candidates.length === 0) {break}- const generationById = await hydrateSentimentGenerations(candidates, values)+ const generationById = await hydrateSentimentGenerations(candidates, values, refresh)let consumedCandidates = 0for (const candidate of candidates) {diff --git a/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsx b/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsxindex 19303ef1e60e..2987135ab5d0 100644--- a/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsx+++ b/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { combineUrl } from 'kea-router'import { IconPlus, IconRefresh } from '@posthog/icons'-import { LemonButton, Link, Spinner, Tooltip } from '@posthog/lemon-ui'+import { LemonButton, LemonSelect, Link, Spinner, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { LemonSlider } from 'lib/lemon-ui/LemonSlider'@@ -173,28 +173,41 @@ function SentimentCardRow({}const CATEGORY_CONFIG: { value: SentimentCategory; label: string; activeClass: string }[] = [- { value: 'positive', label: 'Positive', activeClass: 'bg-success/20 border-success' },{ value: 'negative', label: 'Negative', activeClass: 'bg-danger/20 border-danger' },- { value: 'neutral', label: 'Neutral', activeClass: 'bg-border/20 border-border' },+ { value: 'positive', label: 'Positive', activeClass: 'bg-success/20 border-success' },]function SentimentControls(): JSX.Element {- const { activeFilters, intensityThreshold, sentimentSummary, generationsLoading } =+ const { activeFilters, intensityThreshold, sentimentSummary, generationsLoading, evaluationId, evaluationOptions } =useValues(aiObservabilitySentimentLogic)- const { toggleSentimentCategory, setIntensityThreshold, loadGenerations } =+ const { toggleSentimentCategory, setIntensityThreshold, setEvaluationId, loadGenerations } =useActions(aiObservabilitySentimentLogic)- const total = sentimentSummary.positive + sentimentSummary.negative + sentimentSummary.neutral+ const total = sentimentSummary.negative + sentimentSummary.positivereturn (<div className="flex items-center gap-4 flex-wrap mb-3" data-attr="llma-sentiment-controls"><div className="flex items-center gap-2">- <Tooltip title="Filter by sentiment polarity. Each user message is classified as positive, negative, or neutral.">+ <Tooltip title="Narrow results to a single sentiment evaluation. Each evaluation has its own trigger conditions, so this filters at the evaluation layer.">+ <span className="text-sm font-medium">Evaluation:</span>+ </Tooltip>+ <LemonSelect+ size="small"+ value={evaluationId}+ options={evaluationOptions}+ onChange={setEvaluationId}+ className="max-w-52"+ data-attr="llma-sentiment-evaluation-filter"+ />+ </div>+ <div className="flex items-center gap-2">+ <Tooltip title="Only fetch results for the sentiments you select. Each user message is classified as positive, negative, or neutral, and neutral messages are never shown here."><span className="text-sm font-medium">Show:</span></Tooltip><div className="flex items-center gap-1" data-attr="llma-sentiment-filter">{CATEGORY_CONFIG.map(({ value, label, activeClass }) => {const isActive = activeFilters.has(value)- const count = sentimentSummary[value]+ // Deselected categories aren't fetched, so their count would be misleading+ const count = isActive ? sentimentSummary[value] : 0return (<LemonButtonkey={value}@@ -212,14 +225,14 @@ function SentimentControls(): JSX.Element {</div>{total > 0 && !generationsLoading && (<Tooltip- title={`${sentimentSummary.positive} positive, ${sentimentSummary.negative} negative, ${sentimentSummary.neutral} neutral messages across all sentiment evaluation results`}+ title={`${sentimentSummary.negative} negative, ${sentimentSummary.positive} positive messages across the loaded sentiment evaluation results`}><span className="text-xs text-muted tabular-nums ml-1">{total} total</span></Tooltip>)}</div><div className="flex items-center gap-2">- <Tooltip title="Only show messages with a sentiment confidence score at or above this threshold. Higher values surface stronger signals. Does not apply to neutral messages.">+ <Tooltip title="Only show messages with a sentiment confidence score at or above this threshold. Higher values surface stronger signals."><span className="text-sm font-medium whitespace-nowrap">Min intensity:</span></Tooltip><LemonSlider@@ -237,8 +250,9 @@ function SentimentControls(): JSX.Element {icon={<IconRefresh />}size="small"type="secondary"- onClick={loadGenerations}+ onClick={() => loadGenerations({ forceRefresh: true })}loading={generationsLoading}+ disabledReason={generationsLoading ? 'Loading results' : undefined}data-attr="llma-sentiment-reload">Reloaddiff --git a/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.tsindex 12481a20735a..7cfbb0a093aa 100644--- a/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.ts+++ b/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.ts@@ -4,23 +4,20 @@ import { subscriptions } from 'kea-subscriptions'import posthog from 'posthog-js'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import type { LemonSelectOption } from 'lib/lemon-ui/LemonSelect'import { groupsModel } from '~/models/groupsModel'import type { AnyPropertyFilter } from '../../../../frontend/src/types'import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'import type { AIObservabilityTabId } from '../aiObservabilitySharedLogic'+import type { EvaluationApi } from '../generated/api.schemas'import { sentimentEvaluationAvailabilityLogic } from '../sentimentEvaluationAvailabilityLogic'-import { fetchSentimentGenerationsPage, type SentimentGeneration } from '../sentimentQueries'+import { fetchSentimentGenerationsPage, type SentimentCategory, type SentimentGeneration } from '../sentimentQueries'import type { MessageSentiment } from '../sentimentResults'import { extractContentText } from '../sentimentUtils'-export type { SentimentGeneration } from '../sentimentQueries'--export type SentimentCategory = 'positive' | 'negative' | 'neutral'--/** @deprecated Use SentimentCategory with activeFilters set instead */-export type SentimentFilterLabel = SentimentCategory | 'both'+export type { SentimentGeneration, SentimentCategory } from '../sentimentQueries'/** A generation paired with the index of the best matching message for display */export interface SentimentCard {@@ -154,8 +151,11 @@ export interface aiObservabilitySentimentLogicValues {groupsTaxonomicTypes: TaxonomicFilterGroupType[] // groupsModelhasLoadedSentimentEvaluations: boolean // sentimentEvaluationAvailabilityLogichasSentimentEvaluations: boolean // sentimentEvaluationAvailabilityLogic+ sentimentEvaluations: EvaluationApi[] // sentimentEvaluationAvailabilityLogicsentimentEvaluationsLoading: boolean // sentimentEvaluationAvailabilityLogicactiveFilters: Set<SentimentCategory>+ evaluationId: string | null+ evaluationOptions: LemonSelectOption<string | null>[]expandedCardIds: Set<string>generations: SentimentGeneration[]generationsError: boolean@@ -165,7 +165,6 @@ export interface aiObservabilitySentimentLogicValues {hasMore: booleanintensityThreshold: numbersentimentCards: SentimentCard[]- sentimentFilter: SentimentFilterLabelsentimentSummary: Record<SentimentCategory, number>showSentimentEvaluationOnboarding: booleanstillAnalyzing: boolean@@ -177,7 +176,9 @@ export interface aiObservabilitySentimentLogicActions {activate: () => {value: true}- loadGenerations: () => any+ loadGenerations: ({ forceRefresh }?: { forceRefresh?: boolean }) => {+ forceRefresh?: boolean+ }loadGenerationsFailure: (error: string,errorObject?: any@@ -187,10 +188,14 @@ export interface aiObservabilitySentimentLogicActions {}loadGenerationsSuccess: (generations: SentimentGeneration[],- payload?: any+ payload?: {+ forceRefresh?: boolean+ }) => {generations: SentimentGeneration[]- payload?: any+ payload?: {+ forceRefresh?: boolean+ }}loadMoreGenerations: () => {value: true@@ -213,15 +218,15 @@ export interface aiObservabilitySentimentLogicActions {value: true}}+ setEvaluationId: (evaluationId: string | null) => {+ evaluationId: string | null+ }setHasMore: (hasMore: boolean) => {hasMore: boolean}setIntensityThreshold: (intensityThreshold: number) => {intensityThreshold: number}- setSentimentFilter: (sentimentFilter: SentimentFilterLabel) => {- sentimentFilter: SentimentFilterLabel- }toggleCardExpanded: (cardKey: string) => {cardKey: string}@@ -237,6 +242,7 @@ export interface aiObservabilitySentimentLogicActions {export interface aiObservabilitySentimentLogicMeta {__keaTypeGenInternalSelectorTypes: {taxonomicGroupTypes: (groupsTaxonomicTypes: TaxonomicFilterGroupType[]) => TaxonomicFilterGroupType[]+ evaluationOptions: (sentimentEvaluations: EvaluationApi[]) => LemonSelectOption<string | null>[]sentimentCards: (generations: SentimentGeneration[],activeFilters: Set<SentimentCategory>,@@ -277,15 +283,19 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTygroupsModel,['groupsTaxonomicTypes'],sentimentEvaluationAvailabilityLogic,- ['hasLoadedSentimentEvaluations', 'hasSentimentEvaluations', 'sentimentEvaluationsLoading'],+ [+ 'hasLoadedSentimentEvaluations',+ 'hasSentimentEvaluations',+ 'sentimentEvaluations',+ 'sentimentEvaluationsLoading',+ ],],})),actions({activate: true,- /** @deprecated Use toggleSentimentCategory instead */- setSentimentFilter: (sentimentFilter: SentimentFilterLabel) => ({ sentimentFilter }),toggleSentimentCategory: (category: SentimentCategory) => ({ category }),+ setEvaluationId: (evaluationId: string | null) => ({ evaluationId }),setIntensityThreshold: (intensityThreshold: number) => ({ intensityThreshold }),toggleCardExpanded: (cardKey: string) => ({ cardKey }),loadMoreGenerations: true,@@ -294,14 +304,8 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTy}),reducers({- sentimentFilter: [- 'both' as SentimentFilterLabel,- {- setSentimentFilter: (_, { sentimentFilter }) => sentimentFilter,- },- ],activeFilters: [- new Set<SentimentCategory>(['positive', 'negative']) as Set<SentimentCategory>,+ new Set<SentimentCategory>(['negative']) as Set<SentimentCategory>,{toggleSentimentCategory: (state, { category }) => {const next = new Set(state)@@ -323,6 +327,12 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTysetIntensityThreshold: (_, { intensityThreshold }) => intensityThreshold,},],+ evaluationId: [+ null as string | null,+ {+ setEvaluationId: (_, { evaluationId }) => evaluationId,+ },+ ],expandedCardIds: [new Set<string>(),{@@ -365,8 +375,11 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTygenerations: [[] as SentimentGeneration[],{- loadGenerations: async () => {- const page = await fetchSentimentGenerationsPage(values, 0)+ loadGenerations: async ({ forceRefresh }: { forceRefresh?: boolean } = {}, breakpoint) => {+ const page = await fetchSentimentGenerationsPage(values, 0, forceRefresh)+ // The query is slow enough that toggling filters twice can leave two requests in+ // flight — drop this one if a newer load started while it was running+ breakpoint()lastPageHasMore = page.hasMorenextGenerationsOffset = page.rawCountreturn page.generations@@ -395,6 +408,16 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTyTaxonomicFilterGroupType.HogQLExpression,],],+ evaluationOptions: [+ (s) => [s.sentimentEvaluations],+ (sentimentEvaluations: EvaluationApi[]): LemonSelectOption<string | null>[] => [+ { value: null, label: 'All evaluations' },+ ...sentimentEvaluations.map((evaluation) => ({+ value: evaluation.id,+ label: evaluation.name,+ })),+ ],+ ],sentimentCards: [(s) => [s.generations, s.activeFilters, s.intensityThreshold],(@@ -416,9 +439,7 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTyif (!activeFilters.has(msg.label as SentimentCategory)) {continue}- // For neutral messages, skip the intensity threshold — neutral scores are- // inherently lower and the threshold is designed for positive/negative signals- if (msg.label !== 'neutral' && msg.score < intensityThreshold) {+ if (msg.score < intensityThreshold) {continue}const prev = best[msg.label]@@ -438,7 +459,7 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTysentimentSummary: [(s) => [s.generations, s.intensityThreshold],(generations: SentimentGeneration[], intensityThreshold: number): Record<SentimentCategory, number> => {- const counts: Record<SentimentCategory, number> = { positive: 0, negative: 0, neutral: 0 }+ const counts: Record<SentimentCategory, number> = { negative: 0, positive: 0 }for (const gen of generations) {const sentimentData = gen.sentimentif (!sentimentData?.messages) {@@ -451,7 +472,7 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTyif (!(label in counts)) {continue}- if (label !== 'neutral' && msg.score < intensityThreshold) {+ if (msg.score < intensityThreshold) {continue}const prev = best[label]@@ -589,6 +610,16 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTyactions.loadGenerations()}},+ activeFilters: () => {+ if (values.hasLoadedOnce) {+ actions.loadGenerations()+ }+ },+ evaluationId: () => {+ if (values.hasLoadedOnce) {+ actions.loadGenerations()+ }+ },stillAnalyzing: (stillAnalyzing: boolean) => {if (wasAnalyzing && !stillAnalyzing && values.activeTab === 'sentiment') {const totalGenerations = values.generations.length