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.

feat(llma): improve sentiment eval ui (#65267)

Radu Raicea7dbb84862a94
diff --git a/posthog/temporal/ai_observability/sentiment/tests/test_extraction.py b/posthog/temporal/ai_observability/sentiment/tests/test_extraction.py
index 13aa847ba311..2e6d9e653fca 100644
--- a/posthog/temporal/ai_observability/sentiment/tests/test_extraction.py
+++ b/posthog/temporal/ai_observability/sentiment/tests/test_extraction.py
@@ -143,22 +143,21 @@ class TestTruncateToTokenLimit:
class TestTruncateToHeadTail:
- def test_keeps_short_text_unchanged(self):
- assert truncate_to_head_tail("short", max_chars=100, head_chars=30) == "short"
-
- def test_keeps_head_and_tail_within_max_chars(self):
- text = ("h" * 400) + ("m" * 400) + ("t" * 800)
- result = truncate_to_head_tail(text, max_chars=1000, head_chars=300)
- tail_chars = 1000 - len(HEAD_TAIL_SEPARATOR) - 300
-
- assert len(result) == 1000
- assert result.startswith("h" * 300)
- assert HEAD_TAIL_SEPARATOR in result
- assert result.endswith("t" * tail_chars)
-
- def test_falls_back_to_tail_when_head_chars_is_zero(self):
- text = "abcdefgh"
- assert truncate_to_head_tail(text, max_chars=5, head_chars=0) == "defgh"
+ @parameterized.expand(
+ [
+ ("short_text", "short", 100, 30, "short"),
+ (
+ "keeps_head_and_tail",
+ ("h" * 400) + ("m" * 400) + ("t" * 800),
+ 1000,
+ 300,
+ ("h" * 300) + HEAD_TAIL_SEPARATOR + ("t" * (1000 - len(HEAD_TAIL_SEPARATOR) - 300)),
+ ),
+ ("head_chars_zero_uses_tail", "abcdefgh", 5, 0, "defgh"),
+ ]
+ )
+ def test_truncation(self, _name: str, text: str, max_chars: int, head_chars: int, expected: str):
+ assert truncate_to_head_tail(text, max_chars=max_chars, head_chars=head_chars) == expected
class TestExtractSentimentEvalMessages:
diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
index 2ac5804a04ba..13d40996a0d3 100644
--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
@@ -16,6 +16,7 @@ import {
IconDownload,
IconMessage,
IconPlay,
+ IconPlus,
IconReceipt,
IconSearch,
IconShare,
@@ -67,6 +68,7 @@ import { ClustersTabContent } from './components/ClustersTabContent'
import { CostBreakdownTooltip } from './components/CostBreakdownTooltip'
import { EvalResultBadges } from './components/EvalResultBadges'
import { EvalsTabContent } from './components/EvalsTabContent'
+import { isSentimentRun } from './components/EvaluationResultTag'
import { EventContentConversation } from './components/EventContentWithAsyncData'
import { FeedbackTag } from './components/FeedbackTag'
import { JSONValueDisplay } from './components/JSONValueDisplay'
@@ -81,6 +83,7 @@ import { MetadataHeader } from './ConversationDisplay/MetadataHeader'
import { ParametersHeader } from './ConversationDisplay/ParametersHeader'
import { SaveToDatasetButton } from './datasets/SaveToDatasetButton'
import { FeedbackViewDisplay } from './feedback-view/FeedbackViewDisplay'
+import { generationEvaluationRunsLogic } from './generationEvaluationRunsLogic'
import { useAIData } from './hooks/useAIData'
import { llmGenerationSentimentLazyLoaderLogic } from './llmGenerationSentimentLazyLoaderLogic'
import { LLMInputOutput } from './LLMInputOutput'
@@ -606,6 +609,34 @@ function UsageChip({ event }: { event: LLMTraceEvent | LLMTrace }): JSX.Element
) : null
}
+function CreateSentimentEvaluationButton({ traceId }: { traceId: string }): JSX.Element | null {
+ const { generationEvaluationRuns, generationEvaluationRunsLoading } = useValues(
+ generationEvaluationRunsLogic({ lookupBy: 'trace', traceId })
+ )
+ const hasSentimentEvaluationRun = generationEvaluationRuns.some(isSentimentRun)
+
+ if (generationEvaluationRunsLoading || hasSentimentEvaluationRun) {
+ return null
+ }
+
+ const createSentimentEvaluationUrl = combineUrl(urls.aiObservabilityEvaluation('new'), {
+ type: 'sentiment',
+ }).url
+
+ return (
+ <LemonButton
+ type="primary"
+ status="alt"
+ size="xsmall"
+ icon={<IconPlus />}
+ to={createSentimentEvaluationUrl}
+ data-attr="llma-create-sentiment-evaluation-from-trace"
+ >
+ Create sentiment eval
+ </LemonButton>
+ )
+}
+
function CostChip({
costContext,
billedTotalUsd,
@@ -1461,6 +1492,8 @@ const EventContent = React.memo(
const showPromptButton = !!promptName
const showPlaygroundButton = isGenerationEvent
+ const showCreateSentimentEvalButton =
+ isGenerationEvent && !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_SENTIMENT]
const showSaveToDatasetButton = featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_DATASETS]
@@ -1582,6 +1615,7 @@ const EventContent = React.memo(
)}
{(showPromptButton ||
showPlaygroundButton ||
+ showCreateSentimentEvalButton ||
hasSessionRecording ||
showSaveToDatasetButton) && (
<div className="flex flex-row items-center gap-2">
@@ -1616,6 +1650,9 @@ const EventContent = React.memo(
Open in Playground
</LemonButton>
)}
+ {showCreateSentimentEvalButton && (
+ <CreateSentimentEvaluationButton traceId={trace.id} />
+ )}
{showSaveToDatasetButton && (
<SaveToDatasetButton
traceId={trace.id}
diff --git a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx
index 2a0f7ba21496..4b00a0c084f3 100644
--- a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx
@@ -29,7 +29,7 @@ describe('EvaluationDisplay', () => {
</Provider>
)
- expect(screen.getByText('Positive (91%)')).toBeInTheDocument()
+ expect(screen.getByText('Positive')).toBeInTheDocument()
expect(screen.queryByText('False')).not.toBeInTheDocument()
})
diff --git a/products/ai_observability/frontend/components/EvalResultBadges.test.tsx b/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
index a2078dedff45..1f4e003b2789 100644
--- a/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
+++ b/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
@@ -1,5 +1,6 @@
import { EvaluationRun } from '../evaluations/types'
import { getEvalBadgeProps, getEvalSummaries } from './EvalResultBadges'
+import { isSentimentRun } from './EvaluationResultTag'
function makeRun(overrides: Partial<EvaluationRun> = {}): EvaluationRun {
return {
@@ -16,102 +17,118 @@ function makeRun(overrides: Partial<EvaluationRun> = {}): EvaluationRun {
}
}
-describe('getEvalSummaries', () => {
- it('returns empty array for empty input', () => {
- expect(getEvalSummaries([])).toEqual([])
- })
+describe('EvalResultBadges', () => {
+ describe('getEvalSummaries', () => {
+ it('returns empty array for empty input', () => {
+ expect(getEvalSummaries([])).toEqual([])
+ })
- it('groups runs by evaluation_id and counts them', () => {
- const runs = [
- makeRun({ id: 'r1', evaluation_id: 'eval-a', timestamp: '2026-04-10T12:00:00Z' }),
- makeRun({ id: 'r2', evaluation_id: 'eval-a', timestamp: '2026-04-09T12:00:00Z' }),
- makeRun({ id: 'r3', evaluation_id: 'eval-b', timestamp: '2026-04-10T12:00:00Z' }),
- ]
- const summaries = getEvalSummaries(runs)
- expect(summaries).toHaveLength(2)
+ it('groups runs by evaluation_id and counts them', () => {
+ const runs = [
+ makeRun({ id: 'r1', evaluation_id: 'eval-a', timestamp: '2026-04-10T12:00:00Z' }),
+ makeRun({ id: 'r2', evaluation_id: 'eval-a', timestamp: '2026-04-09T12:00:00Z' }),
+ makeRun({ id: 'r3', evaluation_id: 'eval-b', timestamp: '2026-04-10T12:00:00Z' }),
+ ]
+ const summaries = getEvalSummaries(runs)
+ expect(summaries).toHaveLength(2)
- const evalA = summaries.find((s) => s.latestRun.evaluation_id === 'eval-a')!
- expect(evalA.runCount).toBe(2)
- expect(evalA.latestRun.id).toBe('r1')
+ const evalA = summaries.find((s) => s.latestRun.evaluation_id === 'eval-a')!
+ expect(evalA.runCount).toBe(2)
+ expect(evalA.latestRun.id).toBe('r1')
- const evalB = summaries.find((s) => s.latestRun.evaluation_id === 'eval-b')!
- expect(evalB.runCount).toBe(1)
- })
+ const evalB = summaries.find((s) => s.latestRun.evaluation_id === 'eval-b')!
+ expect(evalB.runCount).toBe(1)
+ })
- it('picks the latest run regardless of input order', () => {
- const older = makeRun({ id: 'old', evaluation_id: 'eval-a', timestamp: '2026-04-01T00:00:00Z' })
- const newer = makeRun({ id: 'new', evaluation_id: 'eval-a', timestamp: '2026-04-10T00:00:00Z' })
+ it('picks the latest run regardless of input order', () => {
+ const older = makeRun({ id: 'old', evaluation_id: 'eval-a', timestamp: '2026-04-01T00:00:00Z' })
+ const newer = makeRun({ id: 'new', evaluation_id: 'eval-a', timestamp: '2026-04-10T00:00:00Z' })
- const ascResult = getEvalSummaries([older, newer])
- expect(ascResult[0].latestRun.id).toBe('new')
+ const ascResult = getEvalSummaries([older, newer])
+ expect(ascResult[0].latestRun.id).toBe('new')
- const descResult = getEvalSummaries([newer, older])
- expect(descResult[0].latestRun.id).toBe('new')
- })
+ const descResult = getEvalSummaries([newer, older])
+ expect(descResult[0].latestRun.id).toBe('new')
+ })
- it('handles a single run', () => {
- const summaries = getEvalSummaries([makeRun()])
- expect(summaries).toHaveLength(1)
- expect(summaries[0].runCount).toBe(1)
+ it('handles a single run', () => {
+ const summaries = getEvalSummaries([makeRun()])
+ expect(summaries).toHaveLength(1)
+ expect(summaries[0].runCount).toBe(1)
+ })
})
-})
-describe('getEvalBadgeProps', () => {
- it.each([
- ['failed status', makeRun({ status: 'failed' }), { type: 'danger', label: 'Error' }],
- ['running status', makeRun({ status: 'running' }), { type: 'primary', label: 'Running' }],
- ['null result', makeRun({ result: null }), { type: 'muted', label: 'N/A' }],
- ['true result', makeRun({ result: true }), { type: 'success', label: 'True' }],
- ['false result', makeRun({ result: false }), { type: 'danger', label: 'False' }],
- [
- 'positive sentiment',
- makeRun({
- evaluation_type: 'sentiment',
- result: null,
- sentiment_label: 'positive',
- sentiment_score: 0.91,
- }),
- { type: 'success', label: 'Positive (91%)' },
- ],
- [
- 'neutral sentiment',
- makeRun({
- evaluation_type: 'sentiment',
- result: null,
- sentiment_label: 'neutral',
- sentiment_score: 0.67,
- }),
- { type: 'none', label: 'Neutral (67%)' },
- ],
- [
- 'negative sentiment',
- makeRun({
- evaluation_type: 'sentiment',
- result: null,
- sentiment_label: 'negative',
- sentiment_score: 0.82,
- }),
- { type: 'danger', label: 'Negative (82%)' },
- ],
- [
- 'unknown sentiment',
- makeRun({ evaluation_type: 'sentiment', result: null, sentiment_label: null, sentiment_score: null }),
- { type: 'muted', label: 'Unknown' },
- ],
- ])('%s', (_name, run, expected) => {
- const props = getEvalBadgeProps(run)
- expect(props.type).toBe(expected.type)
- expect(props.label).toBe(expected.label)
- expect(props.icon).toBeTruthy()
- })
+ describe('getEvalBadgeProps', () => {
+ it.each([
+ ['failed status', makeRun({ status: 'failed' }), { type: 'danger', label: 'Error' }],
+ ['running status', makeRun({ status: 'running' }), { type: 'primary', label: 'Running' }],
+ ['null result', makeRun({ result: null }), { type: 'muted', label: 'N/A' }],
+ ['true result', makeRun({ result: true }), { type: 'success', label: 'True' }],
+ ['false result', makeRun({ result: false }), { type: 'danger', label: 'False' }],
+ [
+ 'positive sentiment',
+ makeRun({
+ evaluation_type: 'sentiment',
+ result: null,
+ sentiment_label: 'positive',
+ sentiment_score: 0.91,
+ }),
+ { type: 'success', label: 'Positive' },
+ ],
+ [
+ 'neutral sentiment',
+ makeRun({
+ evaluation_type: 'sentiment',
+ result: null,
+ sentiment_label: 'neutral',
+ sentiment_score: 0.67,
+ }),
+ { type: 'none', label: 'Neutral' },
+ ],
+ [
+ 'negative sentiment',
+ makeRun({
+ evaluation_type: 'sentiment',
+ result: null,
+ sentiment_label: 'negative',
+ sentiment_score: 0.82,
+ }),
+ { type: 'danger', label: 'Negative' },
+ ],
+ [
+ 'unknown sentiment',
+ makeRun({ evaluation_type: 'sentiment', result: null, sentiment_label: null, sentiment_score: null }),
+ { type: 'muted', label: 'Unknown' },
+ ],
+ ])('%s', (_name, run, expected) => {
+ const props = getEvalBadgeProps(run)
+ expect(props.type).toBe(expected.type)
+ expect(props.label).toBe(expected.label)
+ expect(props.icon).toBeTruthy()
+ })
+
+ it('prioritizes failed status over result value', () => {
+ const props = getEvalBadgeProps(makeRun({ status: 'failed', result: true }))
+ expect(props.label).toBe('Error')
+ })
- it('prioritizes failed status over result value', () => {
- const props = getEvalBadgeProps(makeRun({ status: 'failed', result: true }))
- expect(props.label).toBe('Error')
+ it('prioritizes running status over result value', () => {
+ const props = getEvalBadgeProps(makeRun({ status: 'running', result: true }))
+ expect(props.label).toBe('Running')
+ })
})
- it('prioritizes running status over result value', () => {
- const props = getEvalBadgeProps(makeRun({ status: 'running', result: true }))
- expect(props.label).toBe('Running')
+ describe('isSentimentRun', () => {
+ it.each([
+ ['evaluation type', makeRun({ evaluation_type: 'sentiment' })],
+ ['result type', makeRun({ result_type: 'sentiment' })],
+ ['sentiment label', makeRun({ sentiment_label: 'negative' })],
+ ])('detects sentiment by %s', (_label, run) => {
+ expect(isSentimentRun(run)).toBe(true)
+ })
+
+ it('returns false for boolean evaluation runs', () => {
+ expect(isSentimentRun(makeRun())).toBe(false)
+ })
})
})
diff --git a/products/ai_observability/frontend/components/EvalResultBadges.tsx b/products/ai_observability/frontend/components/EvalResultBadges.tsx
index 7e3e9462f717..8ecba12330e4 100644
--- a/products/ai_observability/frontend/components/EvalResultBadges.tsx
+++ b/products/ai_observability/frontend/components/EvalResultBadges.tsx
@@ -53,7 +53,7 @@ function EvalTooltipContent({ latestRun, runCount }: EvalSummary): JSX.Element {
export function EvalResultBadges({ generationEventId }: { generationEventId: string }): JSX.Element | null {
const { generationEvaluationRuns, generationEvaluationRunsLoading } = useValues(
- generationEvaluationRunsLogic({ generationEventId })
+ generationEvaluationRunsLogic({ lookupBy: 'generation', generationEventId })
)
const traceLogic = useMountedLogic(aiObservabilityTraceLogic)
const { setViewMode } = useActions(traceLogic)
diff --git a/products/ai_observability/frontend/components/EvalsTabContent.tsx b/products/ai_observability/frontend/components/EvalsTabContent.tsx
index 469992ccd4e9..be3758789996 100644
--- a/products/ai_observability/frontend/components/EvalsTabContent.tsx
+++ b/products/ai_observability/frontend/components/EvalsTabContent.tsx
@@ -25,7 +25,7 @@ export function EvalsTabContent({
event: string
distinctId?: string
}): JSX.Element {
- const generationRunsLogic = generationEvaluationRunsLogic({ generationEventId })
+ const generationRunsLogic = generationEvaluationRunsLogic({ lookupBy: 'generation', generationEventId })
const traceLogic = useMountedLogic(aiObservabilityTraceLogic)
useAttachedLogic(generationRunsLogic, traceLogic)
diff --git a/products/ai_observability/frontend/components/EvaluationResultTag.tsx b/products/ai_observability/frontend/components/EvaluationResultTag.tsx
index 79320fdd8fd6..6b2aa3f78291 100644
--- a/products/ai_observability/frontend/components/EvaluationResultTag.tsx
+++ b/products/ai_observability/frontend/components/EvaluationResultTag.tsx
@@ -3,11 +3,11 @@ import { LemonTag } from '@posthog/lemon-ui'
import type { LemonTagProps } from '@posthog/lemon-ui'
import type { EvaluationRun } from '../evaluations/types'
-import { capitalize, formatScore } from '../sentimentUtils'
+import { capitalize } from '../sentimentUtils'
type EvaluationResultLike = Pick<
EvaluationRun,
- 'status' | 'result' | 'result_type' | 'evaluation_type' | 'sentiment_label' | 'sentiment_score'
+ 'status' | 'result' | 'result_type' | 'evaluation_type' | 'sentiment_label'
>
interface EvaluationResultDisplay {
@@ -23,7 +23,7 @@ const SENTIMENT_DISPLAY: Record<string, Pick<EvaluationResultDisplay, 'type' | '
negative: { type: 'danger', icon: <IconX />, sortValue: 1 },
}
-function isSentimentRun(run: EvaluationResultLike): boolean {
+export function isSentimentRun(run: EvaluationResultLike): boolean {
return run.result_type === 'sentiment' || run.evaluation_type === 'sentiment' || !!run.sentiment_label
}
@@ -41,10 +41,9 @@ export function getEvaluationResultDisplay(run: EvaluationResultLike): Evaluatio
icon: <IconMinus />,
sortValue: 0,
}
- const score = run.sentiment_score
return {
...display,
- label: `${capitalize(sentimentLabel)}${score !== null && score !== undefined ? ` (${formatScore(score)})` : ''}`,
+ label: capitalize(sentimentLabel),
}
}
if (run.result === null) {
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
index bb62da6158d4..1cd9087f90e2 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
@@ -444,7 +444,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
)}
<p className="text-muted text-sm -mt-2">
{isSentiment ? (
- 'Classify the sentiment of user messages on each matching generation.'
+ 'Classify the sentiment of only the last user message on each matching generation event with a sentiment classifier, not LLM calls.'
) : isHog ? (
<>
Run deterministic{' '}
@@ -645,5 +645,6 @@ export const scene: SceneExport<LLMEvaluationLogicProps> = {
paramsToProps: ({ params: { id }, searchParams }) => ({
evaluationId: id && id !== 'new' ? id : 'new',
templateKey: typeof searchParams.template === 'string' ? searchParams.template : undefined,
+ evaluationType: searchParams.type === 'sentiment' ? 'sentiment' : undefined,
}),
}
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
index d26990722b6c..5aa26bfe6274 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
import { IconRefresh } from '@posthog/icons'
-import { LemonButton, LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+import { LemonButton, LemonSegmentedButton, LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
@@ -12,15 +12,40 @@ import { EvaluationResultTag, getEvaluationResultSortValue } from '../../compone
import { sanitizeTraceUrlSearchParams } from '../../utils'
import { evaluationSupportsReports } from '../evaluationCapabilities'
import { llmEvaluationLogic } from '../llmEvaluationLogic'
-import { EvaluationRun } from '../types'
+import { EvaluationRun, SentimentEvaluationRunsFilter } from '../types'
import { EvaluationSummaryControls, EvaluationSummaryPanel } from './EvaluationSummaryPanel'
+const SENTIMENT_FILTER_OPTIONS: { value: SentimentEvaluationRunsFilter; label: string }[] = [
+ { value: 'negative', label: 'Negative' },
+ { value: 'positive', label: 'Positive' },
+ { value: 'neutral', label: 'Neutral' },
+ { value: 'all', label: 'All' },
+]
+
+function SentimentEvaluationRunsFilters(): JSX.Element {
+ const { evaluationSummaryFilter } = useValues(llmEvaluationLogic)
+ const { setEvaluationSummaryFilter } = useActions(llmEvaluationLogic)
+
+ return (
+ <LemonSegmentedButton
+ value={evaluationSummaryFilter as SentimentEvaluationRunsFilter}
+ onChange={(value) => {
+ setEvaluationSummaryFilter(value as SentimentEvaluationRunsFilter, evaluationSummaryFilter)
+ }}
+ options={SENTIMENT_FILTER_OPTIONS}
+ size="small"
+ data-attr="llma-sentiment-evaluation-runs-filter"
+ />
+ )
+}
+
export function EvaluationRunsTable(): JSX.Element {
const { filteredEvaluationRuns, evaluation, evaluationRunsLoading, runsLookup } = useValues(llmEvaluationLogic)
const { searchParams } = useValues(router)
const traceSearchParams = sanitizeTraceUrlSearchParams(searchParams, { removeSearch: true })
const { refreshEvaluationRuns } = useActions(llmEvaluationLogic)
const showSummary = evaluationSupportsReports(evaluation)
+ const showSentimentFilters = evaluation?.evaluation_type === 'sentiment'
const columns: LemonTableColumns<EvaluationRun> = [
{
@@ -90,7 +115,13 @@ export function EvaluationRunsTable(): JSX.Element {
return (
<div className="space-y-4">
<div className="flex justify-between items-center">
- {showSummary ? <EvaluationSummaryControls /> : <div />}
+ {showSummary ? (
+ <EvaluationSummaryControls />
+ ) : showSentimentFilters ? (
+ <SentimentEvaluationRunsFilters />
+ ) : (
+ <div />
+ )}
<LemonButton
type="secondary"
icon={<IconRefresh />}
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationSummaryPanel.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationSummaryPanel.tsx
index 6ed4ad17f849..43f3cfdb10c4 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationSummaryPanel.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationSummaryPanel.tsx
@@ -9,13 +9,24 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { llmEvaluationLogic } from '../llmEvaluationLogic'
-import { EvaluationPattern, EvaluationRun, EvaluationSummary, EvaluationSummaryFilter } from '../types'
+import {
+ EvaluationPattern,
+ EvaluationRun,
+ EvaluationSummary,
+ EvaluationSummaryFilter,
+ SentimentEvaluationRunsFilter,
+} from '../types'
import { PatternCard } from './PatternCard'
+type ReportPatternFilter = Exclude<EvaluationSummaryFilter, 'all' | SentimentEvaluationRunsFilter>
+
const FILTER_LABELS: Record<Exclude<EvaluationSummaryFilter, 'all'>, string> = {
pass: 'passing ',
fail: 'failing ',
na: 'N/A ',
+ negative: 'negative ',
+ positive: 'positive ',
+ neutral: 'neutral ',
}
function getFilterLabel(filter: EvaluationSummaryFilter): string {
@@ -293,7 +304,7 @@ function PatternList({
}
const FILTER_CONFIG: Record<
- Exclude<EvaluationSummaryFilter, 'all'>,
+ ReportPatternFilter,
{
patternsKey: 'pass_patterns' | 'fail_patterns' | 'na_patterns'
icon: JSX.Element
@@ -325,6 +336,10 @@ const FILTER_CONFIG: Record<
},
}
+function isReportPatternFilter(filter: EvaluationSummaryFilter): filter is ReportPatternFilter {
+ return filter === 'pass' || filter === 'fail' || filter === 'na'
+}
+
function FilteredPatternSection({
filter,
evaluationSummary,
@@ -334,7 +349,7 @@ function FilteredPatternSection({
evaluationSummary: EvaluationSummary
runsLookup: Record<string, EvaluationRun>
}): JSX.Element | null {
- if (filter === 'all') {
+ if (filter === 'all' || !isReportPatternFilter(filter)) {
return null
}
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationTriggers.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationTriggers.tsx
index ff56f7ca4e5e..5eb20e9f0287 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationTriggers.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationTriggers.tsx
@@ -21,7 +21,7 @@ export function EvaluationTriggers(): JSX.Element {
const addConditionSet = (): void => {
const newCondition: EvaluationConditionSet = {
id: `cond-${Date.now()}`,
- rollout_percentage: 0,
+ rollout_percentage: 100,
properties: [],
}
setTriggerConditions([...evaluation.conditions, newCondition])
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index 7d619625e0dc..2a81341600fc 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -124,6 +124,78 @@ const mockRuns: EvaluationRun[] = [
},
]
+const mockSentimentEvaluation: EvaluationConfig = {
+ ...mockEvaluation,
+ evaluation_type: 'sentiment',
+ evaluation_config: { source: 'user_messages' },
+ output_type: 'sentiment',
+ output_config: {},
+ model_configuration: null,
+}
+
+const mockSentimentRuns: EvaluationRun[] = [
+ {
+ id: 'run-negative',
+ evaluation_id: 'eval-123',
+ evaluation_name: 'Sentiment Evaluation',
+ generation_id: 'gen-negative',
+ trace_id: 'trace-negative',
+ timestamp: '2024-01-01T12:00:00Z',
+ evaluation_type: 'sentiment',
+ result_type: 'sentiment',
+ result: null,
+ sentiment_label: 'negative',
+ sentiment_score: -0.8,
+ reasoning: 'The message was frustrated',
+ status: 'completed',
+ },
+ {
+ id: 'run-positive',
+ evaluation_id: 'eval-123',
+ evaluation_name: 'Sentiment Evaluation',
+ generation_id: 'gen-positive',
+ trace_id: 'trace-positive',
+ timestamp: '2024-01-01T13:00:00Z',
+ evaluation_type: 'sentiment',
+ result_type: 'sentiment',
+ result: null,
+ sentiment_label: 'positive',
+ sentiment_score: 0.7,
+ reasoning: 'The message was happy',
+ status: 'completed',
+ },
+ {
+ id: 'run-neutral',
+ evaluation_id: 'eval-123',
+ evaluation_name: 'Sentiment Evaluation',
+ generation_id: 'gen-neutral',
+ trace_id: 'trace-neutral',
+ timestamp: '2024-01-01T14:00:00Z',
+ evaluation_type: 'sentiment',
+ result_type: 'sentiment',
+ result: null,
+ sentiment_label: 'neutral',
+ sentiment_score: 0.1,
+ reasoning: 'The message was neutral',
+ status: 'completed',
+ },
+ {
+ id: 'run-positive-failed',
+ evaluation_id: 'eval-123',
+ evaluation_name: 'Sentiment Evaluation',
+ generation_id: 'gen-positive-failed',
+ trace_id: 'trace-positive-failed',
+ timestamp: '2024-01-01T15:00:00Z',
+ evaluation_type: 'sentiment',
+ result_type: 'sentiment',
+ result: null,
+ sentiment_label: 'positive',
+ sentiment_score: 0.5,
+ reasoning: 'This run did not complete',
+ status: 'failed',
+ },
+]
+
describe('llmEvaluationLogic', () => {
let logic: ReturnType<typeof llmEvaluationLogic.build>
let keysLogic: ReturnType<typeof llmProviderKeysLogic.build>
@@ -211,6 +283,16 @@ describe('llmEvaluationLogic', () => {
})
})
+ it('initializes new evaluations with 100% sampling', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+
+ await expectLogic(logic).toMatchValues({
+ evaluation: expect.objectContaining({
+ conditions: [expect.objectContaining({ rollout_percentage: 100 })],
+ }),
+ })
+ })
+
it('setModelConfiguration updates model config', async () => {
await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
@@ -264,6 +346,7 @@ describe('llmEvaluationLogic', () => {
await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
logic.actions.setEvaluationName('Valid Name')
logic.actions.setEvaluationPrompt('Valid prompt')
+ logic.actions.setTriggerConditions([{ id: 'c1', rollout_percentage: 0, properties: [] }])
await expectLogic(logic).toMatchValues({ formValid: false })
})
@@ -438,7 +521,10 @@ describe('llmEvaluationLogic', () => {
logic.actions.resetEvaluation()
await expectLogic(logic).toMatchValues({
- evaluation: expect.objectContaining({ name: '' }),
+ evaluation: expect.objectContaining({
+ name: '',
+ conditions: [expect.objectContaining({ rollout_percentage: 100 })],
+ }),
hasUnsavedChanges: false,
})
})
@@ -502,6 +588,20 @@ describe('llmEvaluationLogic', () => {
})
})
+ describe('sentiment evaluation filters', () => {
+ it('defaults to all for boolean evaluations', async () => {
+ expect(logic.values.evaluationSummaryFilter).toBe('all')
+ })
+
+ it('defaults to negative for sentiment evaluations', async () => {
+ logic.actions.loadEvaluationSuccess(mockSentimentEvaluation)
+
+ await expectLogic(logic).toMatchValues({
+ evaluationSummaryFilter: 'negative',
+ })
+ })
+ })
+
describe('runsToSummarizeCount', () => {
it('returns 0 when no runs', async () => {
expect(logic.values.runsToSummarizeCount).toBe(0)
@@ -653,6 +753,35 @@ describe('llmEvaluationLogic', () => {
filteredEvaluationRuns: [expect.objectContaining({ id: 'run-1' })],
})
})
+
+ it('returns only negative sentiment runs by default for sentiment evaluations', async () => {
+ logic.actions.loadEvaluationSuccess(mockSentimentEvaluation)
+ logic.actions.loadEvaluationRunsSuccess(mockSentimentRuns)
+
+ await expectLogic(logic).toMatchValues({
+ filteredEvaluationRuns: [expect.objectContaining({ id: 'run-negative' })],
+ })
+ })
+
+ it('returns only completed sentiment runs matching the selected filter', async () => {
+ logic.actions.loadEvaluationSuccess(mockSentimentEvaluation)
+ logic.actions.loadEvaluationRunsSuccess(mockSentimentRuns)
+ logic.actions.setEvaluationSummaryFilter('positive', 'negative')
+
+ await expectLogic(logic).toMatchValues({
+ filteredEvaluationRuns: [expect.objectContaining({ id: 'run-positive' })],
+ })
+ })
+
+ it('returns all sentiment runs when the all filter is selected', async () => {
+ logic.actions.loadEvaluationSuccess(mockSentimentEvaluation)
+ logic.actions.loadEvaluationRunsSuccess(mockSentimentRuns)
+ logic.actions.setEvaluationSummaryFilter('all', 'negative')
+
+ await expectLogic(logic).toMatchValues({
+ filteredEvaluationRuns: mockSentimentRuns,
+ })
+ })
})
describe('runsLookup', () => {
@@ -709,6 +838,25 @@ describe('llmEvaluationLogic', () => {
logic.actions.setEvaluationType('sentiment')
+ await expectLogic(logic).toMatchValues({
+ evaluation: expect.objectContaining({
+ evaluation_type: 'sentiment',
+ evaluation_config: { source: 'user_messages' },
+ output_type: 'sentiment',
+ output_config: {},
+ model_configuration: null,
+ conditions: [expect.objectContaining({ rollout_percentage: 100 })],
+ }),
+ })
+ })
+
+ it('initializes new evaluations as sentiment when requested', async () => {
+ logic.unmount()
+ logic = llmEvaluationLogic({ evaluationId: 'new', evaluationType: 'sentiment' })
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+
await expectLogic(logic).toMatchValues({
evaluation: expect.objectContaining({
evaluation_type: 'sentiment',
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index 9b6660135380..7f71d5cb339a 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -51,6 +51,8 @@ if (not result) {
return result`
const DEFAULT_SENTIMENT_SOURCE = 'user_messages' as const
+const DEFAULT_SENTIMENT_RUNS_FILTER = 'negative' as const
+const DEFAULT_CONDITION_ROLLOUT_PERCENTAGE = 100
function toLLMJudgeEvaluation(evaluation: EvaluationConfig): LLMJudgeEvaluation {
return {
@@ -84,15 +86,40 @@ function toSentimentEvaluation(evaluation: EvaluationConfig): SentimentEvaluatio
}
}
+function filterEvaluationRuns(runs: EvaluationRun[], filter: EvaluationSummaryFilter): EvaluationRun[] {
+ if (filter === 'all') {
+ return runs
+ }
+
+ const completedRuns = runs.filter((r) => r.status === 'completed')
+ if (filter === 'pass') {
+ return completedRuns.filter((r) => r.result === true)
+ }
+ if (filter === 'fail') {
+ return completedRuns.filter((r) => r.result === false)
+ }
+ if (filter === 'na') {
+ return completedRuns.filter((r) => r.result === null)
+ }
+
+ return completedRuns.filter((r) => r.sentiment_label?.toLowerCase() === filter)
+}
+
export interface LLMEvaluationLogicProps {
evaluationId: string
templateKey?: EvaluationTemplateKey
+ evaluationType?: EvaluationType
}
export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
path(['products', 'ai_observability', 'evaluations', 'llmEvaluationLogic']),
props({} as LLMEvaluationLogicProps),
- key((props) => `${props.evaluationId || 'new'}${props.templateKey ? `-${props.templateKey}` : ''}`),
+ key(
+ (props) =>
+ `${props.evaluationId || 'new'}${props.templateKey ? `-${props.templateKey}` : ''}${
+ props.evaluationType ? `-${props.evaluationType}` : ''
+ }`
+ ),
connect(() => ({
values: [
@@ -379,6 +406,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
'all' as EvaluationSummaryFilter,
{
setEvaluationSummaryFilter: (_, { filter }) => filter,
+ loadEvaluationSuccess: (_, { evaluation }) =>
+ evaluation?.evaluation_type === 'sentiment' ? DEFAULT_SENTIMENT_RUNS_FILTER : 'all',
},
],
// Clear summary when filter changes so stale summary doesn't mismatch current filter
@@ -446,7 +475,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
conditions: [
{
id: `cond-${Date.now()}`,
- rollout_percentage: 0,
+ rollout_percentage: DEFAULT_CONDITION_ROLLOUT_PERCENTAGE,
properties: [],
},
],
@@ -456,19 +485,27 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
updated_at: new Date().toISOString(),
}
const newEvaluation: EvaluationConfig =
- template?.evaluation_type === 'hog'
+ props.evaluationType === 'sentiment'
? {
...baseFields,
- evaluation_type: 'hog' as const,
- evaluation_config: { source: template.source, bytecode: [] },
- }
- : {
- ...baseFields,
- evaluation_type: 'llm_judge' as const,
- evaluation_config: {
- prompt: template && 'prompt' in template ? template.prompt : '',
- },
+ evaluation_type: 'sentiment' as const,
+ evaluation_config: { source: DEFAULT_SENTIMENT_SOURCE },
+ output_type: 'sentiment' as const,
+ output_config: {},
}
+ : template?.evaluation_type === 'hog'
+ ? {
+ ...baseFields,
+ evaluation_type: 'hog' as const,
+ evaluation_config: { source: template.source, bytecode: [] },
+ }
+ : {
+ ...baseFields,
+ evaluation_type: 'llm_judge' as const,
+ evaluation_config: {
+ prompt: template && 'prompt' in template ? template.prompt : '',
+ },
+ }
actions.loadEvaluationSuccess(newEvaluation)
}
},
@@ -536,7 +573,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
conditions: [
{
id: `cond-${Date.now()}`,
- rollout_percentage: 0,
+ rollout_percentage: DEFAULT_CONDITION_ROLLOUT_PERCENTAGE,
properties: [],
},
],
@@ -769,21 +806,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
filteredEvaluationRuns: [
(s) => [s.evaluationRuns, s.evaluationSummaryFilter],
- (runs: EvaluationRun[], filter: EvaluationSummaryFilter): EvaluationRun[] => {
- if (filter === 'all') {
- return runs
- }
- // Only consider completed runs for filtering
- const completedRuns = runs.filter((r) => r.status === 'completed')
- if (filter === 'pass') {
- return completedRuns.filter((r) => r.result === true)
- }
- if (filter === 'fail') {
- return completedRuns.filter((r) => r.result === false)
- }
- // na
- return completedRuns.filter((r) => r.result === null)
- },
+ (runs: EvaluationRun[], filter: EvaluationSummaryFilter): EvaluationRun[] =>
+ filterEvaluationRuns(runs, filter),
],
runsToSummarizeCount: [
diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.ts
index 84a7e28cefaf..df25bb1b3883 100644
--- a/products/ai_observability/frontend/evaluations/types.ts
+++ b/products/ai_observability/frontend/evaluations/types.ts
@@ -191,7 +191,8 @@ export interface EvaluationReportRun {
created_at: string
}
-export type EvaluationSummaryFilter = 'all' | 'pass' | 'fail' | 'na'
+export type SentimentEvaluationRunsFilter = 'negative' | 'positive' | 'neutral' | 'all'
+export type EvaluationSummaryFilter = 'pass' | 'fail' | 'na' | SentimentEvaluationRunsFilter
export interface EvaluationPattern {
title: string
diff --git a/products/ai_observability/frontend/generationEvaluationRunsLogic.ts b/products/ai_observability/frontend/generationEvaluationRunsLogic.ts
index e0aaddd4d589..877f15e026e2 100644
--- a/products/ai_observability/frontend/generationEvaluationRunsLogic.ts
+++ b/products/ai_observability/frontend/generationEvaluationRunsLogic.ts
@@ -5,14 +5,24 @@ import { EvaluationRun } from './evaluations/types'
import type { generationEvaluationRunsLogicType } from './generationEvaluationRunsLogicType'
import { queryEvaluationRuns } from './utils'
-export interface GenerationEvaluationRunsLogicProps {
+export interface GenerationEvaluationRunsByGenerationProps {
+ lookupBy: 'generation'
generationEventId: string
}
+export interface GenerationEvaluationRunsByTraceProps {
+ lookupBy: 'trace'
+ traceId: string
+}
+
+export type GenerationEvaluationRunsLogicProps =
+ | GenerationEvaluationRunsByGenerationProps
+ | GenerationEvaluationRunsByTraceProps
+
export const generationEvaluationRunsLogic = kea<generationEvaluationRunsLogicType>([
path(['products', 'ai_observability', 'frontend', 'generationEvaluationRunsLogic']),
props({} as GenerationEvaluationRunsLogicProps),
- key((props) => props.generationEventId),
+ key((props) => (props.lookupBy === 'trace' ? `trace-${props.traceId}` : props.generationEventId)),
actions({
refreshGenerationEvaluationRuns: true,
@@ -26,7 +36,9 @@ export const generationEvaluationRunsLogic = kea<generationEvaluationRunsLogicTy
loadGenerationEvaluationRuns: async () => {
try {
return await queryEvaluationRuns({
- generationEventId: props.generationEventId,
+ ...(props.lookupBy === 'trace'
+ ? { traceId: props.traceId }
+ : { generationEventId: props.generationEventId }),
forceRefresh: values.isForceRefresh,
})
} catch (error) {
diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.ts
index b3ffad8f26aa..c21b442c2ea0 100644
--- a/products/ai_observability/frontend/utils.ts
+++ b/products/ai_observability/frontend/utils.ts
@@ -1137,16 +1137,18 @@ export function mapEvaluationRunRow(row: RawEvaluationRunRow): EvaluationRun {
export async function queryEvaluationRuns(params: {
evaluationId?: string
generationEventId?: string
+ traceId?: string
forceRefresh?: boolean
}): Promise<EvaluationRun[]> {
- const { evaluationId, generationEventId, forceRefresh } = params
+ const { evaluationId, generationEventId, traceId, forceRefresh } = params
- if (!evaluationId && !generationEventId) {
- throw new Error('Either evaluationId or generationEventId must be provided')
+ const propertyValue = evaluationId || generationEventId || traceId
+
+ if (!propertyValue) {
+ throw new Error('Either evaluationId, generationEventId, or traceId must be provided')
}
- const propertyName = evaluationId ? '$ai_evaluation_id' : '$ai_target_event_id'
- const propertyValue = evaluationId || generationEventId
+ const propertyName = evaluationId ? '$ai_evaluation_id' : generationEventId ? '$ai_target_event_id' : '$ai_trace_id'
const query = hogql`
SELECT