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): add sentiment evaluation type (#64136)

Radu Raicea8427e3ff7dce
diff --git a/ee/hogai/context/test/test_context.py b/ee/hogai/context/test/test_context.py
index 6d30333d77f1..2fed8af9e56b 100644
--- a/ee/hogai/context/test/test_context.py
+++ b/ee/hogai/context/test/test_context.py
@@ -14,7 +14,7 @@ from posthog.schema import (
ContextMessage,
DashboardFilter,
EntityType,
- EvaluationType,
+ EvaluationRuntime,
EventsNode,
FunnelsQuery,
HogQLQuery,
@@ -1010,7 +1010,7 @@ class TestAssistantContextManager(BaseTest):
id="eval-1",
name="Check output",
description="Validates output quality",
- evaluation_type=EvaluationType.HOG,
+ evaluation_type=EvaluationRuntime.HOG,
hog_source="return length(output) > 0",
),
[
@@ -1027,7 +1027,7 @@ class TestAssistantContextManager(BaseTest):
MaxEvaluationContext(
id="eval-2",
name="LLM Judge Eval",
- evaluation_type=EvaluationType.LLM_JUDGE,
+ evaluation_type=EvaluationRuntime.LLM_JUDGE,
),
[
"<evaluations_context>",
@@ -1039,7 +1039,7 @@ class TestAssistantContextManager(BaseTest):
"evaluation with no name falls back",
MaxEvaluationContext(
id="eval-3",
- evaluation_type=EvaluationType.HOG,
+ evaluation_type=EvaluationRuntime.HOG,
),
["<evaluations_context>", "Evaluation eval-3", "Type: hog"],
],
@@ -1048,7 +1048,7 @@ class TestAssistantContextManager(BaseTest):
MaxEvaluationContext(
id="eval-4",
name="STL test",
- evaluation_type=EvaluationType.HOG,
+ evaluation_type=EvaluationRuntime.HOG,
),
[
"Standard library — strings:",
@@ -1077,7 +1077,7 @@ class TestAssistantContextManager(BaseTest):
evaluation = MaxEvaluationContext(
id="eval-4",
name="No source eval",
- evaluation_type=EvaluationType.HOG,
+ evaluation_type=EvaluationRuntime.HOG,
)
ui_context = MaxUIContext(evaluations=[evaluation])
result = await self.context_manager._format_ui_context(ui_context)
diff --git a/frontend/jest.config.ts b/frontend/jest.config.ts
index 8ab249a2113d..a0506e154efc 100644
--- a/frontend/jest.config.ts
+++ b/frontend/jest.config.ts
@@ -193,9 +193,14 @@ const config: Config = {
'^common/(.*)$': '<rootDir>/../common/$1',
'^@posthog/replay-shared$': '<rootDir>/../common/replay-shared/src/index.ts',
'^@posthog/replay-shared/(.*)$': '<rootDir>/../common/replay-shared/src/$1',
+ '^@posthog/quill$': '<rootDir>/../packages/quill/packages/quill/src/index.ts',
+ '^@posthog/quill-blocks$': '<rootDir>/../packages/quill/packages/blocks/src/index.ts',
'^@posthog/quill-charts$': '<rootDir>/../packages/quill/packages/charts/src/index.ts',
'^@posthog/quill-charts/testing$': '<rootDir>/../packages/quill/packages/charts/src/testing/index.ts',
'^@posthog/quill-charts/story-helpers$': '<rootDir>/../packages/quill/packages/charts/src/story-helpers.tsx',
+ '^@posthog/quill-components$': '<rootDir>/../packages/quill/packages/components/src/index.ts',
+ '^@posthog/quill-primitives$': '<rootDir>/../packages/quill/packages/primitives/src/index.ts',
+ '^@posthog/quill-tokens$': '<rootDir>/../packages/quill/packages/tokens/src/index.ts',
'^@posthog/shared-onboarding/(.*)$': '<rootDir>/../docs/onboarding/$1',
d3: '<rootDir>/node_modules/d3/dist/d3.min.js',
'^d3-(.*)$': `d3-$1/dist/d3-$1`,
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 1f869a8fc954..35bc26fe47ff 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -338,6 +338,7 @@ export const FEATURE_FLAGS = {
LLM_ANALYTICS_EVALUATIONS_CUSTOM_MODELS: 'llm-analytics-evaluations-custom-models', // owner: #team-ai-observability
LLM_ANALYTICS_EVALUATIONS_HOG_CODE: 'llm-analytics-evaluations-hog-code', // owner: #team-ai-observability
LLM_ANALYTICS_EVALUATIONS_REPORTS: 'llm-analytics-evaluations-reports', // owner: #team-ai-observability
+ LLM_ANALYTICS_EVALUATIONS_SENTIMENT: 'llm-analytics-sentiment-evaluations', // owner: #team-ai-observability
LLM_ANALYTICS_EVALUATIONS_SUMMARY: 'llm-analytics-evaluations-summary', // owner: #team-ai-observability
LLM_ANALYTICS_OFFLINE_EVALS: 'llm-analytics-offline-evals', // owner: #team-ai-observability
LLM_ANALYTICS_SENTIMENT: 'llm-analytics-sentiment', // owner: #team-ai-observability
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 08d6121bf299..fa03805704cf 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -17920,6 +17920,10 @@
"required": ["results"],
"type": "object"
},
+ "EvaluationRuntime": {
+ "enum": ["hog", "llm_judge", "sentiment"],
+ "type": "string"
+ },
"EventDefinition": {
"additionalProperties": false,
"properties": {
@@ -28344,8 +28348,7 @@
"type": ["string", "null"]
},
"evaluation_type": {
- "enum": ["hog", "llm_judge"],
- "type": "string"
+ "$ref": "#/definitions/EvaluationRuntime"
},
"hog_source": {
"type": ["string", "null"]
diff --git a/frontend/src/scenes/max/maxContextLogic.ts b/frontend/src/scenes/max/maxContextLogic.ts
index 5407e80b4606..5fa3be331777 100644
--- a/frontend/src/scenes/max/maxContextLogic.ts
+++ b/frontend/src/scenes/max/maxContextLogic.ts
@@ -33,6 +33,7 @@ import {
MaxInsightContext,
MaxNotebookContext,
MaxUIContext,
+ EvaluationRuntime,
} from './maxTypes'
import {
actionToMaxContextPayload,
@@ -111,7 +112,7 @@ export const maxContextLogic = kea<maxContextLogicType>([
id: string
name?: string | null
description?: string | null
- evaluation_type: 'hog' | 'llm_judge'
+ evaluation_type: EvaluationRuntime
hog_source?: string | null
}) => ({ data }),
removeContextInsight: (id: string | number) => ({ id }),
@@ -227,7 +228,7 @@ export const maxContextLogic = kea<maxContextLogicType>([
id: string
name?: string | null
description?: string | null
- evaluation_type: 'hog' | 'llm_judge'
+ evaluation_type: EvaluationRuntime
hog_source?: string | null
}
}
diff --git a/frontend/src/scenes/max/maxTypes.ts b/frontend/src/scenes/max/maxTypes.ts
index cd4485c3bc05..525b0fc46882 100644
--- a/frontend/src/scenes/max/maxTypes.ts
+++ b/frontend/src/scenes/max/maxTypes.ts
@@ -60,12 +60,14 @@ export interface MaxErrorTrackingIssueContext {
name?: string | null
}
+export type EvaluationRuntime = 'hog' | 'llm_judge' | 'sentiment'
+
export interface MaxEvaluationContext {
type: MaxContextType.EVALUATION
id: string
name?: string | null
description?: string | null
- evaluation_type: 'hog' | 'llm_judge'
+ evaluation_type: EvaluationRuntime
hog_source?: string | null
}
@@ -142,7 +144,7 @@ type MaxEvaluationContextInput = {
id: string
name?: string | null
description?: string | null
- evaluation_type: 'hog' | 'llm_judge'
+ evaluation_type: EvaluationRuntime
hog_source?: string | null
}
}
@@ -224,7 +226,7 @@ export const createMaxContextHelpers = {
id: string
name?: string | null
description?: string | null
- evaluation_type: 'hog' | 'llm_judge'
+ evaluation_type: EvaluationRuntime
hog_source?: string | null
}): MaxEvaluationContextInput => ({
type: MaxContextType.EVALUATION,
diff --git a/frontend/src/scenes/max/utils.ts b/frontend/src/scenes/max/utils.ts
index 12fbcb9384c4..f7ee80cdf738 100644
--- a/frontend/src/scenes/max/utils.ts
+++ b/frontend/src/scenes/max/utils.ts
@@ -41,6 +41,7 @@ import { MODE_DEFINITIONS } from './max-constants'
import { EnhancedToolCall } from './max-constants'
import { SuggestionGroup } from './maxLogic'
import {
+ EvaluationRuntime,
InsightWithQuery,
MaxActionContext,
MaxContextType,
@@ -258,7 +259,7 @@ export const evaluationToMaxContextPayload = (evaluation: {
id: string
name?: string | null
description?: string | null
- evaluation_type: 'hog' | 'llm_judge'
+ evaluation_type: EvaluationRuntime
hog_source?: string | null
}): MaxEvaluationContext => ({
type: MaxContextType.EVALUATION,
@@ -283,7 +284,7 @@ export interface MaxOpenContext {
id: string
name?: string | null
description?: string | null
- evaluation_type: 'hog' | 'llm_judge'
+ evaluation_type: EvaluationRuntime
hog_source?: string | null
}
}
diff --git a/nodejs/src/ai-observability/services/temporal.service.test.ts b/nodejs/src/ai-observability/services/temporal.service.test.ts
index d43fc6029cae..4106802a9012 100644
--- a/nodejs/src/ai-observability/services/temporal.service.test.ts
+++ b/nodejs/src/ai-observability/services/temporal.service.test.ts
@@ -1,10 +1,10 @@
import { Client, Connection } from '@temporalio/client'
import { EncryptionCodec } from '~/common/temporal/codec'
-import { Hub, RawKafkaEvent } from '~/types'
-import { closeHub, createHub } from '~/utils/db/hub'
+import { RawKafkaEvent } from '~/types'
import { TemporalService } from './temporal.service'
+import type { EvaluationWorkflowRuntime, TemporalServiceConfig } from './temporal.service'
jest.mock('@temporalio/client')
@@ -24,17 +24,23 @@ const createMockEvent = (overrides: Partial<RawKafkaEvent> = {}): RawKafkaEvent
}
describe('TemporalService', () => {
- let hub: Hub
+ let config: TemporalServiceConfig
let service: TemporalService
let mockClient: jest.Mocked<Client>
let mockConnection: jest.Mocked<Connection>
let mockWorkflowHandle: any
- beforeEach(async () => {
- hub = await createHub()
- hub.TEMPORAL_HOST = 'localhost'
- hub.TEMPORAL_PORT = '7233'
- hub.TEMPORAL_NAMESPACE = 'test-namespace'
+ beforeEach(() => {
+ config = {
+ TEMPORAL_CLIENT_ROOT_CA: undefined,
+ TEMPORAL_CLIENT_CERT: undefined,
+ TEMPORAL_CLIENT_KEY: undefined,
+ TEMPORAL_PORT: '7233',
+ TEMPORAL_HOST: 'localhost',
+ TEMPORAL_NAMESPACE: 'test-namespace',
+ TEMPORAL_SECRET_KEY: undefined,
+ TEMPORAL_FALLBACK_SECRET_KEYS: '',
+ }
mockWorkflowHandle = {
workflowId: 'test-workflow-id',
@@ -53,17 +59,16 @@ describe('TemporalService', () => {
;(Connection.connect as jest.Mock) = jest.fn().mockResolvedValue(mockConnection)
;(Client as unknown as jest.Mock) = jest.fn().mockReturnValue(mockClient)
- service = new TemporalService(hub)
+ service = new TemporalService(config)
})
- afterEach(async () => {
- await closeHub(hub)
+ afterEach(() => {
jest.clearAllMocks()
})
describe('connection management', () => {
it('creates client with correct config', async () => {
- await service.startEvaluationRunWorkflow('test', createMockEvent({ uuid: 'test-uuid' }))
+ await service.startEvaluationRunWorkflow('test', createMockEvent({ uuid: 'test-uuid' }), 'llm_judge')
expect(Connection.connect).toHaveBeenCalledWith({
address: 'localhost:7233',
@@ -72,12 +77,12 @@ describe('TemporalService', () => {
})
it('handles TLS config when certificates provided', async () => {
- hub.TEMPORAL_CLIENT_ROOT_CA = 'root-ca-cert'
- hub.TEMPORAL_CLIENT_CERT = 'client-cert'
- hub.TEMPORAL_CLIENT_KEY = 'client-key'
+ config.TEMPORAL_CLIENT_ROOT_CA = 'root-ca-cert'
+ config.TEMPORAL_CLIENT_CERT = 'client-cert'
+ config.TEMPORAL_CLIENT_KEY = 'client-key'
- const newService = new TemporalService(hub)
- await newService.startEvaluationRunWorkflow('test', createMockEvent({ uuid: 'test-uuid' }))
+ const newService = new TemporalService(config)
+ await newService.startEvaluationRunWorkflow('test', createMockEvent({ uuid: 'test-uuid' }), 'llm_judge')
expect(Connection.connect).toHaveBeenCalledWith({
address: 'localhost:7233',
@@ -92,11 +97,11 @@ describe('TemporalService', () => {
})
it('configures an encryption codec when a secret key is set', async () => {
- hub.TEMPORAL_SECRET_KEY = 'test-secret-key-for-codec-000000'
- hub.TEMPORAL_FALLBACK_SECRET_KEYS = 'fallback-key-one-000000000000000,fallback-key-two-000000000000000'
+ config.TEMPORAL_SECRET_KEY = 'test-secret-key-for-codec-000000'
+ config.TEMPORAL_FALLBACK_SECRET_KEYS = 'fallback-key-one-000000000000000,fallback-key-two-000000000000000'
- const newService = new TemporalService(hub)
- await newService.startEvaluationRunWorkflow('test', createMockEvent({ uuid: 'test-uuid' }))
+ const newService = new TemporalService(config)
+ await newService.startEvaluationRunWorkflow('test', createMockEvent({ uuid: 'test-uuid' }), 'llm_judge')
const clientOptions = (Client as unknown as jest.Mock).mock.calls[0][0]
expect(clientOptions.dataConverter.payloadCodecs).toHaveLength(1)
@@ -104,17 +109,17 @@ describe('TemporalService', () => {
})
it('sends payloads unencrypted when no secret key is set', async () => {
- hub.TEMPORAL_SECRET_KEY = undefined
+ config.TEMPORAL_SECRET_KEY = undefined
- const newService = new TemporalService(hub)
- await newService.startEvaluationRunWorkflow('test', createMockEvent({ uuid: 'test-uuid' }))
+ const newService = new TemporalService(config)
+ await newService.startEvaluationRunWorkflow('test', createMockEvent({ uuid: 'test-uuid' }), 'llm_judge')
const clientOptions = (Client as unknown as jest.Mock).mock.calls[0][0]
expect(clientOptions.dataConverter).toBeUndefined()
})
it('disconnects client properly', async () => {
- await service.startEvaluationRunWorkflow('test', createMockEvent({ uuid: 'test-uuid' }))
+ await service.startEvaluationRunWorkflow('test', createMockEvent({ uuid: 'test-uuid' }), 'llm_judge')
await service.disconnect()
expect(mockConnection.close).toHaveBeenCalled()
@@ -125,7 +130,7 @@ describe('TemporalService', () => {
it('starts evaluation run workflow with correct parameters', async () => {
const mockEvent = createMockEvent({ properties: { $ai_input: 'test', $ai_output: 'response' } as any })
- await service.startEvaluationRunWorkflow('eval-123', mockEvent)
+ await service.startEvaluationRunWorkflow('eval-123', mockEvent, 'llm_judge')
expect(mockClient.workflow.start).toHaveBeenCalledWith('run-evaluation', {
taskQueue: 'llm-analytics-evals-task-queue',
@@ -142,11 +147,36 @@ describe('TemporalService', () => {
})
})
+ it('uses sentiment workflow prefix for sentiment evaluations', async () => {
+ const mockEvent = createMockEvent()
+
+ await service.startEvaluationRunWorkflow('eval-123', mockEvent, 'sentiment')
+
+ expect(mockClient.workflow.start).toHaveBeenCalledWith(
+ 'run-evaluation',
+ expect.objectContaining({
+ workflowId: 'llma-sentiment-eval-eval-123-event-456-ingestion',
+ })
+ )
+ })
+
+ it('throws when evaluation runtime has no workflow prefix', async () => {
+ await expect(
+ service.startEvaluationRunWorkflow(
+ 'eval-123',
+ createMockEvent(),
+ 'unknown' as EvaluationWorkflowRuntime
+ )
+ ).rejects.toThrow('Unsupported evaluation runtime: unknown')
+
+ expect(mockClient.workflow.start).not.toHaveBeenCalled()
+ })
+
it('generates deterministic workflow IDs', async () => {
const mockEvent = createMockEvent()
- await service.startEvaluationRunWorkflow('eval-123', mockEvent)
- await service.startEvaluationRunWorkflow('eval-123', mockEvent)
+ await service.startEvaluationRunWorkflow('eval-123', mockEvent, 'llm_judge')
+ await service.startEvaluationRunWorkflow('eval-123', mockEvent, 'llm_judge')
const calls = (mockClient.workflow.start as jest.Mock).mock.calls
const workflowId1 = calls[0][1].workflowId
@@ -160,8 +190,8 @@ describe('TemporalService', () => {
const mockEvent1 = createMockEvent({ uuid: 'event-1' })
const mockEvent2 = createMockEvent({ uuid: 'event-2' })
- await service.startEvaluationRunWorkflow('eval-123', mockEvent1)
- await service.startEvaluationRunWorkflow('eval-123', mockEvent2)
+ await service.startEvaluationRunWorkflow('eval-123', mockEvent1, 'llm_judge')
+ await service.startEvaluationRunWorkflow('eval-123', mockEvent2, 'llm_judge')
const calls = (mockClient.workflow.start as jest.Mock).mock.calls
const workflowId1 = calls[0][1].workflowId
@@ -173,18 +203,17 @@ describe('TemporalService', () => {
})
it('returns workflow handle on success', async () => {
- const handle = await service.startEvaluationRunWorkflow('eval-123', createMockEvent())
+ const handle = await service.startEvaluationRunWorkflow('eval-123', createMockEvent(), 'llm_judge')
- expect(handle).toBeDefined()
expect(handle).toBe(mockWorkflowHandle)
})
it('throws on workflow start failure', async () => {
;(mockClient.workflow.start as jest.Mock).mockRejectedValue(new Error('Temporal unavailable'))
- await expect(service.startEvaluationRunWorkflow('eval-123', createMockEvent())).rejects.toThrow(
- 'Temporal unavailable'
- )
+ await expect(
+ service.startEvaluationRunWorkflow('eval-123', createMockEvent(), 'llm_judge')
+ ).rejects.toThrow('Temporal unavailable')
})
it('starts tagger run workflow with correct parameters', async () => {
@@ -231,7 +260,7 @@ describe('TemporalService', () => {
})
it('tagger and evaluation share the same task queue', async () => {
- await service.startEvaluationRunWorkflow('eval-1', createMockEvent({ uuid: 'e1' }))
+ await service.startEvaluationRunWorkflow('eval-1', createMockEvent({ uuid: 'e1' }), 'llm_judge')
await service.startTaggerRunWorkflow('tagger-1', createMockEvent({ uuid: 'e2' }))
const calls = (mockClient.workflow.start as jest.Mock).mock.calls
diff --git a/nodejs/src/ai-observability/services/temporal.service.ts b/nodejs/src/ai-observability/services/temporal.service.ts
index 7ab69703af38..092601cdd1b4 100644
--- a/nodejs/src/ai-observability/services/temporal.service.ts
+++ b/nodejs/src/ai-observability/services/temporal.service.ts
@@ -23,6 +23,24 @@ export type TemporalServiceConfig = Pick<
const EVALUATION_TASK_QUEUE = isDevEnv() ? 'development-task-queue' : 'llm-analytics-evals-task-queue'
+const EVALUATION_WORKFLOW_PREFIXES = {
+ hog: 'llma-hog-eval',
+ llm_judge: 'llma-llm-eval',
+ sentiment: 'llma-sentiment-eval',
+} as const
+
+export type EvaluationWorkflowRuntime = keyof typeof EVALUATION_WORKFLOW_PREFIXES
+
+export function isEvaluationWorkflowRuntime(
+ evaluationRuntime: unknown
+): evaluationRuntime is EvaluationWorkflowRuntime {
+ return typeof evaluationRuntime === 'string' && Object.hasOwn(EVALUATION_WORKFLOW_PREFIXES, evaluationRuntime)
+}
+
+function getEvaluationWorkflowPrefix(evaluationRuntime: EvaluationWorkflowRuntime): string {
+ return EVALUATION_WORKFLOW_PREFIXES[evaluationRuntime]
+}
+
const temporalWorkflowsStarted = new Counter({
name: 'evaluation_run_workflows_started',
help: 'Number of evaluation run workflows started',
@@ -131,11 +149,14 @@ export class TemporalService {
async startEvaluationRunWorkflow(
evaluationId: string,
event: RawKafkaEvent,
- evaluationRuntime: string = 'llm_judge'
+ evaluationRuntime: EvaluationWorkflowRuntime
): Promise<WorkflowHandle> {
const client = await this.ensureConnected()
- const prefix = evaluationRuntime === 'hog' ? 'llma-hog-eval' : 'llma-llm-eval'
+ if (!isEvaluationWorkflowRuntime(evaluationRuntime)) {
+ throw new Error(`Unsupported evaluation runtime: ${evaluationRuntime}`)
+ }
+ const prefix = getEvaluationWorkflowPrefix(evaluationRuntime)
const workflowId = `${prefix}-${evaluationId}-${event.uuid}-ingestion`
const handle = await client.workflow.start('run-evaluation', {
diff --git a/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts b/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts
index c6d8fec6c438..0a0df9a5d118 100644
--- a/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts
+++ b/nodejs/src/evaluation-scheduler/evaluation-scheduler.test.ts
@@ -8,8 +8,6 @@ import {
} from '~/ai-observability/_tests/fixtures'
import { getDefaultAIObservabilityConfig } from '~/ai-observability/config'
import { parseTeamsList } from '~/ingestion/event-processing/split-ai-events-step'
-import { Hub } from '~/types'
-import { closeHub, createHub } from '~/utils/db/hub'
import { logger } from '~/utils/logger'
import {
@@ -23,21 +21,20 @@ import {
unwrapOrLog,
} from './evaluation-scheduler'
-jest.mock('~/ai-observability/services/temporal.service')
+jest.mock('~/ai-observability/services/temporal.service', () => {
+ const actual = jest.requireActual('~/ai-observability/services/temporal.service')
+ return {
+ ...actual,
+ TemporalService: jest.fn(),
+ }
+})
jest.mock('~/ai-observability/services/evaluation-manager.service')
jest.mock('~/cdp/utils/hog-exec')
describe('Evaluation Scheduler', () => {
- let hub: Hub
-
const teamId = 1
- beforeEach(async () => {
- hub = await createHub()
- })
-
- afterEach(async () => {
- await closeHub(hub)
+ afterEach(() => {
jest.clearAllMocks()
})
@@ -673,6 +670,38 @@ describe('Evaluation Scheduler', () => {
)
})
+ it('does not provider-key gate sentiment evaluations', async () => {
+ const event = createAiGenerationEvent(teamId)
+ const evaluation = createEvaluation({
+ team_id: teamId,
+ evaluation_type: 'sentiment',
+ evaluation_config: { source: 'user_messages' },
+ output_type: 'sentiment',
+ output_config: {},
+ provider_key_id: 'key-1',
+ conditions: [
+ createEvaluationCondition({ id: 'cond-1', bytecode: ['_H', 1, 32, true], rollout_percentage: 100 }),
+ ],
+ })
+ ;(evaluationManager.getEvaluationsForTeams as jest.Mock).mockResolvedValue({ [teamId]: [evaluation] })
+
+ await eachBatchEvaluationScheduler(
+ [messageFor(event)],
+ evaluationManager,
+ taggerManager,
+ temporalService,
+ { topic: 'events', aiTopicTeams: [] },
+ { enabled: true, providerKeyManager }
+ )
+
+ expect(providerKeyManager.getProviderKey).not.toHaveBeenCalled()
+ expect(temporalService.startEvaluationRunWorkflow).toHaveBeenCalledWith(
+ evaluation.id,
+ event,
+ evaluation.evaluation_type
+ )
+ })
+
it('does not start tagger workflows when the configured provider key is not ok', async () => {
const event = createAiGenerationEvent(teamId)
const tagger = createTagger({
diff --git a/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts b/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
index bcef5e498710..fa594c4a8fc1 100644
--- a/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
+++ b/nodejs/src/evaluation-scheduler/evaluation-scheduler.ts
@@ -28,7 +28,11 @@ import { AIObservabilityConfig } from '../ai-observability/config'
import { EvaluationManagerService } from '../ai-observability/services/evaluation-manager.service'
import { ProviderKeyManagerService } from '../ai-observability/services/provider-key-manager.service'
import { TaggerManagerService } from '../ai-observability/services/tagger-manager.service'
-import { TemporalService, TemporalServiceConfig } from '../ai-observability/services/temporal.service'
+import {
+ TemporalService,
+ TemporalServiceConfig,
+ isEvaluationWorkflowRuntime,
+} from '../ai-observability/services/temporal.service'
import { Evaluation, EvaluationConditionSet, Matchable, Tagger } from '../ai-observability/types'
import { execHog } from '../cdp/utils/hog-exec'
import { KAFKA_CLICKHOUSE_AI_EVENTS_JSON, KAFKA_EVENTS_JSON, prefix as KAFKA_PREFIX } from '../config/kafka-topics'
@@ -328,7 +332,7 @@ export const startEvaluationScheduler = async (
)
)
- const onShutdown = async () => {
+ const onShutdown = async (): Promise<void> => {
await temporalService.disconnect()
await kafkaConsumer.disconnect()
}
@@ -358,6 +362,13 @@ type ProviderKeyGateDefinition = {
tagger_type?: string
}
+const NON_PROVIDER_KEY_RUNTIMES = new Set(['hog', 'sentiment'])
+
+function definitionUsesProviderKey(definition: ProviderKeyGateDefinition): boolean {
+ const runtime = definition.evaluation_type ?? definition.tagger_type
+ return !runtime || !NON_PROVIDER_KEY_RUNTIMES.has(runtime)
+}
+
export async function eachBatchEvaluationScheduler(
messages: Message[],
evaluationManager: EvaluationManagerService,
@@ -499,11 +510,12 @@ async function processEventEvaluationMatch(
evaluationMatchesCounter.labels({ outcome: 'matched', type: 'evaluation' }).inc()
- await temporalService.startEvaluationRunWorkflow(
- evaluationDefinition.id,
- event,
- evaluationDefinition.evaluation_type as string
- )
+ const evaluationRuntime = evaluationDefinition.evaluation_type
+ if (!isEvaluationWorkflowRuntime(evaluationRuntime)) {
+ throw new Error(`Unsupported evaluation runtime: ${evaluationRuntime}`)
+ }
+
+ await temporalService.startEvaluationRunWorkflow(evaluationDefinition.id, event, evaluationRuntime)
evaluationSchedulerEventsProcessed.labels({ status: 'success', type: 'evaluation' }).inc()
}
@@ -550,7 +562,7 @@ async function getProviderKeySkipOutcome(
return null
}
- if (definition.evaluation_type === 'hog' || definition.tagger_type === 'hog') {
+ if (!definitionUsesProviderKey(definition)) {
return null
}
diff --git a/posthog/schema.py b/posthog/schema.py
index 0cff57fe93b1..83efa13dda03 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -91,7 +91,7 @@ from posthog.schema_enums import (
ErrorTrackingIssueAssigneeType as ErrorTrackingIssueAssigneeType,
ErrorTrackingIssueStatus as ErrorTrackingIssueStatus,
ErrorTrackingOrderBy as ErrorTrackingOrderBy,
- EvaluationType as EvaluationType,
+ EvaluationRuntime as EvaluationRuntime,
ExperimentMetricGoal as ExperimentMetricGoal,
ExperimentMetricMathType as ExperimentMetricMathType,
ExperimentMetricType as ExperimentMetricType,
@@ -1980,7 +1980,7 @@ class MaxEvaluationContext(BaseModel):
extra="forbid",
)
description: str | None = None
- evaluation_type: EvaluationType
+ evaluation_type: EvaluationRuntime
hog_source: str | None = None
id: str
name: str | None = None
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index d01762c21766..c4a165afd0e0 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -1038,6 +1038,12 @@ class SourceType(StrEnum):
ISSUE_SPIKING = "issue_spiking"
+class EvaluationRuntime(StrEnum):
+ HOG = "hog"
+ LLM_JUDGE = "llm_judge"
+ SENTIMENT = "sentiment"
+
+
class CorrelationType(StrEnum):
SUCCESS = "success"
FAILURE = "failure"
@@ -2318,11 +2324,6 @@ class MaxBillingContextSubscriptionLevel(StrEnum):
CUSTOM = "custom"
-class EvaluationType(StrEnum):
- HOG = "hog"
- LLM_JUDGE = "llm_judge"
-
-
class Goal(Enum):
INCREASE = "increase"
DECREASE = "decrease"
diff --git a/posthog/temporal/ai_observability/__init__.py b/posthog/temporal/ai_observability/__init__.py
index d90dd57b7715..bdbc5336c33e 100644
--- a/posthog/temporal/ai_observability/__init__.py
+++ b/posthog/temporal/ai_observability/__init__.py
@@ -28,20 +28,21 @@ from posthog.temporal.ai_observability.evaluation_clustering import (
perform_evaluation_clustering_compute_activity,
sample_and_embed_for_job_activity,
)
-from posthog.temporal.ai_observability.metrics import EvalsMetricsInterceptor # noqa: F401
-from posthog.temporal.ai_observability.run_evaluation import (
- RunEvaluationWorkflow,
+from posthog.temporal.ai_observability.evaluation_hog import execute_hog_eval_activity
+from posthog.temporal.ai_observability.evaluation_llm_judge import execute_llm_judge_activity
+from posthog.temporal.ai_observability.evaluation_sentiment import execute_sentiment_eval_activity
+from posthog.temporal.ai_observability.evaluation_workflow_activities import (
disable_evaluation_activity,
emit_evaluation_event_activity,
emit_internal_telemetry_activity,
- execute_hog_eval_activity,
- execute_llm_judge_activity,
fetch_evaluation_activity,
increment_trial_eval_count_activity,
send_evaluation_disabled_email_activity,
send_trial_usage_email_activity,
update_key_state_activity,
)
+from posthog.temporal.ai_observability.metrics import EvalsMetricsInterceptor # noqa: F401
+from posthog.temporal.ai_observability.run_evaluation import RunEvaluationWorkflow
from posthog.temporal.ai_observability.run_tagger import (
RunTaggerWorkflow,
disable_tagger_activity,
@@ -87,6 +88,7 @@ EVAL_ACTIVITIES = [
update_key_state_activity,
execute_llm_judge_activity,
execute_hog_eval_activity,
+ execute_sentiment_eval_activity,
emit_evaluation_event_activity,
emit_internal_telemetry_activity,
emit_eval_signal_activity, # kept for in-flight v1 workflows, then remove
@@ -175,6 +177,7 @@ ACTIVITIES = [
update_key_state_activity,
execute_llm_judge_activity,
execute_hog_eval_activity,
+ execute_sentiment_eval_activity,
emit_evaluation_event_activity,
emit_internal_telemetry_activity,
emit_eval_signal_activity, # kept for in-flight v1 workflows, then remove
diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.py
index fcb6bd31ef88..3179eda5b067 100644
--- a/posthog/temporal/ai_observability/eval_reports/activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/activities.py
@@ -45,6 +45,7 @@ async def fetch_due_eval_reports_activity(
next_delivery_date__lte=now_with_buffer,
enabled=True,
deleted=False,
+ evaluation__output_type="boolean",
)
.exclude(frequency=EvaluationReport.Frequency.EVERY_N)
.values_list("id", flat=True)
@@ -88,6 +89,7 @@ async def fetch_count_triggered_eval_reports_activity(
enabled=True,
deleted=False,
trigger_threshold__isnull=False,
+ evaluation__output_type="boolean",
).select_related("evaluation")
)
total_checked = len(reports)
diff --git a/posthog/temporal/ai_observability/evaluation_event_io.py b/posthog/temporal/ai_observability/evaluation_event_io.py
new file mode 100644
index 000000000000..a447fc7dfe6e
--- /dev/null
+++ b/posthog/temporal/ai_observability/evaluation_event_io.py
@@ -0,0 +1,47 @@
+from typing import Any
+
+
+def extract_event_io(event_type: str, properties: dict[str, Any]) -> tuple[Any, Any]:
+ """Extract raw input and output values from event properties.
+
+ Returns (input_raw, output_raw) for use in Hog eval globals and preview display.
+
+ Invariant: `properties` must already contain the heavy `$ai_*` keys when present
+ on the source event. Heavy props are stripped from `events.properties` after the
+ cutover (see AI events migration brief), so callers must source the event from a
+ path that re-populates them — today that's `EvaluationRunViewSet.create`, which
+ reads from `ai_events` and re-merges heavy columns via `merge_heavy_properties`
+ before handing `event_data` to this workflow. Adding a new caller? Use the same
+ pattern, or feed it `event_data` produced by an already-migrated reader.
+
+ Failure mode this invariant guards against: when `is_ai_events_enabled(team)` is
+ False (kill switch flipped) AND the team is post-strip, the events-fallback path
+ in `EvaluationRunViewSet.create` returns rows whose `properties` JSON has NULL
+ heavy keys. `extract_event_io` would then return empty `input_raw` / `output_raw`,
+ and the LLM judge / Hog eval would silently grade an empty conversation. The
+ invariant exists so any future caller short-circuiting around the migrated
+ reader has to confront this case explicitly.
+ """
+ if event_type == "$ai_generation":
+ input_raw = properties.get("$ai_input") or properties.get("$ai_input_state", "")
+ output_raw = (
+ properties.get("$ai_output_choices")
+ or properties.get("$ai_output")
+ or properties.get("$ai_output_state", "")
+ )
+ else:
+ input_raw = properties.get("$ai_input_state", "")
+ output_raw = properties.get("$ai_output_state", "")
+ return input_raw, output_raw
+
+
+def extract_event_tools(properties: dict[str, Any]) -> Any:
+ """Extract the tool catalog (`$ai_tools`) captured on the event, regardless
+ of event type.
+
+ `$ai_generation` is the canonical carrier today, but custom span/trace
+ events (e.g. an agent loop's `run_summary`) may also forward the catalog,
+ and the judge prompt benefits from it for any event shape. Presence of
+ `$ai_tools` drives whether the Tools section renders.
+ """
+ return properties.get("$ai_tools")
diff --git a/posthog/temporal/ai_observability/evaluation_hog.py b/posthog/temporal/ai_observability/evaluation_hog.py
new file mode 100644
index 000000000000..0391f3d1b072
--- /dev/null
+++ b/posthog/temporal/ai_observability/evaluation_hog.py
@@ -0,0 +1,120 @@
+import json
+from datetime import timedelta
+from typing import Any
+
+import structlog
+import temporalio
+from temporalio.exceptions import ApplicationError
+
+from posthog.sync import database_sync_to_async
+from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io
+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
+
+from common.hogvm.python.execute import execute_bytecode
+from common.hogvm.python.utils import HogVMException, HogVMMemoryExceededException, HogVMRuntimeExceededException
+
+logger = structlog.get_logger(__name__)
+
+
+def run_hog_eval(bytecode: list, event_data: dict[str, Any], allows_na: bool = False) -> dict[str, Any]:
+ """Run compiled Hog bytecode against a single event.
+
+ Used by both the Temporal activity and the test endpoint.
+ Returns {"verdict": bool | None, "reasoning": str, "error": str | None}.
+ When allows_na=True, a `return null` is treated as N/A (not an error).
+ """
+ properties = event_data["properties"]
+ if isinstance(properties, str):
+ properties = json.loads(properties)
+
+ event_type = event_data["event"]
+ input_raw, output_raw = extract_event_io(event_type, properties)
+
+ input_val = json.dumps(input_raw) if isinstance(input_raw, list | dict) else (input_raw or "")
+ output_val = json.dumps(output_raw) if isinstance(output_raw, list | dict) else (output_raw or "")
+
+ globals_dict: dict[str, Any] = {
+ "input": input_val,
+ "output": output_val,
+ "properties": properties,
+ "event": {
+ "uuid": event_data.get("uuid", ""),
+ "event": event_type,
+ "distinct_id": event_data.get("distinct_id", ""),
+ },
+ }
+
+ try:
+ response = execute_bytecode(
+ bytecode,
+ globals=globals_dict,
+ timeout=timedelta(seconds=5),
+ team=None,
+ )
+ except HogVMRuntimeExceededException:
+ return {"verdict": None, "reasoning": "", "error": "Execution timed out (5s limit exceeded)"}
+ except HogVMMemoryExceededException:
+ return {"verdict": None, "reasoning": "", "error": "Memory limit exceeded"}
+ except HogVMException as e:
+ return {"verdict": None, "reasoning": "", "error": f"Runtime error: {e}"}
+ except Exception:
+ logger.exception("Unexpected error executing Hog eval bytecode")
+ return {"verdict": None, "reasoning": "", "error": "Unexpected error during evaluation"}
+
+ reasoning = "\n".join(response.stdout) if response.stdout else ""
+
+ if response.result is None and allows_na:
+ return {"verdict": None, "applicable": False, "reasoning": reasoning, "error": None}
+
+ if not isinstance(response.result, bool):
+ hint = " (or null if N/A is enabled)" if allows_na else ""
+ return {
+ "verdict": None,
+ "reasoning": reasoning,
+ "error": f"Must return boolean{hint}, got {type(response.result).__name__}: {response.result}",
+ }
+
+ result: dict[str, Any] = {"verdict": response.result, "reasoning": reasoning, "error": None}
+ if allows_na:
+ result["applicable"] = True
+ return result
+
+
+async def execute_hog_eval_activity(evaluation: dict[str, Any], event_data: dict[str, Any]) -> EvaluationActivityResult:
+ """Execute Hog code to evaluate the target event."""
+ if evaluation["evaluation_type"] != "hog":
+ raise ApplicationError(
+ f"Unsupported evaluation type: {evaluation['evaluation_type']}",
+ non_retryable=True,
+ )
+
+ evaluation_config = evaluation.get("evaluation_config", {})
+ bytecode = evaluation_config.get("bytecode")
+ if not bytecode:
+ raise ApplicationError("Missing bytecode in evaluation_config", non_retryable=True)
+
+ output_config = evaluation.get("output_config", {})
+ allows_na = output_config.get("allows_na", False)
+
+ def _execute() -> dict[str, Any]:
+ return run_hog_eval(bytecode, event_data, allows_na=allows_na)
+
+ result = await database_sync_to_async(_execute, thread_sensitive=False)()
+
+ if result["error"]:
+ raise ApplicationError(
+ f"Hog evaluation error: {result['error']}",
+ non_retryable=True,
+ )
+
+ activity_result: EvaluationActivityResult = {
+ "result_type": "boolean",
+ "verdict": result["verdict"],
+ "reasoning": result["reasoning"],
+ "allows_na": allows_na,
+ }
+ if allows_na:
+ activity_result["applicable"] = result.get("applicable", True)
+
+ return activity_result
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
new file mode 100644
index 000000000000..7251a36e2b10
--- /dev/null
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -0,0 +1,428 @@
+import json
+from dataclasses import dataclass
+from datetime import timedelta
+from typing import Any
+
+from django.utils import timezone
+
+import structlog
+import temporalio
+import posthoganalytics
+from pydantic import BaseModel, model_validator
+from structlog.contextvars import bind_contextvars
+from temporalio.common import RetryPolicy
+from temporalio.exceptions import ApplicationError
+
+from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io, extract_event_tools
+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
+from posthog.temporal.ai_observability.message_utils import extract_text_from_messages, format_tool_definitions
+from posthog.temporal.ai_observability.metrics import (
+ increment_errors,
+ increment_key_type,
+ increment_provider_model,
+ increment_tokens,
+)
+
+from products.ai_observability.backend.llm import TRIAL_MODEL_IDS, Client, CompletionRequest
+from products.ai_observability.backend.llm.config import get_eval_config
+from products.ai_observability.backend.llm.errors import (
+ AuthenticationError,
+ ModelNotFoundError,
+ ModelPermissionError,
+ QuotaExceededError,
+ RateLimitError,
+ StructuredOutputParseError,
+)
+from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
+from products.ai_observability.backend.models.provider_keys import LLMProviderKey
+
+logger = structlog.get_logger(__name__)
+
+DEFAULT_JUDGE_MODEL = "gpt-5-mini"
+
+LLM_JUDGE_RETRY_POLICY = RetryPolicy(
+ maximum_attempts=3,
+ initial_interval=timedelta(seconds=10),
+ maximum_interval=timedelta(seconds=60),
+ backoff_coefficient=2.0,
+)
+
+
+class BooleanEvalResult(BaseModel):
+ """Structured output for boolean evaluation results"""
+
+ reasoning: str
+ verdict: bool
+
+
+class BooleanWithNAEvalResult(BaseModel):
+ """Structured output for boolean with N/A evaluation results.
+
+ When the evaluation criteria doesn't apply to the input/output,
+ applicable should be False and verdict should be None.
+ """
+
+ reasoning: str
+ applicable: bool
+ verdict: bool | None = None
+
+ @model_validator(mode="after")
+ def validate_verdict_consistency(self) -> "BooleanWithNAEvalResult":
+ if self.applicable and self.verdict is None:
+ raise ValueError("verdict is required when applicable is true")
+ if not self.applicable and self.verdict is not None:
+ raise ValueError("verdict must be null when applicable is false")
+ return self
+
+
+@dataclass
+class OutputTypeConfig:
+ """Configuration for each evaluation output type"""
+
+ response_format: type[BooleanEvalResult] | type[BooleanWithNAEvalResult]
+ instructions: str
+
+
+def get_output_type_config(allows_na: bool) -> OutputTypeConfig:
+ """Get the output type configuration based on whether N/A is allowed."""
+ if allows_na:
+ return OutputTypeConfig(
+ response_format=BooleanWithNAEvalResult,
+ instructions="""First, determine if this evaluation criteria is applicable to the given input/output. If the criteria doesn't apply to this case mark it as not applicable.
+
+Note: If the criteria above instructs you to return "N/A", "not applicable", or similar, treat that as applicable=false with verdict=null.
+
+Return:
+- applicable: true if the criteria applies to this input/output, false if it doesn't apply
+- verdict: true if it passes, false if it fails, or null if not applicable
+- reasoning: a brief explanation (1 sentence)""",
+ )
+ return OutputTypeConfig(
+ response_format=BooleanEvalResult,
+ instructions="Provide a brief reasoning (1 sentence) and a boolean verdict (true/false).",
+ )
+
+
+def build_system_prompt(prompt: str, allows_na: bool) -> str:
+ """Build the system prompt for the LLM judge."""
+ config = get_output_type_config(allows_na)
+ return f"""You are an evaluator. Evaluate the following generation according to this criteria:
+
+{prompt}
+
+{config.instructions}"""
+
+
+@dataclass
+class ExecuteLLMJudgeInputs:
+ evaluation: dict[str, Any]
+ event_data: dict[str, Any]
+
+ @property
+ def properties_to_log(self) -> dict[str, Any]:
+ return {
+ "team_id": self.evaluation.get("team_id"),
+ "evaluation_id": self.evaluation.get("id"),
+ }
+
+
+def _is_errored_trace(properties: dict[str, Any]) -> bool:
+ """Return True when the captured trace recorded an error.
+
+ `$ai_is_error` may be ingested as a Python bool or a JSON-encoded string depending on the
+ SDK and capture path, so we normalise both forms here.
+ """
+ raw = properties.get("$ai_is_error")
+ if isinstance(raw, bool):
+ return raw
+ if isinstance(raw, str):
+ return raw.strip().lower() == "true"
+ return False
+
+
+def _build_errored_trace_result(allows_na: bool) -> EvaluationActivityResult:
+ """Result returned when the source trace errored — skips the LLM call entirely.
+
+ `model` and `provider` are deliberately omitted so the `.get(..., DEFAULT_JUDGE_MODEL)`
+ defaults in downstream activities don't silently attribute phantom calls to a model that
+ was never invoked — the emit activity instead detects the `skipped` flag and drops cost
+ and model attribution entirely. The `EvaluationActivityResult` TypedDict expresses the shape
+ contract previously enforced by convention.
+ """
+ reasoning = "Source trace errored before producing output; evaluation skipped."
+ result: EvaluationActivityResult = {
+ "result_type": "boolean",
+ "verdict": None if allows_na else False,
+ "reasoning": reasoning,
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "total_tokens": 0,
+ "is_byok": False,
+ "key_id": None,
+ "allows_na": allows_na,
+ "skipped": True,
+ "skip_reason": "trace_errored",
+ }
+ if allows_na:
+ result["applicable"] = False
+ return result
+
+
+def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActivityResult:
+ """Execute LLM judge to evaluate the target event.
+
+ Fetches API key configuration internally to avoid passing sensitive data between activities.
+ """
+ return _execute_llm_judge_activity(inputs)
+
+
+def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActivityResult:
+ evaluation = inputs.evaluation
+ event_data = inputs.event_data
+
+ if evaluation["evaluation_type"] != "llm_judge":
+ raise ApplicationError(
+ f"Unsupported evaluation type: {evaluation['evaluation_type']}",
+ non_retryable=True,
+ )
+
+ evaluation_config = evaluation.get("evaluation_config", {})
+ prompt = evaluation_config.get("prompt")
+ if not prompt:
+ raise ApplicationError("Missing prompt in evaluation_config", non_retryable=True)
+
+ output_type = evaluation["output_type"]
+ if output_type != "boolean":
+ raise ApplicationError(
+ f"Unsupported output type: {output_type}. Supported types: 'boolean'.",
+ non_retryable=True,
+ )
+
+ output_config = evaluation.get("output_config", {})
+ allows_na = output_config.get("allows_na", False)
+
+ event_type = event_data["event"]
+ properties = event_data["properties"]
+ if isinstance(properties, str):
+ properties = json.loads(properties)
+
+ if _is_errored_trace(properties):
+ return _build_errored_trace_result(allows_na)
+
+ team_id = evaluation["team_id"]
+ model_configuration = evaluation.get("model_configuration")
+
+ def _get_legacy_provider_key() -> LLMProviderKey | None:
+ config, _ = EvaluationConfig.objects.get_or_create(team_id=team_id)
+
+ if config.active_provider_key:
+ key = config.active_provider_key
+ if key.state == LLMProviderKey.State.OK:
+ key.last_used_at = timezone.now()
+ key.save(update_fields=["last_used_at"])
+ return key
+ raise ApplicationError(
+ f"This API key has been disabled (status: {key.state}). Re-validate to recover, or replace it.",
+ {"error_type": "key_invalid", "key_id": str(key.id), "key_state": key.state},
+ non_retryable=True,
+ )
+
+ if config.trial_evals_used >= config.trial_eval_limit:
+ raise ApplicationError(
+ f"Trial evaluation limit ({config.trial_eval_limit}) reached. Add your own API key to continue.",
+ {"error_type": "trial_limit_reached", "trial_eval_limit": config.trial_eval_limit},
+ non_retryable=True,
+ )
+
+ return None
+
+ def _get_provider_key_by_id(key_id: str) -> LLMProviderKey:
+ try:
+ key = LLMProviderKey.objects.get(id=key_id, team_id=team_id)
+ if key.state != LLMProviderKey.State.OK:
+ raise ApplicationError(
+ f"This API key has been disabled (status: {key.state}). Re-validate to recover, or replace it.",
+ {"error_type": "key_invalid", "key_id": str(key.id), "key_state": key.state},
+ non_retryable=True,
+ )
+ key.last_used_at = timezone.now()
+ key.save(update_fields=["last_used_at"])
+ return key
+ except LLMProviderKey.DoesNotExist:
+ raise ApplicationError(
+ "Provider key not found.",
+ {"error_type": "key_not_found", "key_id": key_id},
+ non_retryable=True,
+ )
+
+ def _check_trial_quota() -> None:
+ config, _ = EvaluationConfig.objects.get_or_create(team_id=team_id)
+ if config.trial_evals_used >= config.trial_eval_limit:
+ raise ApplicationError(
+ f"Trial evaluation limit ({config.trial_eval_limit}) reached. Add your own API key to continue.",
+ {"error_type": "trial_limit_reached", "trial_eval_limit": config.trial_eval_limit},
+ non_retryable=True,
+ )
+
+ if model_configuration:
+ provider = model_configuration["provider"]
+ model = model_configuration["model"]
+ provider_key_id = model_configuration.get("provider_key_id")
+
+ if provider_key_id:
+ provider_key = _get_provider_key_by_id(provider_key_id)
+ else:
+ if model not in TRIAL_MODEL_IDS:
+ raise ApplicationError(
+ f"Model '{model}' is not available on the trial plan. Please add your own API key to use this model.",
+ {"error_type": "model_not_allowed", "model": model},
+ non_retryable=True,
+ )
+ _check_trial_quota()
+ provider_key = None
+ else:
+ provider = "openai"
+ model = DEFAULT_JUDGE_MODEL
+ provider_key = _get_legacy_provider_key()
+
+ is_byok = provider_key is not None
+ key_id = str(provider_key.id) if provider_key else None
+
+ input_raw, output_raw = extract_event_io(event_type, properties)
+ tools_raw = extract_event_tools(properties)
+
+ input_data = extract_text_from_messages(input_raw)
+ output_data = extract_text_from_messages(output_raw)
+ tools_data = format_tool_definitions(tools_raw)
+
+ type_config = get_output_type_config(allows_na)
+ system_prompt = build_system_prompt(prompt, allows_na)
+ response_format = type_config.response_format
+
+ sections = [f"Input: {input_data}"]
+ if tools_data:
+ sections.append(f"Tools available:\n{tools_data}")
+ sections.append(f"Output: {output_data}")
+ user_prompt = "\n\n".join(sections)
+
+ config = get_eval_config(provider) if provider_key is None else None
+
+ client = Client(
+ provider_key=provider_key,
+ config=config,
+ capture_analytics=False,
+ )
+
+ try:
+ response = client.complete(
+ CompletionRequest(
+ model=model,
+ system=system_prompt,
+ messages=[{"role": "user", "content": user_prompt}],
+ provider=provider,
+ response_format=response_format,
+ )
+ )
+ except AuthenticationError:
+ increment_errors("auth_error", provider=provider)
+ if is_byok:
+ raise ApplicationError(
+ "API key is invalid or has been deleted.",
+ {"error_type": "auth_error", "key_id": key_id, "provider": provider},
+ non_retryable=True,
+ )
+ raise
+ except ModelPermissionError:
+ increment_errors("permission_error", provider=provider)
+ if is_byok:
+ raise ApplicationError(
+ "API key doesn't have access to this model.",
+ {"error_type": "permission_error", "key_id": key_id, "provider": provider},
+ non_retryable=True,
+ )
+ raise
+ except QuotaExceededError:
+ increment_errors("quota_error", provider=provider)
+ if is_byok:
+ raise ApplicationError(
+ "API key has exceeded its quota.",
+ {"error_type": "quota_error", "key_id": key_id, "provider": provider},
+ non_retryable=True,
+ )
+ raise
+ except RateLimitError:
+ increment_errors("rate_limit", provider=provider)
+ if is_byok:
+ raise ApplicationError(
+ "API key is being rate limited.",
+ {"error_type": "rate_limit", "key_id": key_id, "provider": provider},
+ non_retryable=True,
+ )
+ raise
+ except ModelNotFoundError:
+ increment_errors("model_not_found", provider=provider)
+ raise ApplicationError(
+ f"Model '{model}' not found.",
+ non_retryable=True,
+ )
+ except StructuredOutputParseError as e:
+ increment_errors("parse_error", provider=provider)
+ raise ApplicationError(
+ str(e),
+ {"error_type": "parse_error"},
+ non_retryable=True,
+ ) from e
+
+ except Exception as e:
+ logger.exception(
+ "Unhandled error from LLM client",
+ evaluation_id=evaluation["id"],
+ provider=provider,
+ model=model,
+ error_class=type(e).__name__,
+ )
+ increment_errors(type(e).__name__, provider=provider)
+ raise
+
+ result = response.parsed
+ if result is None:
+ logger.exception("LLM judge returned empty structured response", evaluation_id=evaluation["id"])
+ raise ValueError(f"LLM judge returned empty structured response for evaluation {evaluation['id']}")
+
+ assert isinstance(result, BooleanEvalResult | BooleanWithNAEvalResult)
+
+ usage = response.usage
+
+ if temporalio.activity.in_activity():
+ increment_key_type("byok" if is_byok else "posthog")
+ increment_provider_model(provider, model)
+ if usage:
+ increment_tokens("input", usage.input_tokens)
+ increment_tokens("output", usage.output_tokens)
+ increment_tokens("total", usage.total_tokens)
+ bind_contextvars(provider=provider, model=model)
+
+ result_dict: EvaluationActivityResult = {
+ "result_type": "boolean",
+ "verdict": result.verdict,
+ "reasoning": result.reasoning,
+ "input_tokens": usage.input_tokens if usage else 0,
+ "output_tokens": usage.output_tokens if usage else 0,
+ "total_tokens": usage.total_tokens if usage else 0,
+ "is_byok": is_byok,
+ "key_id": key_id,
+ "allows_na": allows_na,
+ "model": model,
+ "provider": provider,
+ }
+
+ if allows_na and isinstance(result, BooleanWithNAEvalResult):
+ result_dict["applicable"] = result.applicable
+ elif isinstance(result, BooleanEvalResult):
+ pass
+ else:
+ raise ValueError(f"Unexpected result type: {type(result)}")
+
+ return result_dict
diff --git a/posthog/temporal/ai_observability/evaluation_sentiment.py b/posthog/temporal/ai_observability/evaluation_sentiment.py
new file mode 100644
index 000000000000..f3a902fc36c7
--- /dev/null
+++ b/posthog/temporal/ai_observability/evaluation_sentiment.py
@@ -0,0 +1,109 @@
+import json
+import asyncio
+from typing import Any
+
+import temporalio
+from temporalio.exceptions import ApplicationError
+
+from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io
+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
+from posthog.temporal.ai_observability.sentiment.extraction import (
+ extract_user_messages_individually,
+ truncate_to_token_limit,
+)
+from posthog.temporal.ai_observability.sentiment.schema import PendingClassification, SentimentResult
+from posthog.temporal.ai_observability.sentiment.utils import build_generation_result
+
+
+def _neutral_sentiment_activity_result(reasoning: str) -> EvaluationActivityResult:
+ return {
+ "result_type": "sentiment",
+ "reasoning": reasoning,
+ "sentiment_label": "neutral",
+ "sentiment_score": 0.0,
+ "sentiment_scores": {"positive": 0.0, "neutral": 0.0, "negative": 0.0},
+ "sentiment_messages": {},
+ "sentiment_message_count": 0,
+ }
+
+
+def _build_sentiment_activity_result(
+ event_uuid: str,
+ trace_id: str,
+ user_messages: list[tuple[int, str]],
+ classification_results: list[SentimentResult],
+) -> EvaluationActivityResult:
+ if not user_messages:
+ return _neutral_sentiment_activity_result("No user messages found; sentiment defaults to neutral.")
+ if not classification_results:
+ return _neutral_sentiment_activity_result(
+ "No sentiment classifications produced; sentiment defaults to neutral."
+ )
+
+ pending = [
+ PendingClassification(
+ trace_id=trace_id,
+ gen_uuid=event_uuid,
+ msg_index=message_index,
+ text=text,
+ )
+ for message_index, text in user_messages
+ ]
+ generation_result = build_generation_result(event_uuid, pending, classification_results)
+ label = generation_result["label"]
+ message_count = generation_result["message_count"]
+
+ return {
+ "result_type": "sentiment",
+ "reasoning": f"Classified {message_count} user message{'s' if message_count != 1 else ''} as {label}.",
+ "sentiment_label": label,
+ "sentiment_score": generation_result["score"],
+ "sentiment_scores": generation_result["scores"],
+ "sentiment_messages": generation_result["messages"],
+ "sentiment_message_count": message_count,
+ }
+
+
+async def execute_sentiment_eval_activity(
+ evaluation: dict[str, Any], event_data: dict[str, Any]
+) -> EvaluationActivityResult:
+ """Classify sentiment for the target event's user messages."""
+ if evaluation["evaluation_type"] != "sentiment":
+ raise ApplicationError(
+ f"Unsupported evaluation type: {evaluation['evaluation_type']}",
+ non_retryable=True,
+ )
+
+ output_type = evaluation["output_type"]
+ if output_type != "sentiment":
+ raise ApplicationError(
+ f"Unsupported output type: {output_type}. Supported types: 'sentiment'.",
+ non_retryable=True,
+ )
+
+ evaluation_config = evaluation.get("evaluation_config", {})
+ source = evaluation_config.get("source", "user_messages")
+ if source != "user_messages":
+ raise ApplicationError(
+ f"Unsupported sentiment source: {source}. Supported sources: 'user_messages'.",
+ non_retryable=True,
+ )
+
+ properties = event_data["properties"]
+ if isinstance(properties, str):
+ properties = json.loads(properties)
+
+ input_raw, _output_raw = extract_event_io(event_data["event"], properties)
+ event_uuid = event_data["uuid"]
+ trace_id = properties.get("$ai_trace_id", event_uuid)
+ user_messages = extract_user_messages_individually(input_raw)
+ if not user_messages:
+ return _neutral_sentiment_activity_result("No user messages found; sentiment defaults to neutral.")
+
+ texts = [truncate_to_token_limit(text) for _message_index, text in user_messages]
+
+ from posthog.temporal.ai_observability.sentiment.model import classify # noqa: PLC0415 -- loads ONNX deps lazily
+
+ classification_results = await asyncio.to_thread(classify, texts)
+ return _build_sentiment_activity_result(event_uuid, trace_id, user_messages, classification_results)
diff --git a/posthog/temporal/ai_observability/evaluation_types.py b/posthog/temporal/ai_observability/evaluation_types.py
new file mode 100644
index 000000000000..88acd60bc4ed
--- /dev/null
+++ b/posthog/temporal/ai_observability/evaluation_types.py
@@ -0,0 +1,41 @@
+from typing import Any, Literal, NotRequired, Required, TypedDict
+
+
+class EvaluationActivityResult(TypedDict, total=False):
+ """Result produced by evaluation execution activities.
+
+ `total=False` is used as the default so individual fields opt in via `Required` /
+ `NotRequired`, making the contract honest about which keys every path actually sets:
+
+ - `result_type` and `reasoning` are set on every path and are `Required`.
+ - `verdict` and `allows_na` are set for boolean outputs only.
+ - `applicable` is set only when `allows_na=True`.
+ - `skipped` and `skip_reason` are set only on the skip path (e.g. errored source trace).
+ - `model`, `provider`, `key_id`, `is_byok`, and the `*_tokens` fields come from the LLM
+ judge success path. The skip path omits `model`/`provider` so downstream cost
+ attribution doesn't credit phantom calls, and `execute_hog_eval_activity` (whose
+ output also flows into `emit_evaluation_event_activity`) emits only `verdict`,
+ `reasoning`, `allows_na`, and optionally `applicable`.
+ - `sentiment_*` fields are set for sentiment evaluations and deliberately omit
+ `verdict` so report and pass/fail metrics do not treat sentiment as N/A.
+ """
+
+ result_type: Required[Literal["boolean", "sentiment"]]
+ reasoning: Required[str]
+ verdict: NotRequired[bool | None]
+ allows_na: NotRequired[bool]
+ input_tokens: NotRequired[int]
+ output_tokens: NotRequired[int]
+ total_tokens: NotRequired[int]
+ is_byok: NotRequired[bool]
+ key_id: NotRequired[str | None]
+ model: NotRequired[str]
+ provider: NotRequired[str]
+ applicable: NotRequired[bool]
+ skipped: NotRequired[bool]
+ skip_reason: NotRequired[str]
+ sentiment_label: NotRequired[str]
+ sentiment_score: NotRequired[float]
+ sentiment_scores: NotRequired[dict[str, float]]
+ sentiment_messages: NotRequired[dict[str, dict[str, Any]]]
+ sentiment_message_count: NotRequired[int]
diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.py
new file mode 100644
index 000000000000..26c94bde5d1b
--- /dev/null
+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py
@@ -0,0 +1,450 @@
+import json
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import Any
+
+from django.conf import settings
+from django.db import models
+
+import structlog
+import temporalio
+from structlog.contextvars import bind_contextvars
+
+from posthog.api.capture_dispatch import capture_internal_routed
+from posthog.models.team import Team
+from posthog.sync import database_sync_to_async
+from posthog.temporal.ai_observability.evaluation_llm_judge import DEFAULT_JUDGE_MODEL
+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
+from posthog.temporal.ai_observability.metrics import increment_emit_event_outcome
+
+from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
+from products.ai_observability.backend.models.evaluations import Evaluation
+from products.ai_observability.backend.models.provider_keys import LLMProviderKey
+
+logger = structlog.get_logger(__name__)
+
+SOURCE_AI_PROPERTIES_TO_COPY = ("$ai_prompt_name", "$ai_prompt_version")
+TRIAL_NOTIFICATION_THRESHOLDS = [50, 75, 100]
+
+
+@dataclass
+class RunEvaluationInputs:
+ evaluation_id: str
+ event_data: dict[str, Any]
+
+ @property
+ def properties_to_log(self) -> dict[str, Any]:
+ return {
+ "evaluation_id": self.evaluation_id,
+ "team_id": self.event_data.get("team_id"),
+ }
+
+
+async def fetch_evaluation_activity(inputs: RunEvaluationInputs) -> dict[str, Any]:
+ """Fetch evaluation config from Postgres."""
+ bind_contextvars(team_id=inputs.event_data.get("team_id"), evaluation_id=inputs.evaluation_id)
+
+ def _fetch() -> dict[str, Any]:
+ try:
+ evaluation = Evaluation.objects.select_related(
+ "model_configuration",
+ "model_configuration__provider_key",
+ ).get(id=inputs.evaluation_id, team_id=inputs.event_data["team_id"])
+
+ model_configuration = None
+ if evaluation.model_configuration:
+ mc = evaluation.model_configuration
+ model_configuration = {
+ "provider": mc.provider,
+ "model": mc.model,
+ "provider_key_id": str(mc.provider_key_id) if mc.provider_key_id else None,
+ }
+
+ return {
+ "id": str(evaluation.id),
+ "name": evaluation.name,
+ "evaluation_type": evaluation.evaluation_type,
+ "evaluation_config": evaluation.evaluation_config,
+ "output_type": evaluation.output_type,
+ "output_config": evaluation.output_config,
+ "team_id": evaluation.team_id,
+ "model_configuration": model_configuration,
+ }
+ except Evaluation.DoesNotExist:
+ logger.exception("Evaluation not found", evaluation_id=inputs.evaluation_id)
+ raise ValueError(f"Evaluation {inputs.evaluation_id} not found")
+
+ return await database_sync_to_async(_fetch)()
+
+
+async def update_key_state_activity(key_id: str, state: str, error_message: str | None) -> None:
+ """Update the state of an LLM provider key."""
+
+ def _update() -> None:
+ try:
+ key = LLMProviderKey.objects.get(id=key_id)
+ key.state = state
+ key.error_message = error_message
+ key.save(update_fields=["state", "error_message"])
+ except LLMProviderKey.DoesNotExist:
+ logger.warning("Tried to update state for non-existent key", key_id=key_id)
+
+ await database_sync_to_async(_update)()
+
+
+async def increment_trial_eval_count_activity(team_id: int) -> int | None:
+ """Increment trial eval counter after successful execution with PostHog key."""
+ from django.db import connection
+
+ def _increment() -> int | None:
+ table = EvaluationConfig._meta.db_table
+ with connection.cursor() as cursor:
+ cursor.execute(
+ f"""
+ UPDATE {table}
+ SET trial_evals_used = trial_evals_used + 1
+ WHERE team_id = %s
+ RETURNING trial_evals_used, trial_eval_limit
+ """,
+ [team_id],
+ )
+ row = cursor.fetchone()
+ if row is None:
+ logger.warning("No EvaluationConfig found for team during trial increment", team_id=team_id)
+ return None
+ trial_evals_used, trial_eval_limit = row
+
+ for pct in TRIAL_NOTIFICATION_THRESHOLDS:
+ if trial_evals_used == round(trial_eval_limit * pct / 100):
+ return pct
+ return None
+
+ return await database_sync_to_async(_increment)()
+
+
+async def disable_evaluation_activity(evaluation_id: str, team_id: int, status_reason: str = "") -> None:
+ """Transition an evaluation into the ERROR state when the workflow hits a terminal skippable error."""
+
+ def _disable() -> None:
+ reason = status_reason or "trial_limit_reached"
+ evaluation = Evaluation.objects.filter(id=evaluation_id, team_id=team_id).first()
+ if evaluation is not None:
+ evaluation.set_status("error", reason)
+
+ await database_sync_to_async(_disable)()
+
+
+@dataclass
+class SendTrialUsageEmailInputs:
+ team_id: int
+ threshold_pct: int
+
+
+async def send_trial_usage_email_activity(inputs: SendTrialUsageEmailInputs) -> None:
+ """Send an email to org members about trial evaluation usage."""
+
+ def _send() -> None:
+ from posthog.email import EmailMessage, is_email_available
+
+ if not is_email_available(with_absolute_urls=True):
+ logger.info(
+ "Email not available, skipping trial usage notification",
+ team_id=inputs.team_id,
+ threshold_pct=inputs.threshold_pct,
+ )
+ return
+
+ try:
+ team = Team.objects.select_related("organization").get(id=inputs.team_id)
+ except Team.DoesNotExist:
+ logger.warning("Team not found for trial usage email", team_id=inputs.team_id)
+ return
+
+ config = EvaluationConfig.objects.filter(team_id=inputs.team_id).first()
+ if not config:
+ return
+
+ max_listed = 20
+ affected_qs = Evaluation.objects.filter(
+ team_id=inputs.team_id,
+ enabled=True,
+ deleted=False,
+ ).filter(models.Q(model_configuration__isnull=True) | models.Q(model_configuration__provider_key__isnull=True))
+ total_affected = affected_qs.count()
+ affected_evals = list(affected_qs.values_list("name", flat=True)[:max_listed])
+ affected_evals_overflow = max(0, total_affected - max_listed)
+
+ settings_url = f"/project/{team.pk}/settings/project-ai-observability#ai-observability-byok"
+ campaign_key = f"llm_analytics_trial_{inputs.threshold_pct}pct_{team.id}"
+ is_exhausted = inputs.threshold_pct >= 100
+
+ if is_exhausted:
+ subject = "Your AI observability trial evaluations have been used up"
+ template_name = "ai_observability_trial_exhausted"
+ else:
+ subject = f"You've used {inputs.threshold_pct}% of your AI observability trial evaluations"
+ template_name = "ai_observability_trial_warning"
+
+ message = EmailMessage(
+ campaign_key=campaign_key,
+ subject=subject,
+ template_name=template_name,
+ template_context={
+ "trial_eval_limit": config.trial_eval_limit,
+ "trial_evals_used": config.trial_evals_used,
+ "trial_evals_remaining": config.trial_evals_remaining,
+ "threshold_pct": inputs.threshold_pct,
+ "settings_url": settings_url,
+ "affected_evals": affected_evals,
+ "affected_evals_overflow": affected_evals_overflow,
+ },
+ )
+
+ for user in team.organization.members.all():
+ message.add_user_recipient(user)
+
+ if message.to:
+ message.send()
+ logger.info(
+ "Sent trial usage email",
+ team_id=inputs.team_id,
+ org_id=str(team.organization_id),
+ threshold_pct=inputs.threshold_pct,
+ recipient_count=len(message.to),
+ )
+
+ await database_sync_to_async(_send)()
+
+
+@dataclass
+class SendEvaluationDisabledEmailInputs:
+ team_id: int
+ evaluation_id: str
+ evaluation_name: str
+ status_reason: str
+ human_readable_reason: str
+
+
+_STATUS_REASON_SUBJECTS = {
+ "model_not_allowed": "Your AI observability evaluation was disabled because its model isn't supported on the trial plan",
+ "provider_key_deleted": "Your AI observability evaluation was disabled because its provider API key was removed",
+}
+
+
+async def send_evaluation_disabled_email_activity(inputs: SendEvaluationDisabledEmailInputs) -> None:
+ """Email org members when an evaluation enters the ERROR state for a reason other than trial exhaustion."""
+
+ def _send() -> None:
+ from posthog.email import EmailMessage, is_email_available
+
+ if not is_email_available(with_absolute_urls=True):
+ logger.info(
+ "Email not available, skipping evaluation disabled notification",
+ team_id=inputs.team_id,
+ evaluation_id=inputs.evaluation_id,
+ )
+ return
+
+ try:
+ team = Team.objects.select_related("organization").get(id=inputs.team_id)
+ except Team.DoesNotExist:
+ logger.warning("Team not found for evaluation disabled email", team_id=inputs.team_id)
+ return
+
+ settings_url = f"/project/{team.pk}/settings/project-ai-observability#ai-observability-byok"
+ evaluation_url = f"/project/{team.pk}/ai-evals/evaluations/{inputs.evaluation_id}"
+ campaign_key = f"llm_analytics_eval_disabled_{inputs.evaluation_id}_{inputs.status_reason}"
+ subject = _STATUS_REASON_SUBJECTS.get(
+ inputs.status_reason, f'Your evaluation "{inputs.evaluation_name}" has been disabled'
+ )
+
+ message = EmailMessage(
+ campaign_key=campaign_key,
+ subject=subject,
+ template_name="ai_observability_evaluation_disabled",
+ template_context={
+ "evaluation_name": inputs.evaluation_name,
+ "disabled_reason": inputs.human_readable_reason,
+ "settings_url": settings_url,
+ "evaluation_url": evaluation_url,
+ },
+ )
+
+ for user in team.organization.members.all():
+ message.add_user_recipient(user)
+
+ if message.to:
+ message.send()
+ logger.info(
+ "Sent evaluation disabled email",
+ team_id=inputs.team_id,
+ evaluation_id=inputs.evaluation_id,
+ status_reason=inputs.status_reason,
+ recipient_count=len(message.to),
+ )
+
+ await database_sync_to_async(_send)()
+
+
+@dataclass
+class EmitEvaluationEventInputs:
+ evaluation: dict[str, Any]
+ event_data: dict[str, Any]
+ result: EvaluationActivityResult
+ start_time: datetime
+
+ @property
+ def properties_to_log(self) -> dict[str, Any]:
+ return {
+ "team_id": self.event_data.get("team_id"),
+ "evaluation_id": self.evaluation.get("id"),
+ }
+
+
+async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> None:
+ """Emit $ai_evaluation event via capture_internal so it routes through the ingestion pipeline for cost calculation."""
+ evaluation = inputs.evaluation
+ event_data = inputs.event_data
+ result = inputs.result
+ start_time = inputs.start_time
+
+ def _emit() -> None:
+ try:
+ team = Team.objects.get(id=event_data["team_id"])
+ except Team.DoesNotExist:
+ logger.exception("Team not found", team_id=event_data["team_id"])
+ raise ValueError(f"Team {event_data['team_id']} not found")
+
+ allows_na = result.get("allows_na", False)
+ evaluation_type = evaluation.get("evaluation_type", "llm_judge")
+
+ source_props = (
+ json.loads(event_data["properties"])
+ if isinstance(event_data["properties"], str)
+ else event_data["properties"]
+ )
+
+ properties: dict[str, Any] = {
+ "$ai_evaluation_id": evaluation["id"],
+ "$ai_evaluation_name": evaluation["name"],
+ "$ai_evaluation_type": "online",
+ "$ai_evaluation_runtime": evaluation_type,
+ "$ai_evaluation_result_type": result["result_type"],
+ "$ai_evaluation_start_time": start_time.isoformat(),
+ "$ai_evaluation_reasoning": result["reasoning"],
+ "$ai_target_event_id": event_data["uuid"],
+ "$ai_target_event_type": event_data["event"],
+ "$ai_target_id": event_data["uuid"],
+ "$ai_target_type": "generation_uuid",
+ "$ai_trace_id": source_props.get("$ai_trace_id"),
+ "$session_id": source_props.get("$session_id"),
+ }
+
+ for property_name in SOURCE_AI_PROPERTIES_TO_COPY:
+ if source_props.get(property_name) is not None:
+ properties[property_name] = source_props[property_name]
+
+ if result.get("skipped"):
+ properties["$ai_evaluation_skipped"] = True
+ properties["$ai_evaluation_skip_reason"] = result.get("skip_reason")
+
+ if evaluation_type == "llm_judge" and not result.get("skipped"):
+ properties["$ai_model"] = result.get("model", DEFAULT_JUDGE_MODEL)
+ properties["$ai_provider"] = result.get("provider", "openai")
+ properties["$ai_input_tokens"] = result.get("input_tokens", 0)
+ properties["$ai_output_tokens"] = result.get("output_tokens", 0)
+ properties["$ai_evaluation_model"] = result.get("model", DEFAULT_JUDGE_MODEL)
+ properties["$ai_evaluation_provider"] = result.get("provider", "openai")
+ properties["$ai_evaluation_key_type"] = "byok" if result.get("is_byok") else "posthog"
+ properties["$ai_evaluation_key_id"] = result.get("key_id")
+
+ if result["result_type"] == "sentiment":
+ properties["$ai_sentiment_label"] = result.get("sentiment_label")
+ properties["$ai_sentiment_score"] = result.get("sentiment_score")
+ properties["$ai_sentiment_scores"] = result.get("sentiment_scores")
+ properties["$ai_sentiment_messages"] = result.get("sentiment_messages")
+ properties["$ai_sentiment_message_count"] = result.get("sentiment_message_count")
+ else:
+ properties["$ai_evaluation_allows_na"] = allows_na
+ if allows_na:
+ applicable = result.get("applicable", True)
+ properties["$ai_evaluation_applicable"] = applicable
+ if applicable:
+ properties["$ai_evaluation_result"] = result["verdict"]
+ else:
+ properties["$ai_evaluation_result"] = result["verdict"]
+
+ event_timestamp = datetime.now(UTC)
+
+ capture_result = capture_internal_routed(
+ token=team.api_token,
+ event_name="$ai_evaluation",
+ event_source="llm_analytics_evaluation",
+ distinct_id=event_data["distinct_id"],
+ timestamp=event_timestamp,
+ properties=properties,
+ process_person_profile=True,
+ )
+ capture_result.raise_for_status()
+
+ try:
+ await database_sync_to_async(_emit, thread_sensitive=False)()
+ increment_emit_event_outcome("success")
+ except Exception:
+ increment_emit_event_outcome("failed")
+ raise
+
+
+@dataclass
+class EmitInternalTelemetryInputs:
+ evaluation: dict[str, Any]
+ team_id: int
+ result: EvaluationActivityResult
+
+ @property
+ def properties_to_log(self) -> dict[str, Any]:
+ return {
+ "team_id": self.team_id,
+ "evaluation_id": self.evaluation.get("id"),
+ }
+
+
+async def emit_internal_telemetry_activity(inputs: EmitInternalTelemetryInputs) -> None:
+ """Emit telemetry event to PostHog org for internal tracking."""
+ from posthog.tasks.usage_report import get_ph_client
+
+ evaluation = inputs.evaluation
+ team_id = inputs.team_id
+ result = inputs.result
+
+ def _emit_telemetry() -> None:
+ team = Team.objects.get(id=team_id)
+ organization_id = str(team.organization_id)
+
+ ph_client = get_ph_client(sync_mode=True)
+ ph_client.capture(
+ distinct_id=f"org-{organization_id}",
+ event="llm analytics evaluation executed",
+ properties={
+ "evaluation_id": evaluation["id"],
+ "team_id": team_id,
+ "model": result.get("model", DEFAULT_JUDGE_MODEL),
+ "provider": result.get("provider", "openai"),
+ "input_tokens": result.get("input_tokens", 0),
+ "output_tokens": result.get("output_tokens", 0),
+ "total_tokens": result.get("total_tokens", 0),
+ "verdict": result["verdict"],
+ },
+ groups={"organization": organization_id, "instance": settings.SITE_URL},
+ )
+ ph_client.flush()
+
+ await database_sync_to_async(_emit_telemetry, thread_sensitive=False)()
diff --git a/posthog/temporal/ai_observability/metrics.py b/posthog/temporal/ai_observability/metrics.py
index 2e4bee48435b..29b0bf46151d 100644
--- a/posthog/temporal/ai_observability/metrics.py
+++ b/posthog/temporal/ai_observability/metrics.py
@@ -27,6 +27,7 @@ EVAL_ACTIVITY_TYPES = {
"fetch_evaluation_activity",
"execute_llm_judge_activity",
"execute_hog_eval_activity",
+ "execute_sentiment_eval_activity",
"emit_evaluation_event_activity",
"emit_internal_telemetry_activity",
"increment_trial_eval_count_activity",
@@ -201,8 +202,8 @@ class _EvalsMetricsWorkflowInterceptor(WorkflowInboundInterceptor):
increment_workflow_finished(status, evaluation_type)
return result
- # Record verdict
- if isinstance(result, dict):
+ # Record verdict for boolean-output evaluations. Sentiment emits no boolean verdict.
+ if isinstance(result, dict) and "verdict" in result:
verdict = result.get("verdict")
if verdict is True:
increment_verdict("true", evaluation_type)
diff --git a/posthog/temporal/ai_observability/run_evaluation.py b/posthog/temporal/ai_observability/run_evaluation.py
index 5bd927e2b877..3c80a96a3f31 100644
--- a/posthog/temporal/ai_observability/run_evaluation.py
+++ b/posthog/temporal/ai_observability/run_evaluation.py
@@ -1,45 +1,45 @@
import json
-from dataclasses import dataclass
-from datetime import UTC, datetime, timedelta
-from typing import Any, NotRequired, Required, TypedDict
+from datetime import timedelta
+from typing import NotRequired, Required, TypedDict
from django.conf import settings
-from django.db import models
-from django.utils import timezone
-import structlog
import temporalio
-import posthoganalytics
-from pydantic import BaseModel, model_validator
-from structlog.contextvars import bind_contextvars
from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from temporalio.exceptions import ApplicationError
-from posthog.api.capture_dispatch import capture_internal_routed
-from posthog.models.team import Team
-from posthog.sync import database_sync_to_async
-from posthog.temporal.ai_observability.message_utils import extract_text_from_messages, format_tool_definitions
-from posthog.temporal.ai_observability.metrics import (
- increment_emit_event_outcome,
- increment_errors,
- increment_key_type,
- increment_provider_model,
- increment_tokens,
+from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io, extract_event_tools
+from posthog.temporal.ai_observability.evaluation_hog import execute_hog_eval_activity, run_hog_eval
+from posthog.temporal.ai_observability.evaluation_llm_judge import (
+ DEFAULT_JUDGE_MODEL,
+ LLM_JUDGE_RETRY_POLICY,
+ BooleanEvalResult,
+ BooleanWithNAEvalResult,
+ ExecuteLLMJudgeInputs,
+ build_system_prompt,
+ execute_llm_judge_activity,
+ get_output_type_config,
)
+from posthog.temporal.ai_observability.evaluation_sentiment import execute_sentiment_eval_activity
+from posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult
+from posthog.temporal.ai_observability.evaluation_workflow_activities import (
+ EmitEvaluationEventInputs,
+ EmitInternalTelemetryInputs,
+ RunEvaluationInputs,
+ SendEvaluationDisabledEmailInputs,
+ SendTrialUsageEmailInputs,
+ disable_evaluation_activity,
+ emit_evaluation_event_activity,
+ emit_internal_telemetry_activity,
+ fetch_evaluation_activity,
+ increment_trial_eval_count_activity,
+ send_evaluation_disabled_email_activity,
+ send_trial_usage_email_activity,
+ update_key_state_activity,
+)
+from posthog.temporal.ai_observability.metrics import increment_errors
from posthog.temporal.common.base import PostHogWorkflow
-from products.ai_observability.backend.llm import TRIAL_MODEL_IDS, Client, CompletionRequest
-from products.ai_observability.backend.llm.config import get_eval_config
-from products.ai_observability.backend.llm.errors import (
- AuthenticationError,
- ModelNotFoundError,
- ModelPermissionError,
- QuotaExceededError,
- RateLimitError,
- StructuredOutputParseError,
-)
-from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
-from products.ai_observability.backend.models.evaluations import Evaluation
from products.ai_observability.backend.models.provider_keys import LLMProviderKey
from products.signals.backend.temporal.emit_eval_signal import (
EmitEvalSignalInputs,
@@ -47,1091 +47,51 @@ from products.signals.backend.temporal.emit_eval_signal import (
emit_eval_signal_activity,
)
-from common.hogvm.python.execute import execute_bytecode
-from common.hogvm.python.utils import HogVMException, HogVMMemoryExceededException, HogVMRuntimeExceededException
-
-logger = structlog.get_logger(__name__)
-
-# Default model for LLM judge
-DEFAULT_JUDGE_MODEL = "gpt-5-mini"
-
-SOURCE_AI_PROPERTIES_TO_COPY = ("$ai_prompt_name", "$ai_prompt_version")
-
-# Retry policy for LLM judge activity with exponential backoff to prevent amplifying load during outages
-LLM_JUDGE_RETRY_POLICY = RetryPolicy(
- maximum_attempts=3,
- initial_interval=timedelta(seconds=10),
- maximum_interval=timedelta(seconds=60),
- backoff_coefficient=2.0,
-)
-
-
-class LLMJudgeResult(TypedDict, total=False):
- """Result produced by `execute_llm_judge_activity`, `_build_errored_trace_result`, and
- `execute_hog_eval_activity`.
-
- `total=False` is used as the default so individual fields opt in via `Required` /
- `NotRequired`, making the contract honest about which keys every path actually sets:
-
- - `verdict`, `reasoning`, `allows_na` are set on every path (LLM judge success, errored-
- trace skip, hog eval) and are `Required`.
- - `applicable` is set only when `allows_na=True`.
- - `skipped` and `skip_reason` are set only on the skip path (e.g. errored source trace).
- - `model`, `provider`, `key_id`, `is_byok`, and the `*_tokens` fields come from the LLM
- judge success path. The skip path omits `model`/`provider` so downstream cost
- attribution doesn't credit phantom calls, and `execute_hog_eval_activity` (whose
- output also flows into `emit_evaluation_event_activity`) emits only `verdict`,
- `reasoning`, `allows_na`, and optionally `applicable`.
- """
-
- verdict: Required[bool | None]
- reasoning: Required[str]
- allows_na: Required[bool]
- input_tokens: NotRequired[int]
- output_tokens: NotRequired[int]
- total_tokens: NotRequired[int]
- is_byok: NotRequired[bool]
- key_id: NotRequired[str | None]
- model: NotRequired[str]
- provider: NotRequired[str]
- applicable: NotRequired[bool]
- skipped: NotRequired[bool]
- skip_reason: NotRequired[str]
+__all__ = [
+ "BooleanEvalResult",
+ "BooleanWithNAEvalResult",
+ "DEFAULT_JUDGE_MODEL",
+ "EmitEvaluationEventInputs",
+ "EmitInternalTelemetryInputs",
+ "ExecuteLLMJudgeInputs",
+ "EvaluationActivityResult",
+ "RunEvaluationInputs",
+ "RunEvaluationWorkflow",
+ "SendEvaluationDisabledEmailInputs",
+ "SendTrialUsageEmailInputs",
+ "WorkflowResult",
+ "build_system_prompt",
+ "disable_evaluation_activity",
+ "emit_evaluation_event_activity",
+ "emit_internal_telemetry_activity",
+ "execute_hog_eval_activity",
+ "execute_llm_judge_activity",
+ "execute_sentiment_eval_activity",
+ "extract_event_io",
+ "extract_event_tools",
+ "fetch_evaluation_activity",
+ "get_output_type_config",
+ "increment_trial_eval_count_activity",
+ "run_hog_eval",
+ "send_evaluation_disabled_email_activity",
+ "send_trial_usage_email_activity",
+ "update_key_state_activity",
+]
class WorkflowResult(TypedDict, total=False):
- """Result returned by `RunEvaluationWorkflow.run`.
-
- Composes a subset of `LLMJudgeResult` with workflow-level identifiers. Both branches
- that build this dict — the skip-on-error branch (e.g. `trial_limit_reached`,
- `key_invalid`) and the normal-completion branch — always set `verdict`, `evaluation_id`,
- `evaluation_type`, and `skipped`, so those four are `Required`. The skip-on-error branch
- omits `reasoning` and `is_byok` and adds `message`; `skip_reason` is set only when
- `skipped=True`.
- """
+ """Result returned by `RunEvaluationWorkflow.run`."""
- verdict: Required[bool | None]
evaluation_id: Required[str]
evaluation_type: Required[str]
skipped: Required[bool]
+ verdict: NotRequired[bool | None]
reasoning: NotRequired[str]
is_byok: NotRequired[bool]
skip_reason: NotRequired[str]
message: NotRequired[str]
-class BooleanEvalResult(BaseModel):
- """Structured output for boolean evaluation results"""
-
- reasoning: str
- verdict: bool
-
-
-class BooleanWithNAEvalResult(BaseModel):
- """Structured output for boolean with N/A evaluation results.
-
- When the evaluation criteria doesn't apply to the input/output,
- applicable should be False and verdict should be None.
- """
-
- reasoning: str
- applicable: bool
- verdict: bool | None = None
-
- @model_validator(mode="after")
- def validate_verdict_consistency(self) -> "BooleanWithNAEvalResult":
- if self.applicable and self.verdict is None:
- raise ValueError("verdict is required when applicable is true")
- if not self.applicable and self.verdict is not None:
- raise ValueError("verdict must be null when applicable is false")
- return self
-
-
-@dataclass
-class OutputTypeConfig:
- """Configuration for each evaluation output type"""
-
- response_format: type[BooleanEvalResult] | type[BooleanWithNAEvalResult]
- instructions: str
-
-
-def get_output_type_config(allows_na: bool) -> OutputTypeConfig:
- """Get the output type configuration based on whether N/A is allowed."""
- if allows_na:
- return OutputTypeConfig(
- response_format=BooleanWithNAEvalResult,
- instructions="""First, determine if this evaluation criteria is applicable to the given input/output. If the criteria doesn't apply to this case mark it as not applicable.
-
-Note: If the criteria above instructs you to return "N/A", "not applicable", or similar, treat that as applicable=false with verdict=null.
-
-Return:
-- applicable: true if the criteria applies to this input/output, false if it doesn't apply
-- verdict: true if it passes, false if it fails, or null if not applicable
-- reasoning: a brief explanation (1 sentence)""",
- )
- return OutputTypeConfig(
- response_format=BooleanEvalResult,
- instructions="Provide a brief reasoning (1 sentence) and a boolean verdict (true/false).",
- )
-
-
-def build_system_prompt(prompt: str, allows_na: bool) -> str:
- """Build the system prompt for the LLM judge."""
- config = get_output_type_config(allows_na)
- return f"""You are an evaluator. Evaluate the following generation according to this criteria:
-
-{prompt}
-
-{config.instructions}"""
-
-
-@dataclass
-class RunEvaluationInputs:
- evaluation_id: str
- event_data: dict[str, Any]
-
- @property
- def properties_to_log(self) -> dict[str, Any]:
- """Properties for PostHogClientInterceptor error capture."""
- return {
- "evaluation_id": self.evaluation_id,
- "team_id": self.event_data.get("team_id"),
- }
-
-
-async def fetch_evaluation_activity(inputs: RunEvaluationInputs) -> dict[str, Any]:
- """Fetch evaluation config from Postgres"""
- bind_contextvars(team_id=inputs.event_data.get("team_id"), evaluation_id=inputs.evaluation_id)
-
- def _fetch():
- try:
- evaluation = Evaluation.objects.select_related(
- "model_configuration",
- "model_configuration__provider_key",
- ).get(id=inputs.evaluation_id, team_id=inputs.event_data["team_id"])
-
- model_configuration = None
- if evaluation.model_configuration:
- mc = evaluation.model_configuration
- model_configuration = {
- "provider": mc.provider,
- "model": mc.model,
- "provider_key_id": str(mc.provider_key_id) if mc.provider_key_id else None,
- }
-
- return {
- "id": str(evaluation.id),
- "name": evaluation.name,
- "evaluation_type": evaluation.evaluation_type,
- "evaluation_config": evaluation.evaluation_config,
- "output_type": evaluation.output_type,
- "output_config": evaluation.output_config,
- "team_id": evaluation.team_id,
- "model_configuration": model_configuration,
- }
- except Evaluation.DoesNotExist:
- logger.exception("Evaluation not found", evaluation_id=inputs.evaluation_id)
- raise ValueError(f"Evaluation {inputs.evaluation_id} not found")
-
- return await database_sync_to_async(_fetch)()
-
-
-async def update_key_state_activity(key_id: str, state: str, error_message: str | None) -> None:
- """Update the state of an LLM provider key"""
-
- def _update():
- try:
- key = LLMProviderKey.objects.get(id=key_id)
- key.state = state
- key.error_message = error_message
- key.save(update_fields=["state", "error_message"])
- except LLMProviderKey.DoesNotExist:
- logger.warning("Tried to update state for non-existent key", key_id=key_id)
-
- await database_sync_to_async(_update)()
-
-
-TRIAL_NOTIFICATION_THRESHOLDS = [50, 75, 100]
-
-
-async def increment_trial_eval_count_activity(team_id: int) -> int | None:
- """Increment trial eval counter after successful execution with PostHog key.
-
- Returns the usage percentage threshold that was just crossed (50, 75, or
- 100), or None if no threshold was crossed. The increment and read are
- performed atomically via UPDATE ... RETURNING to avoid race conditions
- where concurrent increments could both see the same threshold.
- """
- from django.db import connection
-
- def _increment() -> int | None:
- table = EvaluationConfig._meta.db_table
- with connection.cursor() as cursor:
- cursor.execute(
- f"""
- UPDATE {table}
- SET trial_evals_used = trial_evals_used + 1
- WHERE team_id = %s
- RETURNING trial_evals_used, trial_eval_limit
- """,
- [team_id],
- )
- row = cursor.fetchone()
- if row is None:
- logger.warning("No EvaluationConfig found for team during trial increment", team_id=team_id)
- return None
- trial_evals_used, trial_eval_limit = row
-
- for pct in TRIAL_NOTIFICATION_THRESHOLDS:
- if trial_evals_used == round(trial_eval_limit * pct / 100):
- return pct
- return None
-
- return await database_sync_to_async(_increment)()
-
-
-async def disable_evaluation_activity(evaluation_id: str, team_id: int, status_reason: str = "") -> None:
- """Transition an evaluation into the ERROR state when the workflow hits a terminal skippable error.
-
- status_reason must be one of EvaluationStatusReason values; empty is accepted for backwards compat but
- should never happen for new callers — the model's save() enforces a reason when status is ERROR.
- """
-
- def _disable():
- reason = status_reason or "trial_limit_reached"
- evaluation = Evaluation.objects.filter(id=evaluation_id, team_id=team_id).first()
- if evaluation is not None:
- evaluation.set_status("error", reason)
-
- await database_sync_to_async(_disable)()
-
-
-@dataclass
-class SendTrialUsageEmailInputs:
- team_id: int
- threshold_pct: int
-
-
-async def send_trial_usage_email_activity(inputs: SendTrialUsageEmailInputs) -> None:
- """Send an email to org members about trial evaluation usage.
-
- Handles both warning emails (50%, 75%) and the exhaustion email (100%).
- """
-
- def _send():
- from posthog.email import EmailMessage, is_email_available
-
- if not is_email_available(with_absolute_urls=True):
- logger.info(
- "Email not available, skipping trial usage notification",
- team_id=inputs.team_id,
- threshold_pct=inputs.threshold_pct,
- )
- return
-
- try:
- team = Team.objects.select_related("organization").get(id=inputs.team_id)
- except Team.DoesNotExist:
- logger.warning("Team not found for trial usage email", team_id=inputs.team_id)
- return
-
- config = EvaluationConfig.objects.filter(team_id=inputs.team_id).first()
- if not config:
- return
-
- # Find evaluations that will be affected (on trial, enabled, not deleted)
- max_listed = 20
- affected_qs = Evaluation.objects.filter(
- team_id=inputs.team_id,
- enabled=True,
- deleted=False,
- ).filter(models.Q(model_configuration__isnull=True) | models.Q(model_configuration__provider_key__isnull=True))
- total_affected = affected_qs.count()
- affected_evals = list(affected_qs.values_list("name", flat=True)[:max_listed])
- affected_evals_overflow = max(0, total_affected - max_listed)
-
- settings_url = f"/project/{team.pk}/settings/project-ai-observability#ai-observability-byok"
- campaign_key = f"llm_analytics_trial_{inputs.threshold_pct}pct_{team.id}"
- is_exhausted = inputs.threshold_pct >= 100
-
- if is_exhausted:
- subject = "Your AI observability trial evaluations have been used up"
- template_name = "ai_observability_trial_exhausted"
- else:
- subject = f"You've used {inputs.threshold_pct}% of your AI observability trial evaluations"
- template_name = "ai_observability_trial_warning"
-
- message = EmailMessage(
- campaign_key=campaign_key,
- subject=subject,
- template_name=template_name,
- template_context={
- "trial_eval_limit": config.trial_eval_limit,
- "trial_evals_used": config.trial_evals_used,
- "trial_evals_remaining": config.trial_evals_remaining,
- "threshold_pct": inputs.threshold_pct,
- "settings_url": settings_url,
- "affected_evals": affected_evals,
- "affected_evals_overflow": affected_evals_overflow,
- },
- )
-
- for user in team.organization.members.all():
- message.add_user_recipient(user)
-
- if message.to:
- message.send()
- logger.info(
- "Sent trial usage email",
- team_id=inputs.team_id,
- org_id=str(team.organization_id),
- threshold_pct=inputs.threshold_pct,
- recipient_count=len(message.to),
- )
-
- await database_sync_to_async(_send)()
-
-
-@dataclass
-class SendEvaluationDisabledEmailInputs:
- team_id: int
- evaluation_id: str
- evaluation_name: str
- status_reason: str
- human_readable_reason: str
-
-
-_STATUS_REASON_SUBJECTS = {
- "model_not_allowed": "Your AI observability evaluation was disabled because its model isn't supported on the trial plan",
- "provider_key_deleted": "Your AI observability evaluation was disabled because its provider API key was removed",
-}
-
-
-async def send_evaluation_disabled_email_activity(inputs: SendEvaluationDisabledEmailInputs) -> None:
- """Email org members when an evaluation enters the ERROR state for a reason other than trial exhaustion.
-
- Trial-exhausted disabling continues to use send_trial_usage_email_activity because that one aggregates
- across all affected evals and has a different recovery CTA.
- """
-
- def _send():
- from posthog.email import EmailMessage, is_email_available
-
- if not is_email_available(with_absolute_urls=True):
- logger.info(
- "Email not available, skipping evaluation disabled notification",
- team_id=inputs.team_id,
- evaluation_id=inputs.evaluation_id,
- )
- return
-
- try:
- team = Team.objects.select_related("organization").get(id=inputs.team_id)
- except Team.DoesNotExist:
- logger.warning("Team not found for evaluation disabled email", team_id=inputs.team_id)
- return
-
- settings_url = f"/project/{team.pk}/settings/project-ai-observability#ai-observability-byok"
- evaluation_url = f"/project/{team.pk}/ai-evals/evaluations/{inputs.evaluation_id}"
- # Campaign key includes the reason so users get a fresh notification if an eval errors for a
- # different reason later (e.g. model was allowed, then the provider key got deleted).
- campaign_key = f"llm_analytics_eval_disabled_{inputs.evaluation_id}_{inputs.status_reason}"
- subject = _STATUS_REASON_SUBJECTS.get(
- inputs.status_reason, f'Your evaluation "{inputs.evaluation_name}" has been disabled'
- )
-
- message = EmailMessage(
- campaign_key=campaign_key,
- subject=subject,
- template_name="ai_observability_evaluation_disabled",
- template_context={
- "evaluation_name": inputs.evaluation_name,
- "disabled_reason": inputs.human_readable_reason,
- "settings_url": settings_url,
- "evaluation_url": evaluation_url,
- },
- )
-
- for user in team.organization.members.all():
- message.add_user_recipient(user)
-
- if message.to:
- message.send()
- logger.info(
- "Sent evaluation disabled email",
- team_id=inputs.team_id,
- evaluation_id=inputs.evaluation_id,
- status_reason=inputs.status_reason,
- recipient_count=len(message.to),
- )
-
- await database_sync_to_async(_send)()
-
-
-@dataclass
-class ExecuteLLMJudgeInputs:
- evaluation: dict[str, Any]
- event_data: dict[str, Any]
-
- @property
- def properties_to_log(self) -> dict[str, Any]:
- return {
- "team_id": self.evaluation.get("team_id"),
- "evaluation_id": self.evaluation.get("id"),
- }
-
-
-def _is_errored_trace(properties: dict[str, Any]) -> bool:
- """Return True when the captured trace recorded an error.
-
- `$ai_is_error` may be ingested as a Python bool or a JSON-encoded string depending on the
- SDK and capture path, so we normalise both forms here.
- """
- raw = properties.get("$ai_is_error")
- if isinstance(raw, bool):
- return raw
- if isinstance(raw, str):
- return raw.strip().lower() == "true"
- return False
-
-
-def _build_errored_trace_result(allows_na: bool) -> LLMJudgeResult:
- """Result returned when the source trace errored — skips the LLM call entirely.
-
- `model` and `provider` are deliberately omitted so the `.get(..., DEFAULT_JUDGE_MODEL)`
- defaults in downstream activities don't silently attribute phantom calls to a model that
- was never invoked — the emit activity instead detects the `skipped` flag and drops cost
- and model attribution entirely. The `LLMJudgeResult` TypedDict expresses the shape
- contract previously enforced by convention.
- """
- reasoning = "Source trace errored before producing output; evaluation skipped."
- result: LLMJudgeResult = {
- "verdict": None if allows_na else False,
- "reasoning": reasoning,
- "input_tokens": 0,
- "output_tokens": 0,
- "total_tokens": 0,
- "is_byok": False,
- "key_id": None,
- "allows_na": allows_na,
- "skipped": True,
- "skip_reason": "trace_errored",
- }
- if allows_na:
- result["applicable"] = False
- return result
-
-
-def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeResult:
- """Execute LLM judge to evaluate the target event.
-
- Fetches API key configuration internally to avoid passing sensitive data between activities.
- """
- return _execute_llm_judge_activity(inputs)
-
-
-def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeResult:
- evaluation = inputs.evaluation
- event_data = inputs.event_data
-
- if evaluation["evaluation_type"] != "llm_judge":
- raise ApplicationError(
- f"Unsupported evaluation type: {evaluation['evaluation_type']}",
- non_retryable=True,
- )
-
- evaluation_config = evaluation.get("evaluation_config", {})
- prompt = evaluation_config.get("prompt")
- if not prompt:
- raise ApplicationError("Missing prompt in evaluation_config", non_retryable=True)
-
- output_type = evaluation["output_type"]
- if output_type != "boolean":
- raise ApplicationError(
- f"Unsupported output type: {output_type}. Supported types: 'boolean'.",
- non_retryable=True,
- )
-
- output_config = evaluation.get("output_config", {})
- allows_na = output_config.get("allows_na", False)
-
- # Parse properties early so we can short-circuit on traces that errored before producing
- # any output. Without this guard, the judge runs against an empty Output and tends to
- # return spurious verdicts (often `true`) instead of recognising that there is nothing to
- # evaluate.
- event_type = event_data["event"]
- properties = event_data["properties"]
- if isinstance(properties, str):
- properties = json.loads(properties)
-
- if _is_errored_trace(properties):
- # Visibility for skipped evaluations comes from the workflow-level SKIPPED status emitted
- # by the metrics interceptor; there is no error to record here.
- return _build_errored_trace_result(allows_na)
-
- # Fetch provider key configuration (BYOK or trial)
- team_id = evaluation["team_id"]
- model_configuration = evaluation.get("model_configuration")
-
- def _get_legacy_provider_key() -> LLMProviderKey | None:
- """Legacy fallback for evaluations without model_configuration."""
- config, _ = EvaluationConfig.objects.get_or_create(team_id=team_id)
-
- # Check if team has active BYOK key
- if config.active_provider_key:
- key = config.active_provider_key
- if key.state == LLMProviderKey.State.OK:
- key.last_used_at = timezone.now()
- key.save(update_fields=["last_used_at"])
- return key
- # Active key exists but is invalid - fail, don't fall back to trial
- raise ApplicationError(
- f"This API key has been disabled (status: {key.state}). Re-validate to recover, or replace it.",
- {"error_type": "key_invalid", "key_id": str(key.id), "key_state": key.state},
- non_retryable=True,
- )
-
- # No active key - check trial quota
- if config.trial_evals_used >= config.trial_eval_limit:
- raise ApplicationError(
- f"Trial evaluation limit ({config.trial_eval_limit}) reached. Add your own API key to continue.",
- {"error_type": "trial_limit_reached", "trial_eval_limit": config.trial_eval_limit},
- non_retryable=True,
- )
-
- # Trial mode - no provider key, use PostHog defaults
- return None
-
- def _get_provider_key_by_id(key_id: str) -> LLMProviderKey:
- """Fetch a specific provider key by ID, validating team ownership."""
- try:
- key = LLMProviderKey.objects.get(id=key_id, team_id=team_id)
- if key.state != LLMProviderKey.State.OK:
- raise ApplicationError(
- f"This API key has been disabled (status: {key.state}). Re-validate to recover, or replace it.",
- {"error_type": "key_invalid", "key_id": str(key.id), "key_state": key.state},
- non_retryable=True,
- )
- key.last_used_at = timezone.now()
- key.save(update_fields=["last_used_at"])
- return key
- except LLMProviderKey.DoesNotExist:
- raise ApplicationError(
- "Provider key not found.",
- {"error_type": "key_not_found", "key_id": key_id},
- non_retryable=True,
- )
-
- def _check_trial_quota() -> None:
- """Check if trial quota is available for PostHog key usage."""
- config, _ = EvaluationConfig.objects.get_or_create(team_id=team_id)
- if config.trial_evals_used >= config.trial_eval_limit:
- raise ApplicationError(
- f"Trial evaluation limit ({config.trial_eval_limit}) reached. Add your own API key to continue.",
- {"error_type": "trial_limit_reached", "trial_eval_limit": config.trial_eval_limit},
- non_retryable=True,
- )
-
- # Determine provider, model, and key based on model_configuration
- if model_configuration:
- provider = model_configuration["provider"]
- model = model_configuration["model"]
- provider_key_id = model_configuration.get("provider_key_id")
-
- if provider_key_id:
- provider_key = _get_provider_key_by_id(provider_key_id)
- else:
- # Using PostHog key — enforce trial model allowlist and quota
- if model not in TRIAL_MODEL_IDS:
- raise ApplicationError(
- f"Model '{model}' is not available on the trial plan. Please add your own API key to use this model.",
- {"error_type": "model_not_allowed", "model": model},
- non_retryable=True,
- )
- _check_trial_quota()
- provider_key = None
- else:
- # TODO(llma): Remove after migration completes - legacy evals without model_configuration
- provider = "openai"
- model = DEFAULT_JUDGE_MODEL
- provider_key = _get_legacy_provider_key()
-
- is_byok = provider_key is not None
- key_id = str(provider_key.id) if provider_key else None
-
- # Extract input/output based on event type
- input_raw, output_raw = extract_event_io(event_type, properties)
- tools_raw = extract_event_tools(properties)
-
- # Extract readable text from message structures
- input_data = extract_text_from_messages(input_raw)
- output_data = extract_text_from_messages(output_raw)
- tools_data = format_tool_definitions(tools_raw)
-
- # Build judge prompt based on allows_na config
- type_config = get_output_type_config(allows_na)
- system_prompt = build_system_prompt(prompt, allows_na)
- response_format = type_config.response_format
-
- # Insert a `Tools available:` section between Input and Output when the
- # event captured the tool catalog. The judge needs to see what the agent
- # *could* call to evaluate prompts like "did it pick the right tool?".
- sections = [f"Input: {input_data}"]
- if tools_data:
- sections.append(f"Tools available:\n{tools_data}")
- sections.append(f"Output: {output_data}")
- user_prompt = "\n\n".join(sections)
-
- # Get eval-specific config when using PostHog defaults (no provider_key)
- config = get_eval_config(provider) if provider_key is None else None
-
- # Create unified Client with analytics disabled to prevent eval loops
- client = Client(
- provider_key=provider_key,
- config=config,
- capture_analytics=False,
- )
-
- try:
- response = client.complete(
- CompletionRequest(
- model=model,
- system=system_prompt,
- messages=[{"role": "user", "content": user_prompt}],
- provider=provider,
- response_format=response_format,
- )
- )
- except AuthenticationError:
- increment_errors("auth_error", provider=provider)
- if is_byok:
- raise ApplicationError(
- "API key is invalid or has been deleted.",
- {"error_type": "auth_error", "key_id": key_id, "provider": provider},
- non_retryable=True,
- )
- raise
- except ModelPermissionError:
- increment_errors("permission_error", provider=provider)
- if is_byok:
- raise ApplicationError(
- "API key doesn't have access to this model.",
- {"error_type": "permission_error", "key_id": key_id, "provider": provider},
- non_retryable=True,
- )
- raise
- except QuotaExceededError:
- increment_errors("quota_error", provider=provider)
- if is_byok:
- raise ApplicationError(
- "API key has exceeded its quota.",
- {"error_type": "quota_error", "key_id": key_id, "provider": provider},
- non_retryable=True,
- )
- raise
- except RateLimitError:
- increment_errors("rate_limit", provider=provider)
- if is_byok:
- raise ApplicationError(
- "API key is being rate limited.",
- {"error_type": "rate_limit", "key_id": key_id, "provider": provider},
- non_retryable=True,
- )
- raise
- except ModelNotFoundError:
- increment_errors("model_not_found", provider=provider)
- raise ApplicationError(
- f"Model '{model}' not found.",
- non_retryable=True,
- )
- except StructuredOutputParseError as e:
- increment_errors("parse_error", provider=provider)
- raise ApplicationError(
- str(e),
- {"error_type": "parse_error"},
- non_retryable=True,
- ) from e
-
- except Exception as e:
- logger.exception(
- "Unhandled error from LLM client",
- evaluation_id=evaluation["id"],
- provider=provider,
- model=model,
- error_class=type(e).__name__,
- )
- increment_errors(type(e).__name__, provider=provider)
- raise
-
- # Parse structured output
- result = response.parsed
- if result is None:
- logger.exception("LLM judge returned empty structured response", evaluation_id=evaluation["id"])
- raise ValueError(f"LLM judge returned empty structured response for evaluation {evaluation['id']}")
-
- # Type narrowing for mypy - the response_format guarantees one of these types
- assert isinstance(result, (BooleanEvalResult, BooleanWithNAEvalResult))
-
- # Extract token usage from response
- usage = response.usage
-
- # Record metrics
- if temporalio.activity.in_activity():
- increment_key_type("byok" if is_byok else "posthog")
- increment_provider_model(provider, model)
- if usage:
- increment_tokens("input", usage.input_tokens)
- increment_tokens("output", usage.output_tokens)
- increment_tokens("total", usage.total_tokens)
- bind_contextvars(provider=provider, model=model)
-
- # Build result dict based on allows_na config
- result_dict: LLMJudgeResult = {
- "verdict": result.verdict,
- "reasoning": result.reasoning,
- "input_tokens": usage.input_tokens if usage else 0,
- "output_tokens": usage.output_tokens if usage else 0,
- "total_tokens": usage.total_tokens if usage else 0,
- "is_byok": is_byok,
- "key_id": key_id,
- "allows_na": allows_na,
- "model": model,
- "provider": provider,
- }
-
- if allows_na and isinstance(result, BooleanWithNAEvalResult):
- result_dict["applicable"] = result.applicable
- elif isinstance(result, BooleanEvalResult):
- pass
- else:
- raise ValueError(f"Unexpected result type: {type(result)}")
-
- return result_dict
-
-
-def extract_event_io(event_type: str, properties: dict[str, Any]) -> tuple[Any, Any]:
- """Extract raw input and output values from event properties.
-
- Returns (input_raw, output_raw) for use in Hog eval globals and preview display.
-
- Invariant: `properties` must already contain the heavy `$ai_*` keys when present
- on the source event. Heavy props are stripped from `events.properties` after the
- cutover (see AI events migration brief), so callers must source the event from a
- path that re-populates them — today that's `EvaluationRunViewSet.create`, which
- reads from `ai_events` and re-merges heavy columns via `merge_heavy_properties`
- before handing `event_data` to this workflow. Adding a new caller? Use the same
- pattern, or feed it `event_data` produced by an already-migrated reader.
-
- Failure mode this invariant guards against: when `is_ai_events_enabled(team)` is
- False (kill switch flipped) AND the team is post-strip, the events-fallback path
- in `EvaluationRunViewSet.create` returns rows whose `properties` JSON has NULL
- heavy keys. `extract_event_io` would then return empty `input_raw` / `output_raw`,
- and the LLM judge / Hog eval would silently grade an empty conversation. The
- invariant exists so any future caller short-circuiting around the migrated
- reader has to confront this case explicitly.
- """
- if event_type == "$ai_generation":
- input_raw = properties.get("$ai_input") or properties.get("$ai_input_state", "")
- output_raw = (
- properties.get("$ai_output_choices")
- or properties.get("$ai_output")
- or properties.get("$ai_output_state", "")
- )
- else:
- input_raw = properties.get("$ai_input_state", "")
- output_raw = properties.get("$ai_output_state", "")
- return input_raw, output_raw
-
-
-def extract_event_tools(properties: dict[str, Any]) -> Any:
- """Extract the tool catalog (`$ai_tools`) captured on the event, regardless
- of event type.
-
- `$ai_generation` is the canonical carrier today, but custom span/trace
- events (e.g. an agent loop's `run_summary`) may also forward the catalog,
- and the judge prompt benefits from it for any event shape. Presence of
- `$ai_tools` drives whether the Tools section renders.
- """
- return properties.get("$ai_tools")
-
-
-def run_hog_eval(bytecode: list, event_data: dict[str, Any], allows_na: bool = False) -> dict[str, Any]:
- """Run compiled Hog bytecode against a single event.
-
- Used by both the Temporal activity and the test endpoint.
- Returns {"verdict": bool | None, "reasoning": str, "error": str | None}.
- When allows_na=True, a `return null` is treated as N/A (not an error).
- """
- properties = event_data["properties"]
- if isinstance(properties, str):
- properties = json.loads(properties)
-
- event_type = event_data["event"]
- input_raw, output_raw = extract_event_io(event_type, properties)
-
- # Ensure input/output are always strings so string operations (ilike, length, etc.) work consistently.
- # Users can still parse structured data with jsonParse() when needed.
- input_val = json.dumps(input_raw) if isinstance(input_raw, (list, dict)) else (input_raw or "")
- output_val = json.dumps(output_raw) if isinstance(output_raw, (list, dict)) else (output_raw or "")
-
- globals_dict: dict[str, Any] = {
- "input": input_val,
- "output": output_val,
- "properties": properties,
- "event": {
- "uuid": event_data.get("uuid", ""),
- "event": event_type,
- "distinct_id": event_data.get("distinct_id", ""),
- },
- }
-
- try:
- response = execute_bytecode(
- bytecode,
- globals=globals_dict,
- timeout=timedelta(seconds=5),
- team=None,
- )
- except HogVMRuntimeExceededException:
- return {"verdict": None, "reasoning": "", "error": "Execution timed out (5s limit exceeded)"}
- except HogVMMemoryExceededException:
- return {"verdict": None, "reasoning": "", "error": "Memory limit exceeded"}
- except HogVMException as e:
- return {"verdict": None, "reasoning": "", "error": f"Runtime error: {e}"}
- except Exception:
- logger.exception("Unexpected error executing Hog eval bytecode")
- return {"verdict": None, "reasoning": "", "error": "Unexpected error during evaluation"}
-
- reasoning = "\n".join(response.stdout) if response.stdout else ""
-
- if response.result is None and allows_na:
- return {"verdict": None, "applicable": False, "reasoning": reasoning, "error": None}
-
- if not isinstance(response.result, bool):
- hint = " (or null if N/A is enabled)" if allows_na else ""
- return {
- "verdict": None,
- "reasoning": reasoning,
- "error": f"Must return boolean{hint}, got {type(response.result).__name__}: {response.result}",
- }
-
- result: dict[str, Any] = {"verdict": response.result, "reasoning": reasoning, "error": None}
- if allows_na:
- result["applicable"] = True
- return result
-
-
-async def execute_hog_eval_activity(evaluation: dict[str, Any], event_data: dict[str, Any]) -> LLMJudgeResult:
- """Execute Hog code to evaluate the target event.
-
- Returns a strict subset of `LLMJudgeResult` (verdict, reasoning, allows_na, optionally
- applicable). The shared TypedDict lets both this activity and `execute_llm_judge_activity`
- feed `EmitEvaluationEventInputs.result` without a wider union — downstream code already
- branches on `evaluation_type` and `result.get("skipped")` before reading LLM-only keys.
- """
- if evaluation["evaluation_type"] != "hog":
- raise ApplicationError(
- f"Unsupported evaluation type: {evaluation['evaluation_type']}",
- non_retryable=True,
- )
-
- evaluation_config = evaluation.get("evaluation_config", {})
- bytecode = evaluation_config.get("bytecode")
- if not bytecode:
- raise ApplicationError("Missing bytecode in evaluation_config", non_retryable=True)
-
- output_config = evaluation.get("output_config", {})
- allows_na = output_config.get("allows_na", False)
-
- def _execute():
- return run_hog_eval(bytecode, event_data, allows_na=allows_na)
-
- result = await database_sync_to_async(_execute, thread_sensitive=False)()
-
- if result["error"]:
- raise ApplicationError(
- f"Hog evaluation error: {result['error']}",
- non_retryable=True,
- )
-
- activity_result: LLMJudgeResult = {
- "verdict": result["verdict"],
- "reasoning": result["reasoning"],
- "allows_na": allows_na,
- }
- if allows_na:
- activity_result["applicable"] = result.get("applicable", True)
-
- return activity_result
-
-
-@dataclass
-class EmitEvaluationEventInputs:
- evaluation: dict[str, Any]
- event_data: dict[str, Any]
- result: LLMJudgeResult
- start_time: datetime
-
- @property
- def properties_to_log(self) -> dict[str, Any]:
- return {
- "team_id": self.event_data.get("team_id"),
- "evaluation_id": self.evaluation.get("id"),
- }
-
-
-async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> None:
- """Emit $ai_evaluation event via capture_internal so it routes through the ingestion pipeline for cost calculation"""
- evaluation = inputs.evaluation
- event_data = inputs.event_data
- result = inputs.result
- start_time = inputs.start_time
-
- def _emit():
- try:
- team = Team.objects.get(id=event_data["team_id"])
- except Team.DoesNotExist:
- logger.exception("Team not found", team_id=event_data["team_id"])
- raise ValueError(f"Team {event_data['team_id']} not found")
-
- allows_na = result.get("allows_na", False)
-
- evaluation_type = evaluation.get("evaluation_type", "llm_judge")
-
- source_props = (
- json.loads(event_data["properties"])
- if isinstance(event_data["properties"], str)
- else event_data["properties"]
- )
-
- properties: dict[str, Any] = {
- # Evaluation-specific properties
- "$ai_evaluation_id": evaluation["id"],
- "$ai_evaluation_name": evaluation["name"],
- "$ai_evaluation_type": "online",
- "$ai_evaluation_runtime": evaluation_type,
- "$ai_evaluation_start_time": start_time.isoformat(),
- "$ai_evaluation_allows_na": allows_na,
- "$ai_evaluation_reasoning": result["reasoning"],
- "$ai_target_event_id": event_data["uuid"],
- "$ai_target_event_type": event_data["event"],
- "$ai_target_id": event_data["uuid"],
- "$ai_target_type": "generation_uuid",
- "$ai_trace_id": source_props.get("$ai_trace_id"),
- # Carry the trigger user's session_id from the source event so evals
- # can link back to the session recording that originated the trace.
- "$session_id": source_props.get("$session_id"),
- }
-
- for property_name in SOURCE_AI_PROPERTIES_TO_COPY:
- if source_props.get(property_name) is not None:
- properties[property_name] = source_props[property_name]
-
- if result.get("skipped"):
- properties["$ai_evaluation_skipped"] = True
- properties["$ai_evaluation_skip_reason"] = result.get("skip_reason")
-
- # LLM-specific properties: cost attribution and model info (not applicable for hog evals,
- # and skipped evaluations never made an API call so attributing them to a model would
- # pollute cost dashboards with phantom calls).
- if evaluation_type != "hog" and not result.get("skipped"):
- properties["$ai_model"] = result.get("model", DEFAULT_JUDGE_MODEL)
- properties["$ai_provider"] = result.get("provider", "openai")
- properties["$ai_input_tokens"] = result.get("input_tokens", 0)
- properties["$ai_output_tokens"] = result.get("output_tokens", 0)
- properties["$ai_evaluation_model"] = result.get("model", DEFAULT_JUDGE_MODEL)
- properties["$ai_evaluation_provider"] = result.get("provider", "openai")
- properties["$ai_evaluation_key_type"] = "byok" if result.get("is_byok") else "posthog"
- properties["$ai_evaluation_key_id"] = result.get("key_id")
-
- # Handle result based on allows_na config
- if allows_na:
- applicable = result.get("applicable", True)
- properties["$ai_evaluation_applicable"] = applicable
- if applicable:
- properties["$ai_evaluation_result"] = result["verdict"]
- else:
- properties["$ai_evaluation_result"] = result["verdict"]
-
- event_timestamp = datetime.now(UTC)
-
- capture_result = capture_internal_routed(
- token=team.api_token,
- event_name="$ai_evaluation",
- event_source="llm_analytics_evaluation",
- distinct_id=event_data["distinct_id"],
- timestamp=event_timestamp,
- properties=properties,
- process_person_profile=True,
- )
- capture_result.raise_for_status()
-
- try:
- await database_sync_to_async(_emit, thread_sensitive=False)()
- increment_emit_event_outcome("success")
- except Exception:
- increment_emit_event_outcome("failed")
- raise
-
-
-@dataclass
-class EmitInternalTelemetryInputs:
- evaluation: dict[str, Any]
- team_id: int
- result: LLMJudgeResult
-
- @property
- def properties_to_log(self) -> dict[str, Any]:
- return {
- "team_id": self.team_id,
- "evaluation_id": self.evaluation.get("id"),
- }
-
-
-async def emit_internal_telemetry_activity(inputs: EmitInternalTelemetryInputs) -> None:
- """Emit telemetry event to PostHog org for internal tracking"""
- from posthog.tasks.usage_report import get_ph_client
-
- evaluation = inputs.evaluation
- team_id = inputs.team_id
- result = inputs.result
-
- def _emit_telemetry():
- team = Team.objects.get(id=team_id)
- organization_id = str(team.organization_id)
-
- ph_client = get_ph_client(sync_mode=True)
- ph_client.capture(
- distinct_id=f"org-{organization_id}",
- event="llm analytics evaluation executed",
- properties={
- "evaluation_id": evaluation["id"],
- "team_id": team_id,
- "model": result.get("model", DEFAULT_JUDGE_MODEL),
- "provider": result.get("provider", "openai"),
- "input_tokens": result.get("input_tokens", 0),
- "output_tokens": result.get("output_tokens", 0),
- "total_tokens": result.get("total_tokens", 0),
- "verdict": result["verdict"],
- },
- groups={"organization": organization_id, "instance": settings.SITE_URL},
- )
- ph_client.flush()
-
- await database_sync_to_async(_emit_telemetry, thread_sensitive=False)()
-
-
@temporalio.workflow.defn(name="run-evaluation")
class RunEvaluationWorkflow(PostHogWorkflow):
@staticmethod
@@ -1153,22 +113,26 @@ class RunEvaluationWorkflow(PostHogWorkflow):
evaluation_type = evaluation.get("evaluation_type", "llm_judge")
- # Activity 2: Execute evaluation based on type
if evaluation_type == "hog":
- # Hog evaluations are deterministic — don't retry
result = await temporalio.workflow.execute_activity(
execute_hog_eval_activity,
args=[evaluation, inputs.event_data],
schedule_to_close_timeout=timedelta(seconds=30),
retry_policy=RetryPolicy(maximum_attempts=1),
)
- else:
- # LLM judge evaluation
+ elif evaluation_type == "sentiment":
+ result = await temporalio.workflow.execute_activity(
+ execute_sentiment_eval_activity,
+ args=[evaluation, inputs.event_data],
+ schedule_to_close_timeout=timedelta(seconds=120),
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ elif evaluation_type == "llm_judge":
try:
result = await temporalio.workflow.execute_activity(
execute_llm_judge_activity,
ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=inputs.event_data),
- schedule_to_close_timeout=timedelta(minutes=6), # > SDK timeout (300s) to allow graceful handling
+ schedule_to_close_timeout=timedelta(minutes=6),
retry_policy=LLM_JUDGE_RETRY_POLICY,
)
except temporalio.exceptions.ActivityError as e:
@@ -1176,7 +140,6 @@ class RunEvaluationWorkflow(PostHogWorkflow):
details = e.cause.details[0]
error_type = details.get("error_type")
- # Handle skippable errors - return success with skip info
if error_type in ("trial_limit_reached", "key_invalid", "parse_error", "model_not_allowed"):
if error_type in ("trial_limit_reached", "model_not_allowed"):
await temporalio.workflow.execute_activity(
@@ -1186,8 +149,6 @@ class RunEvaluationWorkflow(PostHogWorkflow):
retry_policy=RetryPolicy(maximum_attempts=2),
)
if error_type == "trial_limit_reached":
- # Trial exhaustion affects all trial-using evals on the team — stick with
- # the aggregate email that lists every impacted eval.
if temporalio.workflow.patched("trial-usage-email"):
try:
await temporalio.workflow.execute_activity(
@@ -1203,8 +164,6 @@ class RunEvaluationWorkflow(PostHogWorkflow):
team_id=evaluation["team_id"],
)
else:
- # model_not_allowed is per-eval — send the targeted email with a
- # per-eval recovery path (pick a supported model for this eval).
if temporalio.workflow.patched("eval-disabled-email"):
model = details.get("model", "the selected model")
try:
@@ -1241,7 +200,6 @@ class RunEvaluationWorkflow(PostHogWorkflow):
}
return skip_result
- # Update key state for API-related errors
key_id = details.get("key_id")
if key_id and error_type in ("auth_error", "permission_error", "quota_error", "rate_limit"):
new_state = (
@@ -1255,9 +213,6 @@ class RunEvaluationWorkflow(PostHogWorkflow):
)
raise
- # Increment trial eval counter if using PostHog key (LLM judge only — no cost for hog evals).
- # Skipped evaluations (e.g. errored source trace) never made an API call, so they do not
- # consume trial quota.
if not result.get("is_byok") and not result.get("skipped"):
threshold_pct = await temporalio.workflow.execute_activity(
increment_trial_eval_count_activity,
@@ -1277,14 +232,17 @@ class RunEvaluationWorkflow(PostHogWorkflow):
retry_policy=RetryPolicy(maximum_attempts=2),
)
except Exception:
- # Email failure should not fail the evaluation workflow
temporalio.workflow.logger.exception(
"Failed to send trial usage email",
team_id=evaluation["team_id"],
threshold_pct=threshold_pct,
)
+ else:
+ raise ApplicationError(
+ f"Unsupported evaluation type: {evaluation_type}",
+ non_retryable=True,
+ )
- # Activity 4: Emit evaluation event
try:
await temporalio.workflow.execute_activity(
emit_evaluation_event_activity,
@@ -1301,11 +259,7 @@ class RunEvaluationWorkflow(PostHogWorkflow):
increment_errors("emit_evaluation_event_failed", provider=result.get("provider"))
raise
- # Activity 5: Emit internal telemetry (fire-and-forget). Internal telemetry tracks model,
- # provider, and token usage on the PostHog org for cost attribution; skipped evaluations
- # never made an API call, so emitting a phantom record with `verdict=False` and zero
- # tokens would pollute that data.
- if not result.get("skipped"):
+ if evaluation_type == "llm_judge" and not result.get("skipped"):
await temporalio.workflow.execute_activity(
emit_internal_telemetry_activity,
EmitInternalTelemetryInputs(
@@ -1316,11 +270,7 @@ class RunEvaluationWorkflow(PostHogWorkflow):
schedule_to_close_timeout=timedelta(seconds=30),
)
- # Emit signal when eval judge verdict is true (fire-and-forget).
- # v2: dedicated workflow on VIDEO_EXPORT_TASK_QUEUE (signals worker).
- # v1: legacy activity on evals queue, kept for in-flight workflows during migration.
- # Always fails due to missing API key on llma worker
- if result.get("verdict") is True and result.get("reasoning"):
+ if evaluation_type == "llm_judge" and result.get("verdict") is True and result.get("reasoning"):
event_uuid = inputs.event_data.get("uuid", "")
properties = inputs.event_data.get("properties", {})
if isinstance(properties, str):
@@ -1351,14 +301,12 @@ class RunEvaluationWorkflow(PostHogWorkflow):
execution_timeout=timedelta(minutes=5),
)
except Exception:
- # Don't fail the workflow if signal emission fails
temporalio.workflow.logger.exception(
"Failed to start eval signal workflow",
evaluation_id=evaluation["id"],
team_id=evaluation["team_id"],
)
elif temporalio.workflow.patched("emit-eval-signal-v1"):
- # Legacy path for in-flight v1 workflows — remove once all v1 executions complete
try:
await temporalio.workflow.execute_activity(
emit_eval_signal_activity,
@@ -1374,16 +322,14 @@ class RunEvaluationWorkflow(PostHogWorkflow):
)
workflow_result: WorkflowResult = {
- "verdict": result["verdict"],
"reasoning": result["reasoning"],
"evaluation_id": evaluation["id"],
"evaluation_type": evaluation_type,
"is_byok": result.get("is_byok", False),
"skipped": result.get("skipped", False),
}
- # Match the shape of the existing workflow-level skip path (around the `error_type` branch
- # above) so consumers can group skipped workflows by reason without special-casing the
- # source of the skip.
+ if "verdict" in result:
+ workflow_result["verdict"] = result["verdict"]
if result.get("skipped"):
skip_reason = result.get("skip_reason")
if skip_reason is not None:
diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.py
index 650f47000908..0b8ba90607e0 100644
--- a/posthog/temporal/ai_observability/run_tagger.py
+++ b/posthog/temporal/ai_observability/run_tagger.py
@@ -13,8 +13,14 @@ from temporalio.exceptions import ApplicationError
from posthog.api.capture_dispatch import capture_internal_routed
from posthog.models.team import Team
from posthog.sync import database_sync_to_async
+from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io
+from posthog.temporal.ai_observability.evaluation_workflow_activities import (
+ SendTrialUsageEmailInputs,
+ increment_trial_eval_count_activity,
+ send_trial_usage_email_activity,
+ update_key_state_activity,
+)
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages
-from posthog.temporal.ai_observability.run_evaluation import extract_event_io
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.scoped import scoped_temporal
@@ -408,8 +414,8 @@ def run_hog_tagger(bytecode: list, event_data: dict[str, Any], valid_tag_names:
event_type = event_data["event"]
input_raw, output_raw = extract_event_io(event_type, properties)
- input_val = json.dumps(input_raw) if isinstance(input_raw, (list, dict)) else (input_raw or "")
- output_val = json.dumps(output_raw) if isinstance(output_raw, (list, dict)) else (output_raw or "")
+ input_val = json.dumps(input_raw) if isinstance(input_raw, list | dict) else (input_raw or "")
+ output_val = json.dumps(output_raw) if isinstance(output_raw, list | dict) else (output_raw or "")
globals_dict: dict[str, Any] = {
"input": input_val,
@@ -673,11 +679,6 @@ class RunTaggerWorkflow(PostHogWorkflow):
)
if temporalio.workflow.patched("trial-usage-email"):
try:
- from posthog.temporal.ai_observability.run_evaluation import (
- SendTrialUsageEmailInputs,
- send_trial_usage_email_activity,
- )
-
await temporalio.workflow.execute_activity(
send_trial_usage_email_activity,
SendTrialUsageEmailInputs(team_id=tagger["team_id"], threshold_pct=100),
@@ -699,8 +700,6 @@ class RunTaggerWorkflow(PostHogWorkflow):
}
# Update key state for API-related errors
- from posthog.temporal.ai_observability.run_evaluation import update_key_state_activity
-
key_id = details.get("key_id")
if key_id and error_type in ("auth_error", "permission_error", "quota_error", "rate_limit"):
new_state = (
@@ -716,12 +715,6 @@ class RunTaggerWorkflow(PostHogWorkflow):
# Increment trial counter if using PostHog key (LLM taggers only — Hog taggers have no LLM cost)
if tagger_type != "hog" and not result.get("is_byok"):
- from posthog.temporal.ai_observability.run_evaluation import (
- SendTrialUsageEmailInputs,
- increment_trial_eval_count_activity,
- send_trial_usage_email_activity,
- )
-
threshold_pct = await temporalio.workflow.execute_activity(
increment_trial_eval_count_activity,
tagger["team_id"],
diff --git a/posthog/temporal/ai_observability/test_metrics.py b/posthog/temporal/ai_observability/test_metrics.py
index 955aaa83cf0f..05374e5c358d 100644
--- a/posthog/temporal/ai_observability/test_metrics.py
+++ b/posthog/temporal/ai_observability/test_metrics.py
@@ -98,6 +98,7 @@ class TestActivityTypes:
"fetch_evaluation_activity",
"execute_llm_judge_activity",
"execute_hog_eval_activity",
+ "execute_sentiment_eval_activity",
"emit_evaluation_event_activity",
"emit_internal_telemetry_activity",
"increment_trial_eval_count_activity",
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index 90b2f2c69ccd..b25dd4c2f932 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -11,6 +11,7 @@ from parameterized import parameterized
from temporalio.exceptions import ApplicationError
from posthog.models import Organization, Team
+from posthog.temporal.ai_observability.sentiment.schema import SentimentResult
from products.ai_observability.backend.llm.errors import StructuredOutputParseError
from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
@@ -21,8 +22,8 @@ from .run_evaluation import (
BooleanEvalResult,
BooleanWithNAEvalResult,
EmitEvaluationEventInputs,
+ EvaluationActivityResult,
ExecuteLLMJudgeInputs,
- LLMJudgeResult,
RunEvaluationInputs,
RunEvaluationWorkflow,
SendEvaluationDisabledEmailInputs,
@@ -31,6 +32,7 @@ from .run_evaluation import (
emit_evaluation_event_activity,
execute_hog_eval_activity,
execute_llm_judge_activity,
+ execute_sentiment_eval_activity,
extract_event_tools,
fetch_evaluation_activity,
increment_trial_eval_count_activity,
@@ -83,7 +85,9 @@ class TestRunEvaluationWorkflow:
event_data=create_mock_event_data(team.id),
)
- with patch("posthog.temporal.ai_observability.run_evaluation.Evaluation.objects.get") as mock_get:
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_workflow_activities.Evaluation.objects.get"
+ ) as mock_get:
mock_evaluation = MagicMock()
mock_evaluation.id = evaluation.id
mock_evaluation.name = "Test Evaluation"
@@ -128,7 +132,7 @@ class TestRunEvaluationWorkflow:
)
# Mock unified Client response
- with patch("posthog.temporal.ai_observability.run_evaluation.Client") as mock_client_class:
+ with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:
mock_client = MagicMock()
mock_client_class.return_value = mock_client
@@ -159,7 +163,8 @@ class TestRunEvaluationWorkflow:
event_data = create_mock_event_data(team.id, properties={})
- result: LLMJudgeResult = {
+ result: EvaluationActivityResult = {
+ "result_type": "boolean",
"verdict": True,
"reasoning": "Test passed",
"allows_na": False,
@@ -169,8 +174,12 @@ class TestRunEvaluationWorkflow:
"output_tokens": 18,
}
- with patch("posthog.temporal.ai_observability.run_evaluation.Team.objects.get") as mock_team_get:
- with patch("posthog.temporal.ai_observability.run_evaluation.capture_internal_routed") as mock_capture:
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get"
+ ) as mock_team_get:
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_routed"
+ ) as mock_capture:
mock_team_get.return_value = team
mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())
@@ -190,6 +199,7 @@ class TestRunEvaluationWorkflow:
assert call_kwargs["process_person_profile"] is True
props = call_kwargs["properties"]
assert props["$ai_evaluation_result"] is True
+ assert props["$ai_evaluation_result_type"] == "boolean"
assert props["$ai_model"] == "gpt-5-mini"
assert props["$ai_provider"] == "openai"
assert props["$ai_input_tokens"] == 42
@@ -213,7 +223,8 @@ class TestRunEvaluationWorkflow:
event_data = create_mock_event_data(team.id, properties={})
- result: LLMJudgeResult = {
+ result: EvaluationActivityResult = {
+ "result_type": "boolean",
"verdict": False,
"reasoning": "Source trace errored before producing output; evaluation skipped.",
"input_tokens": 0,
@@ -226,8 +237,12 @@ class TestRunEvaluationWorkflow:
"skip_reason": "trace_errored",
}
- with patch("posthog.temporal.ai_observability.run_evaluation.Team.objects.get") as mock_team_get:
- with patch("posthog.temporal.ai_observability.run_evaluation.capture_internal_routed") as mock_capture:
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get"
+ ) as mock_team_get:
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_routed"
+ ) as mock_capture:
mock_team_get.return_value = team
mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())
@@ -244,6 +259,7 @@ class TestRunEvaluationWorkflow:
assert props["$ai_evaluation_skipped"] is True
assert props["$ai_evaluation_skip_reason"] == "trace_errored"
+ assert props["$ai_evaluation_result_type"] == "boolean"
assert props["$ai_evaluation_result"] is False
for cost_key in (
"$ai_model",
@@ -257,6 +273,60 @@ class TestRunEvaluationWorkflow:
):
assert cost_key not in props, f"{cost_key} must be omitted for skipped evaluations"
+ @pytest.mark.asyncio
+ @pytest.mark.django_db(transaction=True)
+ async def test_emit_evaluation_event_activity_sentiment_omits_boolean_and_cost_props(self, setup_data):
+ evaluation_obj = setup_data["evaluation"]
+ team = setup_data["team"]
+
+ evaluation = {
+ "id": str(evaluation_obj.id),
+ "name": "Sentiment Evaluation",
+ "evaluation_type": "sentiment",
+ }
+ event_data = create_mock_event_data(team.id, properties={"$ai_trace_id": "trace-1"})
+ result: EvaluationActivityResult = {
+ "result_type": "sentiment",
+ "reasoning": "Classified 1 user message as positive.",
+ "sentiment_label": "positive",
+ "sentiment_score": 0.9,
+ "sentiment_scores": {"positive": 0.9, "neutral": 0.08, "negative": 0.02},
+ "sentiment_messages": {
+ "0": {"label": "positive", "score": 0.9, "scores": {"positive": 0.9, "neutral": 0.08, "negative": 0.02}}
+ },
+ "sentiment_message_count": 1,
+ }
+
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get"
+ ) as mock_team_get:
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_routed"
+ ) as mock_capture:
+ mock_team_get.return_value = team
+ mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())
+
+ await emit_evaluation_event_activity(
+ EmitEvaluationEventInputs(
+ evaluation=evaluation,
+ event_data=event_data,
+ result=result,
+ start_time=datetime(2024, 1, 1, 12, 0, 0),
+ )
+ )
+
+ props = mock_capture.call_args[1]["properties"]
+
+ assert props["$ai_evaluation_runtime"] == "sentiment"
+ assert props["$ai_evaluation_result_type"] == "sentiment"
+ assert props["$ai_sentiment_label"] == "positive"
+ assert props["$ai_sentiment_score"] == 0.9
+ assert props["$ai_sentiment_message_count"] == 1
+ assert "$ai_evaluation_result" not in props
+ assert "$ai_evaluation_allows_na" not in props
+ assert "$ai_model" not in props
+ assert "$ai_provider" not in props
+
def test_parse_inputs(self):
"""Test that parse_inputs correctly parses workflow inputs"""
event_data = create_mock_event_data(team_id=1)
@@ -291,7 +361,7 @@ class TestRunEvaluationWorkflow:
},
)
- with patch("posthog.temporal.ai_observability.run_evaluation.Client") as mock_client_class:
+ with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:
mock_client = MagicMock()
mock_client_class.return_value = mock_client
@@ -333,7 +403,7 @@ class TestRunEvaluationWorkflow:
},
)
- with patch("posthog.temporal.ai_observability.run_evaluation.Client") as mock_client_class:
+ with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:
mock_client = MagicMock()
mock_client_class.return_value = mock_client
@@ -387,7 +457,7 @@ class TestRunEvaluationWorkflow:
},
)
- with patch("posthog.temporal.ai_observability.run_evaluation.Client") as mock_client_class:
+ with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:
result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))
mock_client_class.assert_not_called()
@@ -429,7 +499,7 @@ class TestRunEvaluationWorkflow:
},
)
- with patch("posthog.temporal.ai_observability.run_evaluation.Client") as mock_client_class:
+ with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:
result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))
mock_client_class.assert_not_called()
@@ -473,7 +543,7 @@ class TestRunEvaluationWorkflow:
},
)
- with patch("posthog.temporal.ai_observability.run_evaluation.Client") as mock_client_class:
+ with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:
mock_client = MagicMock()
mock_client_class.return_value = mock_client
@@ -503,15 +573,20 @@ class TestRunEvaluationWorkflow:
event_data = create_mock_event_data(team.id, properties={})
- result: LLMJudgeResult = {
+ result: EvaluationActivityResult = {
+ "result_type": "boolean",
"verdict": True,
"reasoning": "Test passed",
"applicable": True,
"allows_na": True,
}
- with patch("posthog.temporal.ai_observability.run_evaluation.Team.objects.get") as mock_team_get:
- with patch("posthog.temporal.ai_observability.run_evaluation.capture_internal_routed") as mock_capture:
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get"
+ ) as mock_team_get:
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_routed"
+ ) as mock_capture:
mock_team_get.return_value = team
mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())
@@ -527,6 +602,7 @@ class TestRunEvaluationWorkflow:
mock_capture.assert_called_once()
props = mock_capture.call_args[1]["properties"]
assert props["$ai_evaluation_result"] is True
+ assert props["$ai_evaluation_result_type"] == "boolean"
assert props["$ai_evaluation_applicable"] is True
assert props["$ai_evaluation_allows_na"] is True
@@ -544,15 +620,20 @@ class TestRunEvaluationWorkflow:
event_data = create_mock_event_data(team.id, properties={})
- result: LLMJudgeResult = {
+ result: EvaluationActivityResult = {
+ "result_type": "boolean",
"verdict": None,
"reasoning": "Not applicable",
"applicable": False,
"allows_na": True,
}
- with patch("posthog.temporal.ai_observability.run_evaluation.Team.objects.get") as mock_team_get:
- with patch("posthog.temporal.ai_observability.run_evaluation.capture_internal_routed") as mock_capture:
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get"
+ ) as mock_team_get:
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal_routed"
+ ) as mock_capture:
mock_team_get.return_value = team
mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())
@@ -567,6 +648,7 @@ class TestRunEvaluationWorkflow:
mock_capture.assert_called_once()
props = mock_capture.call_args[1]["properties"]
+ assert props["$ai_evaluation_result_type"] == "boolean"
assert "$ai_evaluation_result" not in props
assert props["$ai_evaluation_applicable"] is False
assert props["$ai_evaluation_allows_na"] is True
@@ -623,7 +705,7 @@ class TestRunEvaluationWorkflow:
},
)
- with patch("posthog.temporal.ai_observability.run_evaluation.Client") as mock_client_class:
+ with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:
mock_client = MagicMock()
mock_client_class.return_value = mock_client
@@ -660,7 +742,7 @@ class TestRunEvaluationWorkflow:
},
)
- with patch("posthog.temporal.ai_observability.run_evaluation.Client") as mock_client_class:
+ with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:
mock_client = MagicMock()
mock_client_class.return_value = mock_client
mock_client.complete.side_effect = StructuredOutputParseError(
@@ -700,8 +782,8 @@ class TestRunEvaluationWorkflow:
event_data = create_mock_event_data(team.id)
with (
- patch("posthog.temporal.ai_observability.run_evaluation.Client") as mock_client_class,
- patch("posthog.temporal.ai_observability.run_evaluation.increment_errors") as mock_increment_errors,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.increment_errors") as mock_increment_errors,
):
mock_client = MagicMock()
mock_client_class.return_value = mock_client
@@ -911,6 +993,76 @@ class TestExecuteHogEvalActivity:
assert result["verdict"] is True
+class TestExecuteSentimentEvalActivity:
+ @pytest.mark.asyncio
+ @pytest.mark.django_db(transaction=True)
+ async def test_sentiment_eval_classifies_user_messages(self, setup_data):
+ team = setup_data["team"]
+ evaluation = {
+ "id": str(setup_data["evaluation"].id),
+ "name": "Sentiment Eval",
+ "evaluation_type": "sentiment",
+ "evaluation_config": {"source": "user_messages"},
+ "output_type": "sentiment",
+ "output_config": {},
+ "team_id": team.id,
+ }
+ event_data = create_mock_event_data(
+ team.id,
+ properties={
+ "$ai_input": [
+ {"role": "system", "content": "Be helpful."},
+ {"role": "user", "content": "I love this answer."},
+ {"role": "assistant", "content": "Thanks!"},
+ ],
+ "$ai_output": "Thanks!",
+ },
+ )
+
+ classification = SentimentResult(
+ label="positive",
+ score=0.9,
+ scores={"positive": 0.9, "neutral": 0.08, "negative": 0.02},
+ )
+ with patch(
+ "posthog.temporal.ai_observability.sentiment.model.classify", return_value=[classification]
+ ) as mock_classify:
+ result = await execute_sentiment_eval_activity(evaluation, event_data)
+
+ mock_classify.assert_called_once_with(["I love this answer."])
+ assert "verdict" not in result
+ assert result["sentiment_label"] == "positive"
+ assert result["sentiment_score"] == 0.9
+ assert result["sentiment_message_count"] == 1
+ assert result["sentiment_messages"]["1"]["label"] == "positive"
+
+ @pytest.mark.asyncio
+ @pytest.mark.django_db(transaction=True)
+ async def test_sentiment_eval_defaults_to_neutral_without_user_messages(self, setup_data):
+ team = setup_data["team"]
+ evaluation = {
+ "id": str(setup_data["evaluation"].id),
+ "name": "Sentiment Eval",
+ "evaluation_type": "sentiment",
+ "evaluation_config": {"source": "user_messages"},
+ "output_type": "sentiment",
+ "output_config": {},
+ "team_id": team.id,
+ }
+ event_data = create_mock_event_data(
+ team.id,
+ properties={"$ai_input": [{"role": "assistant", "content": "Hello"}]},
+ )
+
+ with patch("posthog.temporal.ai_observability.sentiment.model.classify") as mock_classify:
+ result = await execute_sentiment_eval_activity(evaluation, event_data)
+
+ mock_classify.assert_not_called()
+ assert "verdict" not in result
+ assert result["sentiment_label"] == "neutral"
+ assert result["sentiment_message_count"] == 0
+
+
class TestEvalResultModels:
def test_boolean_eval_result(self):
"""Test BooleanEvalResult model"""
@@ -1312,21 +1464,18 @@ class TestJudgePromptAssembly:
regressions in section ordering, tool catalog inclusion, and tool_call_id
correlation that the unit tests for the helpers can't catch alone."""
- @pytest.mark.django_db(transaction=True)
- def test_prompt_contains_input_tools_and_output_sections_in_order(self, setup_data):
- evaluation_obj = setup_data["evaluation"]
- team = setup_data["team"]
+ def test_prompt_contains_input_tools_and_output_sections_in_order(self):
evaluation = {
- "id": str(evaluation_obj.id),
+ "id": "eval-123",
"name": "Test Evaluation",
"evaluation_type": "llm_judge",
"evaluation_config": {"prompt": "Did the agent call the right tool?"},
"output_type": "boolean",
"output_config": {},
- "team_id": team.id,
+ "team_id": 1,
}
event_data = create_mock_event_data(
- team.id,
+ 1,
properties={
"$ai_input": [
{"role": "user", "content": "Send the welcome email."},
@@ -1351,7 +1500,16 @@ class TestJudgePromptAssembly:
},
)
- with patch("posthog.temporal.ai_observability.run_evaluation.Client") as mock_client_class:
+ with (
+ patch(
+ "posthog.temporal.ai_observability.evaluation_llm_judge.EvaluationConfig.objects.get_or_create"
+ ) as mock_get_or_create,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class,
+ ):
+ mock_get_or_create.return_value = (
+ MagicMock(active_provider_key=None, trial_evals_used=0, trial_eval_limit=100),
+ False,
+ )
mock_client = MagicMock()
mock_client_class.return_value = mock_client
mock_response = MagicMock()
@@ -1378,28 +1536,34 @@ class TestJudgePromptAssembly:
assert "- send_email: Send an email." in user_prompt
assert "- lookup_user: Look up a user." in user_prompt
- @pytest.mark.django_db(transaction=True)
- def test_prompt_omits_tools_section_when_catalog_absent(self, setup_data):
- evaluation_obj = setup_data["evaluation"]
- team = setup_data["team"]
+ def test_prompt_omits_tools_section_when_catalog_absent(self):
evaluation = {
- "id": str(evaluation_obj.id),
+ "id": "eval-123",
"name": "Test Evaluation",
"evaluation_type": "llm_judge",
"evaluation_config": {"prompt": "Is this correct?"},
"output_type": "boolean",
"output_config": {},
- "team_id": team.id,
+ "team_id": 1,
}
event_data = create_mock_event_data(
- team.id,
+ 1,
properties={
"$ai_input": [{"role": "user", "content": "What is 2+2?"}],
"$ai_output_choices": [{"role": "assistant", "content": "4"}],
},
)
- with patch("posthog.temporal.ai_observability.run_evaluation.Client") as mock_client_class:
+ with (
+ patch(
+ "posthog.temporal.ai_observability.evaluation_llm_judge.EvaluationConfig.objects.get_or_create"
+ ) as mock_get_or_create,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class,
+ ):
+ mock_get_or_create.return_value = (
+ MagicMock(active_provider_key=None, trial_evals_used=0, trial_eval_limit=100),
+ False,
+ )
mock_client = MagicMock()
mock_client_class.return_value = mock_client
mock_response = MagicMock()
diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.py
index 41cedf9d4ba9..7bc398305eac 100644
--- a/posthog/temporal/tests/ai/test_module_integrity.py
+++ b/posthog/temporal/tests/ai/test_module_integrity.py
@@ -359,6 +359,7 @@ class TestAIObservabilityModuleIntegrity:
"update_key_state_activity",
"execute_llm_judge_activity",
"execute_hog_eval_activity",
+ "execute_sentiment_eval_activity",
"emit_evaluation_event_activity",
"emit_internal_telemetry_activity",
"emit_eval_signal_activity",
diff --git a/products/ai_observability/backend/api/evaluation_reports.py b/products/ai_observability/backend/api/evaluation_reports.py
index e3d8220924a6..d8dceb5fe938 100644
--- a/products/ai_observability/backend/api/evaluation_reports.py
+++ b/products/ai_observability/backend/api/evaluation_reports.py
@@ -21,6 +21,10 @@ from posthog.models.integration import Integration
from posthog.permissions import AccessControlPermission
from products.ai_observability.backend.api.metrics import llma_track_latency
+from products.ai_observability.backend.models.evaluation_configs import (
+ REPORTABLE_OUTPUT_TYPES,
+ evaluation_supports_reports,
+)
from products.ai_observability.backend.models.evaluation_reports import EvaluationReport, EvaluationReportRun
from products.workflows.backend.utils.rrule_utils import validate_rrule
@@ -132,6 +136,8 @@ class EvaluationReportSerializer(serializers.ModelSerializer):
team = self.context["get_team"]()
if value.team_id != team.id:
raise serializers.ValidationError("Evaluation does not belong to this team.")
+ if not evaluation_supports_reports(value.output_type):
+ raise serializers.ValidationError("Reports are only supported for boolean evaluations.")
return value
def validate_rrule(self, value: str) -> str:
@@ -292,7 +298,9 @@ class EvaluationReportViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewse
return super().get_serializer_class()
def safely_get_queryset(self, queryset: QuerySet[EvaluationReport]) -> QuerySet[EvaluationReport]:
- queryset = queryset.filter(team_id=self.team_id).order_by("-created_at")
+ queryset = queryset.filter(team_id=self.team_id, evaluation__output_type__in=REPORTABLE_OUTPUT_TYPES).order_by(
+ "-created_at"
+ )
if self.action not in ("update", "partial_update"):
queryset = queryset.filter(deleted=False)
@@ -420,6 +428,11 @@ class EvaluationReportViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewse
def generate(self, request: Request, **kwargs) -> Response:
"""Trigger immediate report generation."""
report = self.get_object()
+ if not evaluation_supports_reports(report.evaluation.output_type):
+ return Response(
+ {"error": "Reports are only supported for boolean evaluations."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
try:
from posthog.temporal.ai_observability.eval_reports.constants import GENERATE_EVAL_REPORT_WORKFLOW_NAME
diff --git a/products/ai_observability/backend/api/evaluation_runs.py b/products/ai_observability/backend/api/evaluation_runs.py
index 6765d4b9547f..26f5061445b7 100644
--- a/products/ai_observability/backend/api/evaluation_runs.py
+++ b/products/ai_observability/backend/api/evaluation_runs.py
@@ -30,6 +30,19 @@ from ..models.evaluations import Evaluation
logger = structlog.get_logger(__name__)
+EVALUATION_WORKFLOW_PREFIXES = {
+ "hog": "llma-hog-eval",
+ "llm_judge": "llma-llm-eval",
+ "sentiment": "llma-sentiment-eval",
+}
+
+
+def _evaluation_workflow_prefix(evaluation_type: str) -> str:
+ try:
+ return EVALUATION_WORKFLOW_PREFIXES[evaluation_type]
+ except KeyError:
+ raise ValueError(f"Unsupported evaluation type for workflow prefix: {evaluation_type}") from None
+
class EvaluationRunRequestSerializer(serializers.Serializer):
evaluation_id = serializers.UUIDField(required=True, help_text="UUID of the evaluation to run.")
@@ -158,7 +171,7 @@ class EvaluationRunViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
)
# Generate unique workflow ID
- prefix = "llma-hog-eval" if evaluation.evaluation_type == "hog" else "llma-llm-eval"
+ prefix = _evaluation_workflow_prefix(evaluation.evaluation_type)
workflow_id = f"{prefix}-{evaluation_id}-{target_event_id}-manual-{int(time.time() * 1000)}"
# Start Temporal workflow
diff --git a/products/ai_observability/backend/api/evaluation_summary.py b/products/ai_observability/backend/api/evaluation_summary.py
index cf7a8d2ae0e9..44225f70263b 100644
--- a/products/ai_observability/backend/api/evaluation_summary.py
+++ b/products/ai_observability/backend/api/evaluation_summary.py
@@ -1,5 +1,5 @@
"""
-Django REST API endpoint for LLM evaluation results summarization.
+Django REST API endpoint for evaluation results summarization.
This ViewSet provides AI-powered summarization of evaluation results,
identifying patterns in passing and failing evaluations.
@@ -219,7 +219,7 @@ def _fetch_evaluation_runs(
class LLMEvaluationSummaryViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"""
- ViewSet for LLM evaluation results summarization.
+ ViewSet for evaluation results summarization.
Provides AI-powered analysis of evaluation runs to identify patterns
in passing and failing evaluations. Fetches data server-side by ID
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index 300eafdb9b7a..e5635eecc94c 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -1,5 +1,5 @@
import json
-from typing import Any
+from typing import Any, cast
from django.db import transaction
from django.db.models import Q, QuerySet
@@ -19,13 +19,22 @@ from posthog.api.monitoring import monitor
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.event_usage import report_user_action
+from posthog.models import User
from posthog.permissions import AccessControlPermission
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages
from posthog.temporal.ai_observability.run_evaluation import extract_event_io, run_hog_eval
+from ..feature_flags import is_sentiment_evaluations_enabled
from ..models.evaluation_config import EvaluationConfig
-from ..models.evaluation_configs import validate_evaluation_configs
+from ..models.evaluation_configs import (
+ EvaluationType,
+ OutputType,
+ evaluation_supports_reports,
+ evaluation_uses_model_configuration,
+ get_evaluation_config_content_key,
+ validate_evaluation_configs,
+)
from ..models.evaluation_reports import EvaluationReport
from ..models.evaluations import Evaluation
from ..models.model_configuration import LLMModelConfiguration
@@ -64,6 +73,19 @@ logger = structlog.get_logger(__name__)
},
"additionalProperties": False,
},
+ {
+ "type": "object",
+ "title": "Sentiment config",
+ "properties": {
+ "source": {
+ "type": "string",
+ "enum": ["user_messages"],
+ "description": "Classify sentiment from user messages in the generation input.",
+ "default": "user_messages",
+ }
+ },
+ "additionalProperties": False,
+ },
]
}
)
@@ -132,7 +154,10 @@ class EvaluationSerializer(serializers.ModelSerializer):
model_configuration = ModelConfigurationSerializer(required=False, allow_null=True)
evaluation_config = _EvaluationConfigField(
required=False,
- help_text="Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}.",
+ help_text=(
+ "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; "
+ "for 'sentiment': {source: 'user_messages'}."
+ ),
)
output_config = _OutputConfigField(
required=False,
@@ -176,23 +201,59 @@ class EvaluationSerializer(serializers.ModelSerializer):
"description": {"help_text": "Optional description of what this evaluation checks."},
"enabled": {"help_text": "Whether the evaluation runs automatically on new $ai_generation events."},
"evaluation_type": {
- "help_text": "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code."
+ "help_text": (
+ "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; "
+ "'sentiment' classifies user-message sentiment."
+ )
+ },
+ "output_type": {
+ "help_text": (
+ "Output format. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis."
+ )
},
- "output_type": {"help_text": "Output format. Currently only 'boolean' is supported."},
"deleted": {"help_text": "Set to true to soft-delete the evaluation."},
}
def validate(self, data):
- if "evaluation_config" in data and "output_config" in data:
- evaluation_type = data.get("evaluation_type")
- output_type = data.get("output_type")
- if evaluation_type and output_type:
- try:
- data["evaluation_config"], data["output_config"] = validate_evaluation_configs(
- evaluation_type, output_type, data["evaluation_config"], data["output_config"]
- )
- except ValueError as e:
- raise serializers.ValidationError({"config": str(e)})
+ evaluation_type = data.get("evaluation_type") or getattr(self.instance, "evaluation_type", None)
+ output_type = data.get("output_type") or getattr(self.instance, "output_type", None)
+ model_configuration = data.get(
+ "model_configuration",
+ getattr(self.instance, "model_configuration", None) if self.instance else None,
+ )
+
+ if self._requires_sentiment_evaluations_feature(data) and not self._sentiment_evaluations_enabled():
+ raise serializers.ValidationError(
+ {"evaluation_type": "Sentiment evaluations are not available for this project."}
+ )
+
+ if not evaluation_uses_model_configuration(evaluation_type) and model_configuration is not None:
+ raise serializers.ValidationError(
+ {"model_configuration": "This evaluation type does not use model configuration."}
+ )
+
+ should_validate_configs = (
+ self.instance is None
+ or "evaluation_type" in data
+ or "output_type" in data
+ or "evaluation_config" in data
+ or "output_config" in data
+ )
+ if should_validate_configs and evaluation_type and output_type:
+ evaluation_config = data.get(
+ "evaluation_config",
+ getattr(self.instance, "evaluation_config", {}) if self.instance else {},
+ )
+ output_config = data.get(
+ "output_config",
+ getattr(self.instance, "output_config", {}) if self.instance else {},
+ )
+ try:
+ data["evaluation_config"], data["output_config"] = validate_evaluation_configs(
+ evaluation_type, output_type, evaluation_config, output_config
+ )
+ except ValueError as e:
+ raise serializers.ValidationError({"config": str(e)})
# Guard re-enable transitions: if the eval is currently disabled and the caller is flipping
# `enabled=True`, make sure whatever caused the disabled state has actually been resolved.
@@ -203,14 +264,42 @@ class EvaluationSerializer(serializers.ModelSerializer):
return data
+ def _requires_sentiment_evaluations_feature(self, data: dict) -> bool:
+ if self.instance is None:
+ return (
+ data.get("evaluation_type") == EvaluationType.SENTIMENT.value
+ or data.get("output_type") == OutputType.SENTIMENT.value
+ )
+ if (
+ data.get("evaluation_type") == EvaluationType.SENTIMENT.value
+ and self.instance.evaluation_type != EvaluationType.SENTIMENT.value
+ ):
+ return True
+ if (
+ data.get("output_type") == OutputType.SENTIMENT.value
+ and self.instance.output_type != OutputType.SENTIMENT.value
+ ):
+ return True
+ return (
+ data.get("enabled") is True
+ and not self.instance.enabled
+ and self.instance.evaluation_type == EvaluationType.SENTIMENT.value
+ )
+
+ def _sentiment_evaluations_enabled(self) -> bool:
+ return is_sentiment_evaluations_enabled(
+ cast(User, self.context["request"].user),
+ self.context["get_team"](),
+ )
+
def _validate_re_enable(self, data: dict) -> None:
has_byok = self._has_byok_key(data)
status_reason = getattr(self.instance, "status_reason", None)
evaluation_type = data.get("evaluation_type") or getattr(self.instance, "evaluation_type", None)
- # Hog evals run deterministic bytecode server-side: they never call an LLM provider,
- # never consume trial quota, and never need a BYOK key. The trial-limit / model-allowlist /
- # provider-key-deleted gates below all assume an LLM-judge call path, so skip them entirely.
- if evaluation_type == "hog":
+ # Non-model evals never call an LLM provider, consume trial quota, or need a BYOK key.
+ # The trial-limit / model-allowlist / provider-key-deleted gates below assume an
+ # LLM-judge call path, so skip them entirely.
+ if not evaluation_uses_model_configuration(evaluation_type):
return
# Trial limit: can only re-enable if they've attached a BYOK key (which bypasses trial quota).
@@ -451,25 +540,23 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
def _get_config_length(instance) -> int:
"""Get the relevant config content length for tracking."""
if instance.evaluation_config and isinstance(instance.evaluation_config, dict):
- if instance.evaluation_type == "hog":
- source = instance.evaluation_config.get("source", "")
- return len(source) if isinstance(source, str) else 0
- else:
- prompt = instance.evaluation_config.get("prompt", "")
- return len(prompt) if isinstance(prompt, str) else 0
+ content_key = get_evaluation_config_content_key(instance.evaluation_type)
+ content = instance.evaluation_config.get(content_key, "") if content_key else ""
+ return len(content) if isinstance(content, str) else 0
return 0
def perform_create(self, serializer):
with transaction.atomic():
instance = serializer.save()
- # Auto-create a default report config so reports are generated from the start.
- # Defaults to count-triggered (frequency=every_n), so rrule/starts_at stay empty
- # and users add email/Slack delivery targets later if they want notifications.
- EvaluationReport.objects.create(
- team=self.team,
- evaluation=instance,
- )
+ if evaluation_supports_reports(instance.output_type):
+ # Auto-create a default report config so reports are generated from the start.
+ # Defaults to count-triggered (frequency=every_n), so rrule/starts_at stay empty
+ # and users add email/Slack delivery targets later if they want notifications.
+ EvaluationReport.objects.create(
+ team=self.team,
+ evaluation=instance,
+ )
# Calculate properties for tracking
conditions = instance.conditions or []
@@ -539,9 +626,13 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
eval_type = serializer.validated_data.get(
"evaluation_type", serializer.instance.evaluation_type
)
- config_key = "source" if eval_type == "hog" else "prompt"
- old_content = old_value.get(config_key, "") if isinstance(old_value, dict) else ""
- new_content = new_value.get(config_key, "") if isinstance(new_value, dict) else ""
+ config_key = get_evaluation_config_content_key(eval_type)
+ old_content = (
+ old_value.get(config_key, "") if config_key and isinstance(old_value, dict) else ""
+ )
+ new_content = (
+ new_value.get(config_key, "") if config_key and isinstance(new_value, dict) else ""
+ )
if old_content != new_content:
config_content_changed = True
diff --git a/products/ai_observability/backend/api/test/test_evaluation_reports.py b/products/ai_observability/backend/api/test/test_evaluation_reports.py
index a245b861aaee..af488804d9d0 100644
--- a/products/ai_observability/backend/api/test/test_evaluation_reports.py
+++ b/products/ai_observability/backend/api/test/test_evaluation_reports.py
@@ -55,6 +55,19 @@ class TestEvaluationReportApi(APIBaseTest):
payload.update(overrides)
return payload
+ def _create_sentiment_evaluation(self) -> Evaluation:
+ return Evaluation.objects.create(
+ team=self.team,
+ name="Sentiment Eval",
+ evaluation_type="sentiment",
+ evaluation_config={},
+ output_type="sentiment",
+ output_config={},
+ enabled=True,
+ created_by=self.user,
+ conditions=[{"id": "c1", "rollout_percentage": 100, "properties": []}],
+ )
+
def test_unauthenticated_user_cannot_access(self):
self.client.logout()
response = self.client.get(self.base_url)
@@ -130,6 +143,37 @@ class TestEvaluationReportApi(APIBaseTest):
self.assertEqual(report.rrule, "")
self.assertIsNone(report.starts_at)
+ def test_create_rejects_sentiment_evaluation(self):
+ sentiment_evaluation = self._create_sentiment_evaluation()
+ response = self.client.post(
+ self.base_url,
+ {
+ "evaluation": str(sentiment_evaluation.id),
+ "frequency": "every_n",
+ "trigger_threshold": 100,
+ "delivery_targets": [],
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json().get("attr"), "evaluation")
+
+ def test_list_excludes_sentiment_reports(self):
+ sentiment_evaluation = self._create_sentiment_evaluation()
+ EvaluationReport.objects.create(
+ team=self.team,
+ evaluation=sentiment_evaluation,
+ frequency=EvaluationReport.Frequency.EVERY_N,
+ trigger_threshold=100,
+ delivery_targets=[],
+ )
+
+ response = self.client.get(self.base_url)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(response.json()["results"]), 0)
+
def test_create_scheduled_sets_next_delivery_date(self):
response = self.client.post(self.base_url, self._scheduled_payload(rrule="FREQ=HOURLY"), format="json")
self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
diff --git a/products/ai_observability/backend/api/test/test_evaluation_runs.py b/products/ai_observability/backend/api/test/test_evaluation_runs.py
index e3b053a6ef46..ba5118364d54 100644
--- a/products/ai_observability/backend/api/test/test_evaluation_runs.py
+++ b/products/ai_observability/backend/api/test/test_evaluation_runs.py
@@ -1,6 +1,7 @@
import uuid
from datetime import datetime
+import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -10,9 +11,27 @@ from rest_framework import status
from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags
+from ...api.evaluation_runs import _evaluation_workflow_prefix
from ...models.evaluations import Evaluation
+ ("evaluation_type", "expected_prefix"),
+ [
+ ("llm_judge", "llma-llm-eval"),
+ ("hog", "llma-hog-eval"),
+ ("sentiment", "llma-sentiment-eval"),
+ ],
+)
+def test_evaluation_workflow_prefix_maps_every_supported_runtime(evaluation_type: str, expected_prefix: str):
+ assert _evaluation_workflow_prefix(evaluation_type) == expected_prefix
+
+
+def test_evaluation_workflow_prefix_rejects_unknown_runtime():
+ with pytest.raises(ValueError, match="Unsupported evaluation type for workflow prefix: unknown"):
+ _evaluation_workflow_prefix("unknown")
+
+
class TestEvaluationRunViewSet(APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index d07540fcaab2..48b7abd9d275 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -113,6 +113,166 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertEqual(Evaluation.objects.filter(name="Will Rollback").count(), 0)
self.assertEqual(EvaluationReport.objects.count(), 0)
+ def test_can_create_sentiment_evaluation_without_default_report(self):
+ with patch(
+ "products.ai_observability.backend.feature_flags.posthoganalytics.feature_enabled", return_value=True
+ ):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/",
+ {
+ "name": "Sentiment Evaluation",
+ "enabled": True,
+ "evaluation_type": "sentiment",
+ "evaluation_config": {},
+ "output_type": "sentiment",
+ "output_config": {},
+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ evaluation = Evaluation.objects.get(id=response.data["id"])
+ self.assertEqual(evaluation.evaluation_type, "sentiment")
+ self.assertEqual(evaluation.evaluation_config, {"source": "user_messages"})
+ self.assertEqual(evaluation.output_type, "sentiment")
+ self.assertEqual(evaluation.output_config, {})
+ self.assertEqual(EvaluationReport.objects.filter(evaluation=evaluation).count(), 0)
+
+ def test_create_sentiment_evaluation_requires_feature_flag(self):
+ with patch(
+ "products.ai_observability.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False
+ ):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/",
+ {
+ "name": "Sentiment Evaluation",
+ "enabled": True,
+ "evaluation_type": "sentiment",
+ "evaluation_config": {},
+ "output_type": "sentiment",
+ "output_config": {},
+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.data["attr"], "evaluation_type")
+ self.assertEqual(Evaluation.objects.count(), 0)
+
+ def test_re_enable_sentiment_evaluation_requires_feature_flag(self):
+ evaluation = Evaluation.objects.create(
+ name="Sentiment Evaluation",
+ enabled=False,
+ evaluation_type="sentiment",
+ evaluation_config={},
+ output_type="sentiment",
+ output_config={},
+ conditions=[{"id": "test-condition", "rollout_percentage": 50, "properties": []}],
+ team=self.team,
+ created_by=self.user,
+ )
+
+ with patch(
+ "products.ai_observability.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False
+ ):
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{evaluation.id}/",
+ {"enabled": True},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.data["attr"], "evaluation_type")
+ evaluation.refresh_from_db()
+ self.assertFalse(evaluation.enabled)
+
+ def test_update_existing_sentiment_evaluation_allows_unchanged_type_when_feature_flag_off(self):
+ evaluation = Evaluation.objects.create(
+ name="Sentiment Evaluation",
+ enabled=True,
+ evaluation_type="sentiment",
+ evaluation_config={},
+ output_type="sentiment",
+ output_config={},
+ conditions=[{"id": "test-condition", "rollout_percentage": 50, "properties": []}],
+ team=self.team,
+ created_by=self.user,
+ )
+
+ with patch(
+ "products.ai_observability.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False
+ ):
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{evaluation.id}/",
+ {
+ "name": "Updated Sentiment Evaluation",
+ "evaluation_type": "sentiment",
+ "output_type": "sentiment",
+ "evaluation_config": {"source": "user_messages"},
+ "output_config": {},
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ evaluation.refresh_from_db()
+ self.assertEqual(evaluation.name, "Updated Sentiment Evaluation")
+
+ def test_sentiment_evaluation_rejects_model_configuration(self):
+ with patch(
+ "products.ai_observability.backend.feature_flags.posthoganalytics.feature_enabled", return_value=True
+ ):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/",
+ {
+ "name": "Sentiment Evaluation",
+ "enabled": True,
+ "evaluation_type": "sentiment",
+ "evaluation_config": {},
+ "output_type": "sentiment",
+ "output_config": {},
+ "model_configuration": {
+ "provider": "openai",
+ "model": "gpt-5-mini",
+ "provider_key_id": None,
+ },
+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.data["attr"], "model_configuration")
+
+ @parameterized.expand(
+ [
+ ("sentiment_boolean", "sentiment", "boolean", {}, {}),
+ ("llm_judge_sentiment", "llm_judge", "sentiment", {"prompt": "Test prompt"}, {}),
+ ]
+ )
+ def test_rejects_unsupported_evaluation_output_type_combinations(
+ self, _name, evaluation_type, output_type, evaluation_config, output_config
+ ):
+ with patch(
+ "products.ai_observability.backend.feature_flags.posthoganalytics.feature_enabled", return_value=True
+ ):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/",
+ {
+ "name": "Unsupported Evaluation",
+ "enabled": True,
+ "evaluation_type": evaluation_type,
+ "evaluation_config": evaluation_config,
+ "output_type": output_type,
+ "output_config": output_config,
+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.data["attr"], "config")
+ self.assertEqual(Evaluation.objects.count(), 0)
+
def test_can_retrieve_list_of_evaluation_configs(self):
Evaluation.objects.create(
name="Evaluation 1",
diff --git a/products/ai_observability/backend/feature_flags.py b/products/ai_observability/backend/feature_flags.py
new file mode 100644
index 000000000000..396c93555881
--- /dev/null
+++ b/products/ai_observability/backend/feature_flags.py
@@ -0,0 +1,22 @@
+from __future__ import annotations
+
+import posthoganalytics
+
+from posthog.models import Team, User
+
+SENTIMENT_EVALUATIONS_FEATURE_FLAG = "llm-analytics-sentiment-evaluations"
+
+
+def is_sentiment_evaluations_enabled(user: User, team: Team) -> bool:
+ distinct_id = user.distinct_id or str(user.uuid)
+ organization_id = str(team.organization_id)
+ project_id = str(team.id)
+
+ return posthoganalytics.feature_enabled(
+ SENTIMENT_EVALUATIONS_FEATURE_FLAG,
+ distinct_id,
+ groups={"organization": organization_id, "project": project_id},
+ group_properties={"organization": {"id": organization_id}, "project": {"id": project_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
diff --git a/products/ai_observability/backend/migrations/0006_alter_evaluation_evaluation_type_and_more.py b/products/ai_observability/backend/migrations/0006_alter_evaluation_evaluation_type_and_more.py
new file mode 100644
index 000000000000..a4a1727e8e9f
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0006_alter_evaluation_evaluation_type_and_more.py
@@ -0,0 +1,27 @@
+# Generated by Django 5.2.14 on 2026-06-09 18:36
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("ai_observability", "0005_release_skills_to_skills_app"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="evaluation",
+ name="evaluation_type",
+ field=models.CharField(
+ choices=[("llm_judge", "LLM as a judge"), ("hog", "Hog"), ("sentiment", "Sentiment analysis")],
+ max_length=50,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="evaluation",
+ name="output_type",
+ field=models.CharField(
+ choices=[("boolean", "Boolean (Pass/Fail)"), ("sentiment", "Sentiment")], max_length=50
+ ),
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index bb43d9adb48c..3733e3a1c821 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0005_release_skills_to_skills_app
+0006_alter_evaluation_evaluation_type_and_more
diff --git a/products/ai_observability/backend/models/evaluation_config.py b/products/ai_observability/backend/models/evaluation_config.py
index 564c2e366ebe..adf16e091565 100644
--- a/products/ai_observability/backend/models/evaluation_config.py
+++ b/products/ai_observability/backend/models/evaluation_config.py
@@ -2,7 +2,7 @@ from django.db import models
class EvaluationConfig(models.Model):
- """Team-level configuration and usage tracking for LLM evaluations"""
+ """Team-level configuration and usage tracking for evaluations"""
team = models.OneToOneField(
"posthog.Team",
diff --git a/products/ai_observability/backend/models/evaluation_configs.py b/products/ai_observability/backend/models/evaluation_configs.py
index 9b581504799d..51ff514646c4 100644
--- a/products/ai_observability/backend/models/evaluation_configs.py
+++ b/products/ai_observability/backend/models/evaluation_configs.py
@@ -1,4 +1,4 @@
-from typing import Any
+from typing import Any, Literal
from django.db import models
@@ -10,12 +10,14 @@ class EvaluationType(models.TextChoices):
LLM_JUDGE = "llm_judge", "LLM as a judge"
HOG = "hog", "Hog"
+ SENTIMENT = "sentiment", "Sentiment analysis"
class OutputType(models.TextChoices):
"""What type of result is expected"""
BOOLEAN = "boolean", "Boolean (Pass/Fail)"
+ SENTIMENT = "sentiment", "Sentiment"
class LLMJudgeConfig(BaseModel):
@@ -51,12 +53,58 @@ class BooleanOutputConfig(BaseModel):
allows_na: bool = False
+class SentimentEvalConfig(BaseModel):
+ """Configuration for sentiment evaluations."""
+
+ source: Literal["user_messages"] = Field(
+ default="user_messages",
+ description="Text source used for sentiment classification.",
+ )
+
+
+class SentimentOutputConfig(BaseModel):
+ """Configuration for sentiment output type."""
+
+
# Mapping: (evaluation_type, output_type) -> (evaluation_config_model, output_config_model)
-EVALUATION_CONFIG_MODELS: dict[tuple[str, str], tuple[type[BaseModel], type[BooleanOutputConfig]]] = {
+EVALUATION_CONFIG_MODELS: dict[tuple[str, str], tuple[type[BaseModel], type[BaseModel]]] = {
(EvaluationType.LLM_JUDGE.value, OutputType.BOOLEAN.value): (LLMJudgeConfig, BooleanOutputConfig),
(EvaluationType.HOG.value, OutputType.BOOLEAN.value): (HogEvalConfig, BooleanOutputConfig),
+ (EvaluationType.SENTIMENT.value, OutputType.SENTIMENT.value): (SentimentEvalConfig, SentimentOutputConfig),
}
+EVALUATION_CONFIG_CONTENT_KEYS: dict[str, str] = {
+ EvaluationType.LLM_JUDGE.value: "prompt",
+ EvaluationType.HOG.value: "source",
+ EvaluationType.SENTIMENT.value: "source",
+}
+
+REPORTABLE_OUTPUT_TYPES: tuple[str, ...] = (OutputType.BOOLEAN.value,)
+
+
+def evaluation_uses_model_configuration(evaluation_type: str | None) -> bool:
+ return evaluation_type == EvaluationType.LLM_JUDGE.value
+
+
+def evaluation_supports_reports(output_type: str | None) -> bool:
+ return output_type in REPORTABLE_OUTPUT_TYPES
+
+
+def get_evaluation_config_content_key(evaluation_type: str | None) -> str | None:
+ return EVALUATION_CONFIG_CONTENT_KEYS.get(evaluation_type) if evaluation_type is not None else None
+
+
+def evaluation_configs_allow_empty(evaluation_type: str, output_type: str) -> bool:
+ config_models = EVALUATION_CONFIG_MODELS.get((evaluation_type, output_type))
+ if config_models is None:
+ return False
+
+ return all(
+ not field_info.is_required()
+ for config_model in config_models
+ for field_info in config_model.model_fields.values()
+ )
+
def validate_evaluation_configs(
evaluation_type: str, output_type: str, evaluation_config: dict, output_config: dict
diff --git a/products/ai_observability/backend/models/evaluations.py b/products/ai_observability/backend/models/evaluations.py
index 2e04809248b5..e6113de3f28e 100644
--- a/products/ai_observability/backend/models/evaluations.py
+++ b/products/ai_observability/backend/models/evaluations.py
@@ -11,7 +11,14 @@ from rest_framework.exceptions import ValidationError
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.utils import UUIDTModel
-from .evaluation_configs import EvaluationType, OutputType, validate_evaluation_configs
+from .evaluation_configs import (
+ EVALUATION_CONFIG_MODELS,
+ EvaluationType,
+ OutputType,
+ evaluation_configs_allow_empty,
+ evaluation_uses_model_configuration,
+ validate_evaluation_configs,
+)
logger = structlog.get_logger(__name__)
@@ -155,8 +162,18 @@ class Evaluation(ModelActivityMixin, UUIDTModel):
# either field — typically `enabled` from user PATCHes, `status` from system transitions.
self._coerce_status_and_enabled()
- # Validate evaluation and output configs
- if self.evaluation_config or self.output_config:
+ if not evaluation_uses_model_configuration(self.evaluation_type) and self.model_configuration_id:
+ raise ValidationError({"model_configuration": "This evaluation type does not use model configuration."})
+
+ if (self.evaluation_type, self.output_type) not in EVALUATION_CONFIG_MODELS:
+ raise ValidationError(f"Unsupported combination: {self.evaluation_type} + {self.output_type}")
+
+ # Validate configs when callers provide them, or when the selected config models can supply every default.
+ if (
+ evaluation_configs_allow_empty(self.evaluation_type, self.output_type)
+ or self.evaluation_config
+ or self.output_config
+ ):
try:
self.evaluation_config, self.output_config = validate_evaluation_configs(
self.evaluation_type, self.output_type, self.evaluation_config, self.output_config
diff --git a/products/ai_observability/backend/models/test/test_evaluations.py b/products/ai_observability/backend/models/test/test_evaluations.py
index 062300c15c8c..083184c7c77b 100644
--- a/products/ai_observability/backend/models/test/test_evaluations.py
+++ b/products/ai_observability/backend/models/test/test_evaluations.py
@@ -251,6 +251,38 @@ class TestEvaluationModel(BaseTest):
self.assertIn("bytecode", evaluation.evaluation_config)
self.assertNotEqual(evaluation.evaluation_config["bytecode"], original_bytecode)
+ def test_sentiment_evaluation_defaults_to_user_messages_source(self):
+ evaluation = Evaluation.objects.create(
+ team=self.team,
+ name="Sentiment Eval",
+ evaluation_type="sentiment",
+ evaluation_config={},
+ output_type="sentiment",
+ output_config={},
+ enabled=True,
+ created_by=self.user,
+ conditions=[{"id": "cond-1", "rollout_percentage": 100, "properties": []}],
+ )
+
+ evaluation.refresh_from_db()
+
+ self.assertEqual(evaluation.evaluation_config, {"source": "user_messages"})
+ self.assertEqual(evaluation.output_config, {})
+
+ def test_unsupported_evaluation_output_type_combination_rejected(self):
+ with self.assertRaises(ValidationError):
+ Evaluation.objects.create(
+ team=self.team,
+ name="Bad Eval",
+ evaluation_type="llm_judge",
+ evaluation_config={},
+ output_type="sentiment",
+ output_config={},
+ enabled=True,
+ created_by=self.user,
+ conditions=[{"id": "cond-1", "rollout_percentage": 100, "properties": []}],
+ )
+
def test_preserves_other_condition_fields(self):
"""
Other condition fields (id, rollout_percentage) should be preserved during save
diff --git a/products/ai_observability/backend/summarization/llm/evaluation_schema.py b/products/ai_observability/backend/summarization/llm/evaluation_schema.py
index a5962aedf868..f3e0be3dc516 100644
--- a/products/ai_observability/backend/summarization/llm/evaluation_schema.py
+++ b/products/ai_observability/backend/summarization/llm/evaluation_schema.py
@@ -1,5 +1,5 @@
"""
-Pydantic schema for structured LLM evaluation summary outputs.
+Pydantic schema for structured evaluation summary outputs.
"""
from pydantic import BaseModel, ConfigDict, Field
@@ -31,7 +31,7 @@ class EvaluationSummaryStatistics(BaseModel):
class EvaluationSummaryResponse(BaseModel):
- """Structured response from LLM evaluation summarization."""
+ """Structured response from AI-powered evaluation summarization."""
model_config = ConfigDict(extra="forbid")
diff --git a/products/ai_observability/backend/summarization/prompts/evaluation_summary.djt b/products/ai_observability/backend/summarization/prompts/evaluation_summary.djt
index ec0f646c9901..4c258cf4ef9d 100644
--- a/products/ai_observability/backend/summarization/prompts/evaluation_summary.djt
+++ b/products/ai_observability/backend/summarization/prompts/evaluation_summary.djt
@@ -1,4 +1,4 @@
-You are an expert at analyzing LLM evaluation results. Your task is to analyze evaluation run results and identify patterns across them.
+You are an expert at analyzing AI observability evaluation results. Your task is to analyze evaluation run results and identify patterns across them.
## Evaluation Context
@@ -7,19 +7,19 @@ You are an expert at analyzing LLM evaluation results. Your task is to analyze e
**Description:** {{ evaluation_description }}
{% endif %}
-**Evaluation Prompt (what the LLM judge uses to evaluate):**
+**Evaluation criteria:**
```
{{ evaluation_prompt }}
```
-Understanding this evaluation prompt is crucial - it defines what criteria the LLM judge uses to determine if a response passes, fails, or is N/A. Use this context to better understand the reasoning provided in each evaluation result.
+Understanding these criteria is crucial - they define how a response is determined to pass, fail, or be N/A. Use this context to better understand the reasoning provided in each evaluation result.
## Evaluation Results
You are given a list of evaluation results, each containing:
- generation_id: A unique identifier for this evaluation run
- result: Whether the evaluation passed (PASS), failed (FAIL), or was not applicable (N/A)
-- reasoning: The LLM judge's explanation for the result
+- reasoning: The explanation for the result
{% if filter == 'all' %}
Your goal is to:
diff --git a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx
new file mode 100644
index 000000000000..2a0f7ba21496
--- /dev/null
+++ b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx
@@ -0,0 +1,46 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { initKeaTests } from '~/test/init'
+
+import { EvaluationDisplay } from './EvaluationDisplay'
+
+describe('EvaluationDisplay', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('renders sentiment value instead of a boolean result', () => {
+ render(
+ <Provider>
+ <EvaluationDisplay
+ eventProperties={{
+ $ai_evaluation_runtime: 'sentiment',
+ $ai_sentiment_label: 'positive',
+ $ai_sentiment_score: 0.91,
+ }}
+ />
+ </Provider>
+ )
+
+ expect(screen.getByText('Positive (91%)')).toBeInTheDocument()
+ expect(screen.queryByText('False')).not.toBeInTheDocument()
+ })
+
+ it('does not coerce absent boolean results to false', () => {
+ render(
+ <Provider>
+ <EvaluationDisplay eventProperties={{}} />
+ </Provider>
+ )
+
+ expect(screen.getByText('N/A')).toBeInTheDocument()
+ expect(screen.queryByText('False')).not.toBeInTheDocument()
+ })
+})
diff --git a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
index 95b77f3da567..f67e8376a123 100644
--- a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
@@ -1,52 +1,36 @@
-import { IconCheck, IconMinus, IconX } from '@posthog/icons'
-import { LemonTag, Link } from '@posthog/lemon-ui'
+import { Link } from '@posthog/lemon-ui'
import { lowercaseFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { EventType } from '~/types'
+import { EvaluationResultTag } from '../components/EvaluationResultTag'
import { MetadataTag } from '../components/MetadataTag'
+import { normalizeEvaluationResultProperties } from '../utils'
export function EvaluationDisplay({ eventProperties }: { eventProperties: EventType['properties'] }): JSX.Element {
- const rawResult = eventProperties.$ai_evaluation_result
- const rawApplicable = eventProperties.$ai_evaluation_applicable
- // Check if result is explicitly true (handles both boolean and string 'true')
- const isPass = rawResult === true || rawResult === 'true'
- // N/A when backend explicitly sets applicable to false (handle string 'false' from HogQL)
- const isNA = rawApplicable === false || rawApplicable === 'false'
const reasoning = eventProperties.$ai_evaluation_reasoning
const evaluationName = eventProperties.$ai_evaluation_name
const model = eventProperties.$ai_model ?? eventProperties.$ai_evaluation_model
const traceId = eventProperties.$ai_trace_id
const targetEventId = eventProperties.$ai_target_event_id
-
- const renderResultTag = (): JSX.Element => {
- if (isNA) {
- return (
- <LemonTag type="muted" icon={<IconMinus />}>
- N/A
- </LemonTag>
- )
- }
- if (isPass) {
- return (
- <LemonTag type="success" icon={<IconCheck />}>
- True
- </LemonTag>
- )
- }
- return (
- <LemonTag type="danger" icon={<IconX />}>
- False
- </LemonTag>
- )
+ const resultRun = {
+ status: 'completed' as const,
+ ...normalizeEvaluationResultProperties({
+ rawResult: eventProperties.$ai_evaluation_result,
+ rawApplicable: eventProperties.$ai_evaluation_applicable,
+ rawEvaluationType: eventProperties.$ai_evaluation_runtime,
+ rawResultType: eventProperties.$ai_evaluation_result_type,
+ rawSentimentLabel: eventProperties.$ai_sentiment_label,
+ rawSentimentScore: eventProperties.$ai_sentiment_score,
+ }),
}
return (
<div className="space-y-4">
<div className="flex flex-wrap gap-2">
- {renderResultTag()}
+ <EvaluationResultTag run={resultRun} />
{evaluationName && (
<MetadataTag label="Evaluation" textToCopy={evaluationName}>
{evaluationName}
diff --git a/products/ai_observability/frontend/components/EvalResultBadges.test.tsx b/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
index 6896519ef62c..a2078dedff45 100644
--- a/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
+++ b/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
@@ -63,6 +63,41 @@ describe('getEvalBadgeProps', () => {
['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)
diff --git a/products/ai_observability/frontend/components/EvalResultBadges.tsx b/products/ai_observability/frontend/components/EvalResultBadges.tsx
index a12b91d0df51..7e3e9462f717 100644
--- a/products/ai_observability/frontend/components/EvalResultBadges.tsx
+++ b/products/ai_observability/frontend/components/EvalResultBadges.tsx
@@ -1,6 +1,5 @@
import { useActions, useMountedLogic, useValues } from 'kea'
-import { IconCheck, IconMinus, IconWarning, IconX } from '@posthog/icons'
import { LemonSkeleton, LemonTag, LemonTagProps, Tooltip } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
@@ -9,6 +8,7 @@ import { pluralize } from 'lib/utils/strings'
import { TraceViewMode, aiObservabilityTraceLogic } from '../aiObservabilityTraceLogic'
import { EvaluationRun } from '../evaluations/types'
import { generationEvaluationRunsLogic } from '../generationEvaluationRunsLogic'
+import { getEvaluationResultDisplay } from './EvaluationResultTag'
export interface EvalSummary {
latestRun: EvaluationRun
@@ -34,19 +34,8 @@ export function getEvalBadgeProps(run: EvaluationRun): {
icon: JSX.Element
label: string
} {
- if (run.status === 'failed') {
- return { type: 'danger', icon: <IconWarning />, label: 'Error' }
- }
- if (run.status === 'running') {
- return { type: 'primary', icon: <IconMinus />, label: 'Running' }
- }
- if (run.result === null) {
- return { type: 'muted', icon: <IconMinus />, label: 'N/A' }
- }
- if (run.result) {
- return { type: 'success', icon: <IconCheck />, label: 'True' }
- }
- return { type: 'danger', icon: <IconX />, label: 'False' }
+ const { type, icon, label } = getEvaluationResultDisplay(run)
+ return { type, icon, label }
}
function EvalTooltipContent({ latestRun, runCount }: EvalSummary): JSX.Element {
diff --git a/products/ai_observability/frontend/components/EvaluationResultTag.tsx b/products/ai_observability/frontend/components/EvaluationResultTag.tsx
new file mode 100644
index 000000000000..79320fdd8fd6
--- /dev/null
+++ b/products/ai_observability/frontend/components/EvaluationResultTag.tsx
@@ -0,0 +1,76 @@
+import { IconCheck, IconMinus, IconWarning, IconX } from '@posthog/icons'
+import { LemonTag } from '@posthog/lemon-ui'
+import type { LemonTagProps } from '@posthog/lemon-ui'
+
+import type { EvaluationRun } from '../evaluations/types'
+import { capitalize, formatScore } from '../sentimentUtils'
+
+type EvaluationResultLike = Pick<
+ EvaluationRun,
+ 'status' | 'result' | 'result_type' | 'evaluation_type' | 'sentiment_label' | 'sentiment_score'
+>
+
+interface EvaluationResultDisplay {
+ type: LemonTagProps['type']
+ icon: JSX.Element
+ label: string
+ sortValue: number
+}
+
+const SENTIMENT_DISPLAY: Record<string, Pick<EvaluationResultDisplay, 'type' | 'icon' | 'sortValue'>> = {
+ positive: { type: 'success', icon: <IconCheck />, sortValue: 3 },
+ neutral: { type: 'none', icon: <IconMinus />, sortValue: 2 },
+ negative: { type: 'danger', icon: <IconX />, sortValue: 1 },
+}
+
+function isSentimentRun(run: EvaluationResultLike): boolean {
+ return run.result_type === 'sentiment' || run.evaluation_type === 'sentiment' || !!run.sentiment_label
+}
+
+export function getEvaluationResultDisplay(run: EvaluationResultLike): EvaluationResultDisplay {
+ if (run.status === 'failed') {
+ return { type: 'danger', icon: <IconWarning />, label: 'Error', sortValue: -2 }
+ }
+ if (run.status === 'running') {
+ return { type: 'primary', icon: <IconMinus />, label: 'Running', sortValue: -1 }
+ }
+ if (isSentimentRun(run)) {
+ const sentimentLabel = (run.sentiment_label || 'unknown').toLowerCase()
+ const display = SENTIMENT_DISPLAY[sentimentLabel] ?? {
+ type: 'muted' as const,
+ icon: <IconMinus />,
+ sortValue: 0,
+ }
+ const score = run.sentiment_score
+ return {
+ ...display,
+ label: `${capitalize(sentimentLabel)}${score !== null && score !== undefined ? ` (${formatScore(score)})` : ''}`,
+ }
+ }
+ if (run.result === null) {
+ return { type: 'muted', icon: <IconMinus />, label: 'N/A', sortValue: 0.5 }
+ }
+ if (run.result) {
+ return { type: 'success', icon: <IconCheck />, label: 'True', sortValue: 1 }
+ }
+ return { type: 'danger', icon: <IconX />, label: 'False', sortValue: 0 }
+}
+
+export function getEvaluationResultSortValue(run: EvaluationResultLike): number {
+ return getEvaluationResultDisplay(run).sortValue
+}
+
+export function EvaluationResultTag({
+ run,
+ size,
+}: {
+ run: EvaluationResultLike
+ size?: LemonTagProps['size']
+}): JSX.Element {
+ const { type, icon, label } = getEvaluationResultDisplay(run)
+ return (
+ <LemonTag type={type} icon={icon} size={size}>
+ {label}
+ </LemonTag>
+ )
+}
diff --git a/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx b/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx
index fbaae2e63c80..d796d1e2565d 100644
--- a/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx
+++ b/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx
@@ -1,7 +1,6 @@
import { BuiltLogic, useValues } from 'kea'
-import { IconCheck, IconMinus, IconWarning, IconX } from '@posthog/icons'
-import { LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+import { LemonTable, Link, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
@@ -9,6 +8,7 @@ import { urls } from 'scenes/urls'
import { EvaluationRun } from '../evaluations/types'
import { generationEvaluationRunsLogicType } from '../generationEvaluationRunsLogicType'
+import { EvaluationResultTag, getEvaluationResultSortValue } from './EvaluationResultTag'
export function GenerationEvalRunsTable({
generationRunsLogic,
@@ -36,44 +36,9 @@ export function GenerationEvalRunsTable({
{
title: 'Result',
key: 'result',
- render: (_, run) => {
- if (run.status === 'failed') {
- return (
- <LemonTag type="danger" icon={<IconWarning />}>
- Error
- </LemonTag>
- )
- }
- if (run.status === 'running') {
- return <LemonTag type="primary">Running...</LemonTag>
- }
- // Handle N/A case (result is null when not applicable)
- if (run.result === null) {
- return (
- <LemonTag type="muted" icon={<IconMinus />}>
- N/A
- </LemonTag>
- )
- }
- return (
- <div className="flex items-center gap-2">
- {run.result ? (
- <LemonTag type="success" icon={<IconCheck />}>
- True
- </LemonTag>
- ) : (
- <LemonTag type="danger" icon={<IconX />}>
- False
- </LemonTag>
- )}
- </div>
- )
- },
+ render: (_, run) => <EvaluationResultTag run={run} />,
sorter: (a, b) => {
- // N/A (null) sorts between pass (1) and fail (0)
- const valA = a.result === null ? 0.5 : Number(a.result)
- const valB = b.result === null ? 0.5 : Number(b.result)
- return valB - valA
+ return getEvaluationResultSortValue(b) - getEvaluationResultSortValue(a)
},
},
{
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
index 91c853702661..bb62da6158d4 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
@@ -40,6 +40,13 @@ import { EvaluationReportConfig } from './components/EvaluationReportConfig'
import { EvaluationReportsTab } from './components/EvaluationReportsTab'
import { EvaluationRunsTable } from './components/EvaluationRunsTable'
import { EvaluationTriggers } from './components/EvaluationTriggers'
+import {
+ evaluationSupportsReports,
+ evaluationTypeCanBeCreated,
+ evaluationTypeHasEditableCriteria,
+ evaluationTypeSupportsSignalEmission,
+ evaluationTypeUsesModelConfiguration,
+} from './evaluationCapabilities'
import { LLMEvaluationLogicProps, llmEvaluationLogic } from './llmEvaluationLogic'
import { statusReasonLabel } from './statusDisplay'
import { EvaluationType } from './types'
@@ -58,6 +65,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
activeTab,
canEnable,
canEnableReason,
+ originalEvaluation,
} = useValues(llmEvaluationLogic)
const { user } = useValues(userLogic)
const { featureFlags } = useValues(featureFlagLogic)
@@ -85,12 +93,25 @@ export function AIObservabilityEvaluation(): JSX.Element {
return <NotFound object="evaluation" />
}
const openInPlaygroundUrl =
- evaluation.evaluation_type === 'llm_judge' && evaluation.id
+ evaluationTypeUsesModelConfiguration(evaluation.evaluation_type) && evaluation.id
? combineUrl(urls.aiObservabilityPlayground(), { source_evaluation_id: evaluation.id }).url
: null
+ const isHog = evaluation.evaluation_type === 'hog'
+ const isSentiment = evaluation.evaluation_type === 'sentiment'
+ const isReportableEvaluation = evaluationSupportsReports(evaluation)
+ const hasEditableCriteria = evaluationTypeHasEditableCriteria(evaluation.evaluation_type)
+ const canUseEvaluationType = evaluationTypeCanBeCreated(evaluation.evaluation_type, featureFlags)
+ const canSaveEvaluationType =
+ canUseEvaluationType || originalEvaluation?.evaluation_type === evaluation.evaluation_type
+ const effectiveCanEnable = canEnable && (evaluation.enabled || canUseEvaluationType)
+ const effectiveCanEnableReason =
+ !evaluation.enabled && !canUseEvaluationType
+ ? 'Sentiment evaluations are not available for this project.'
+ : canEnableReason
+
const trendInsightUrl =
- !isNewEvaluation && evaluation.id
+ isReportableEvaluation && !isNewEvaluation && evaluation.id
? urls.insightNew({
query: {
kind: NodeKind.InsightVizNode,
@@ -144,10 +165,11 @@ export function AIObservabilityEvaluation(): JSX.Element {
})
: null
- const isHog = evaluation.evaluation_type === 'hog'
const configValid = isHog
? evaluation.evaluation_config.source.trim().length > 0
- : evaluation.evaluation_config.prompt.trim().length > 0
+ : isSentiment
+ ? true
+ : evaluation.evaluation_config.prompt.trim().length > 0
const hasName = evaluation.name.length > 0
const basicFieldsValid = hasName && configValid
const percentageUnset = evaluation.conditions.some((c) => (c.rollout_percentage ?? 0) === 0)
@@ -155,13 +177,15 @@ export function AIObservabilityEvaluation(): JSX.Element {
(c) => (c.rollout_percentage ?? 0) > 100 || (c.rollout_percentage ?? 0) < 0
)
const hasConditions = evaluation.conditions.length > 0
- const saveButtonDisabledReason = !hasName
- ? 'Add a name for this evaluation'
- : !configValid
- ? isHog
- ? 'Add evaluation code before saving'
- : 'Add an evaluation prompt before saving'
- : undefined
+ const saveButtonDisabledReason = !canSaveEvaluationType
+ ? 'Sentiment evaluations are not available for this project'
+ : !hasName
+ ? 'Add a name for this evaluation'
+ : !configValid
+ ? isHog
+ ? 'Add evaluation code before saving'
+ : 'Add an evaluation prompt before saving'
+ : undefined
const focusTriggers = (): void => {
setActiveTab('configuration')
@@ -199,6 +223,34 @@ export function AIObservabilityEvaluation(): JSX.Element {
push(combineUrl(urls.aiObservabilityEvaluations(), searchParams).url)
}
+ const hogEvaluationMethodOptions: { value: EvaluationType; label: string }[] = featureFlags[
+ FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_HOG_CODE
+ ]
+ ? [
+ {
+ value: 'hog',
+ label: 'Hog code',
+ },
+ ]
+ : []
+ const sentimentEvaluationMethodOptions: { value: EvaluationType; label: string }[] =
+ evaluationTypeCanBeCreated('sentiment', featureFlags) || isSentiment
+ ? [
+ {
+ value: 'sentiment',
+ label: 'Sentiment analysis',
+ },
+ ]
+ : []
+ const evaluationMethodOptions: { value: EvaluationType; label: string }[] = [
+ {
+ value: 'llm_judge',
+ label: 'LLM as a judge',
+ },
+ ...hogEvaluationMethodOptions,
+ ...sentimentEvaluationMethodOptions,
+ ]
+
return (
<div className="space-y-6">
<SceneBreadcrumbBackButton />
@@ -317,13 +369,15 @@ export function AIObservabilityEvaluation(): JSX.Element {
<div className="font-semibold text-lg">{runsSummary.total}</div>
<div className="text-muted">Total runs</div>
</div>
- <div className="text-center">
- <div className="font-semibold text-lg text-success">
- {runsSummary.successRate}%
+ {isReportableEvaluation && (
+ <div className="text-center">
+ <div className="font-semibold text-lg text-success">
+ {runsSummary.successRate}%
+ </div>
+ <div className="text-muted">Success rate</div>
</div>
- <div className="text-muted">Success rate</div>
- </div>
- {evaluation.output_config.allows_na && (
+ )}
+ {isReportableEvaluation && evaluation.output_config.allows_na && (
<div className="text-center">
<div className="font-semibold text-lg">
{runsSummary.applicabilityRate}%
@@ -345,6 +399,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
),
},
!isNewEvaluation &&
+ isReportableEvaluation &&
!!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_REPORTS] && {
key: 'reports',
label: 'Reports',
@@ -377,27 +432,20 @@ export function AIObservabilityEvaluation(): JSX.Element {
/>
</Field>
- {featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_HOG_CODE] && (
+ {evaluationMethodOptions.length > 1 && (
<Field name="evaluation_type" label="Method">
<LemonSelect
value={evaluation.evaluation_type}
onChange={(value) => setEvaluationType(value as EvaluationType)}
- options={[
- {
- value: 'llm_judge',
- label: 'LLM as a judge',
- },
- {
- value: 'hog',
- label: 'Hog code',
- },
- ]}
+ options={evaluationMethodOptions}
fullWidth
/>
</Field>
)}
<p className="text-muted text-sm -mt-2">
- {isHog ? (
+ {isSentiment ? (
+ 'Classify the sentiment of user messages on each matching generation.'
+ ) : isHog ? (
<>
Run deterministic{' '}
<Link to="https://posthog.com/docs/hog" target="_blank">
@@ -422,87 +470,94 @@ export function AIObservabilityEvaluation(): JSX.Element {
<div className="flex items-center gap-2">
<Tooltip
- title={canEnableReason}
- visible={canEnableReason ? undefined : false}
+ title={effectiveCanEnableReason}
+ visible={effectiveCanEnableReason ? undefined : false}
>
<span>
<LemonSwitch
checked={evaluation.enabled}
onChange={setEvaluationEnabled}
label="Enable evaluation"
- disabled={!canEnable && !evaluation.enabled}
+ disabled={!effectiveCanEnable && !evaluation.enabled}
/>
</span>
</Tooltip>
<span className="text-muted text-sm">
- {!canEnable && !evaluation.enabled
- ? 'Add a provider API key to re-enable this evaluation'
+ {!effectiveCanEnable && !evaluation.enabled
+ ? effectiveCanEnableReason
: evaluation.enabled
? 'This evaluation will run automatically based on triggers'
: 'This evaluation is paused and will not run'}
</span>
</div>
- <Field
- name="allows_na"
- label={
- <div className="flex items-center gap-1">
- <span>Allow N/A responses</span>
- <Tooltip
- title={
- isHog
- ? 'When enabled, returning null from your Hog code means "not applicable" instead of being treated as an error.'
- : 'Sometimes forcing a True or False is not enough and you want the LLM to decide if the evaluation is applicable or not. Enable this when the evaluation criteria may not apply to all generations.'
- }
- >
+ {isReportableEvaluation && (
+ <Field
+ name="allows_na"
+ label={
+ <div className="flex items-center gap-1">
+ <span>Allow N/A responses</span>
+ <Tooltip
+ title={
+ isHog
+ ? 'When enabled, returning null from your Hog code means "not applicable" instead of being treated as an error.'
+ : 'Sometimes forcing a True or False is not enough and you want the LLM to decide if the evaluation is applicable or not. Enable this when the evaluation criteria may not apply to all generations.'
+ }
+ >
+ <IconInfo className="text-muted text-base" />
+ </Tooltip>
+ </div>
+ }
+ >
+ <div className="flex items-center gap-2">
+ <LemonSwitch
+ checked={evaluation.output_config.allows_na ?? false}
+ onChange={setAllowsNA}
+ />
+ <span className="text-muted text-sm">
+ {evaluation.output_config.allows_na
+ ? isHog
+ ? 'Returning null means "Not Applicable"'
+ : 'Evaluation can return "Not Applicable" when criteria doesn\'t apply'
+ : isHog
+ ? 'Evaluation must return true or false'
+ : 'Evaluation returns true or false'}
+ </span>
+ </div>
+ </Field>
+ )}
+ {!isNewEvaluation &&
+ user?.is_staff &&
+ evaluationTypeSupportsSignalEmission(evaluation.evaluation_type) && (
+ <div className="flex items-center gap-2">
+ <LemonSwitch
+ checked={signalEmissionEnabled}
+ onChange={setSignalEmission}
+ />
+ <span>Emit signals</span>
+ <Tooltip title="When enabled, true verdicts from this evaluation will be emitted as signals for clustering and investigation.">
<IconInfo className="text-muted text-base" />
</Tooltip>
</div>
- }
- >
- <div className="flex items-center gap-2">
- <LemonSwitch
- checked={evaluation.output_config.allows_na ?? false}
- onChange={setAllowsNA}
- />
- <span className="text-muted text-sm">
- {evaluation.output_config.allows_na
- ? isHog
- ? 'Returning null means "Not Applicable"'
- : 'Evaluation can return "Not Applicable" when criteria doesn\'t apply'
- : isHog
- ? 'Evaluation must return true or false'
- : 'Evaluation returns true or false'}
- </span>
- </div>
- </Field>
- {!isNewEvaluation && user?.is_staff && (
- <div className="flex items-center gap-2">
- <LemonSwitch
- checked={signalEmissionEnabled}
- onChange={setSignalEmission}
- />
- <span>Emit signals</span>
- <Tooltip title="When enabled, true verdicts from this evaluation will be emitted as signals for clustering and investigation.">
- <IconInfo className="text-muted text-base" />
- </Tooltip>
- </div>
- )}
+ )}
</div>
</div>
{/* Prompt / Code Configuration */}
- <div className="bg-bg-light border rounded p-6">
- <h3 className="text-lg font-semibold mb-4">
- {isHog ? 'Evaluation code' : 'Evaluation prompt'}
- </h3>
- {isHog ? <EvaluationCodeEditor /> : <EvaluationPromptEditor />}
- </div>
+ {hasEditableCriteria && (
+ <div className="bg-bg-light border rounded p-6">
+ <h3 className="text-lg font-semibold mb-4">
+ {isHog ? 'Evaluation code' : 'Evaluation prompt'}
+ </h3>
+ {isHog ? <EvaluationCodeEditor /> : <EvaluationPromptEditor />}
+ </div>
+ )}
{/* Judge Model Configuration (LLM judge only) */}
- {!isHog && featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_CUSTOM_MODELS] && (
- <EvaluationModelPicker />
- )}
+ {evaluationTypeUsesModelConfiguration(evaluation.evaluation_type) &&
+ featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_CUSTOM_MODELS] && (
+ <EvaluationModelPicker />
+ )}
{/* Trigger Configuration */}
<div ref={triggersRef} className="bg-bg-light border rounded p-6">
@@ -515,17 +570,20 @@ export function AIObservabilityEvaluation(): JSX.Element {
{/* Scheduled Reports (inline config for new evaluations) */}
{isNewEvaluation &&
+ isReportableEvaluation &&
featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_REPORTS] && (
<EvaluationReportConfig evaluationId="new" />
)}
</Form>
{/* Scheduled Reports (for existing evaluations, outside the form) */}
- {!isNewEvaluation && featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_REPORTS] && (
- <div className="mt-6">
- <EvaluationReportConfig evaluationId={evaluation.id} />
- </div>
- )}
+ {!isNewEvaluation &&
+ isReportableEvaluation &&
+ featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_REPORTS] && (
+ <div className="mt-6">
+ <EvaluationReportConfig evaluationId={evaluation.id} />
+ </div>
+ )}
</div>
),
},
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
index 8ff983da9d8f..5ee62e939f13 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
@@ -46,6 +46,7 @@ import {
PASS_RATE_WARNING_THRESHOLD,
} from './components/EvaluationMetrics'
import { OfflineEvaluationsTab } from './components/OfflineEvaluationsTab'
+import { evaluationTypeCanBeCreated, evaluationTypeUsesProviderKey } from './evaluationCapabilities'
import { EvaluationStats, evaluationMetricsLogic } from './evaluationMetricsLogic'
import { EvaluationTemplatesEmptyState } from './EvaluationTemplates'
import { llmEvaluationsLogic } from './llmEvaluationsLogic'
@@ -78,13 +79,43 @@ function getActiveTab(
}
function getProviderKeyIssue(evaluation: EvaluationConfig, providerKeys: LLMProviderKey[]): LLMProviderKey | null {
- if (evaluation.evaluation_type === 'hog') {
+ if (!evaluationTypeUsesProviderKey(evaluation.evaluation_type)) {
return null
}
return getUnhealthyProviderKey(providerKeys, evaluation.model_configuration?.provider_key_id)
}
+function getEvaluationMethodLabel(evaluation: EvaluationConfig): string {
+ if (evaluation.evaluation_type === 'hog') {
+ return 'Hog'
+ }
+ if (evaluation.evaluation_type === 'sentiment') {
+ return 'Sentiment'
+ }
+ return 'LLM judge'
+}
+
+function getEvaluationMethodTagType(evaluation: EvaluationConfig): 'option' | 'highlight' | 'caution' {
+ if (evaluation.evaluation_type === 'hog') {
+ return 'option'
+ }
+ if (evaluation.evaluation_type === 'sentiment') {
+ return 'highlight'
+ }
+ return 'caution'
+}
+
+function getEvaluationConfigPreview(evaluation: EvaluationConfig): string {
+ if (evaluation.evaluation_type === 'hog') {
+ return evaluation.evaluation_config.source
+ }
+ if (evaluation.evaluation_type === 'sentiment') {
+ return 'User messages'
+ }
+ return evaluation.evaluation_config.prompt
+}
+
function AIObservabilityEvaluationsContent(): JSX.Element {
const evaluationsLogic = llmEvaluationsLogic()
const metricsLogic = evaluationMetricsLogic()
@@ -102,6 +133,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
useActions(evaluationsLogic)
const { evaluationsWithMetrics } = useValues(metricsLogic)
const { currentTeamId } = useValues(teamLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
const { push } = useActions(router)
const { searchParams } = useValues(router)
const evaluationUrl = (id: string): string => combineUrl(urls.aiObservabilityEvaluation(id), searchParams).url
@@ -159,21 +191,19 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
</Tooltip>
)
}
- const canEnable = canEnableEvaluation(evaluation)
+ const canUseEvaluationType = evaluationTypeCanBeCreated(evaluation.evaluation_type, featureFlags)
+ const canEnable = canEnableEvaluation(evaluation) && (evaluation.enabled || canUseEvaluationType)
const isBlocked = !canEnable && !evaluation.enabled
+ const blockedReason = !canUseEvaluationType
+ ? 'Sentiment evaluations are not available for this project.'
+ : 'Trial evaluation limit reached. Add a provider API key to re-enable.'
return (
<div className="flex items-center gap-2">
<AccessControlAction
resourceType={AccessControlResourceType.LlmAnalytics}
minAccessLevel={AccessControlLevel.Editor}
>
- <Tooltip
- title={
- isBlocked
- ? 'Trial evaluation limit reached. Add a provider API key to re-enable.'
- : undefined
- }
- >
+ <Tooltip title={isBlocked ? blockedReason : undefined}>
<span>
<LemonSwitch
checked={evaluation.enabled}
@@ -201,8 +231,8 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
title: 'Method',
key: 'method',
render: (_, evaluation) => (
- <LemonTag type={evaluation.evaluation_type === 'hog' ? 'option' : 'caution'}>
- {evaluation.evaluation_type === 'hog' ? 'Hog' : 'LLM judge'}
+ <LemonTag type={getEvaluationMethodTagType(evaluation)}>
+ {getEvaluationMethodLabel(evaluation)}
</LemonTag>
),
},
@@ -210,10 +240,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
title: 'Config',
key: 'config',
render: (_, evaluation) => {
- const preview =
- evaluation.evaluation_type === 'hog'
- ? evaluation.evaluation_config.source
- : evaluation.evaluation_config.prompt
+ const preview = getEvaluationConfigPreview(evaluation)
return (
<div className="max-w-md">
<div className="text-sm font-mono bg-bg-light border rounded px-2 py-1 truncate">
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
index f57b32cf503c..d26990722b6c 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
@@ -1,23 +1,26 @@
import { useActions, useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
-import { IconCheck, IconMinus, IconRefresh, IconWarning, IconX } from '@posthog/icons'
+import { IconRefresh } from '@posthog/icons'
import { LemonButton, LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { urls } from 'scenes/urls'
+import { EvaluationResultTag, getEvaluationResultSortValue } from '../../components/EvaluationResultTag'
import { sanitizeTraceUrlSearchParams } from '../../utils'
+import { evaluationSupportsReports } from '../evaluationCapabilities'
import { llmEvaluationLogic } from '../llmEvaluationLogic'
import { EvaluationRun } from '../types'
import { EvaluationSummaryControls, EvaluationSummaryPanel } from './EvaluationSummaryPanel'
export function EvaluationRunsTable(): JSX.Element {
- const { filteredEvaluationRuns, evaluationRunsLoading, runsLookup } = useValues(llmEvaluationLogic)
+ 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 columns: LemonTableColumns<EvaluationRun> = [
{
@@ -53,45 +56,9 @@ export function EvaluationRunsTable(): JSX.Element {
{
title: 'Result',
key: 'result',
- render: (_, run) => {
- if (run.status === 'failed') {
- return (
- <LemonTag type="danger" icon={<IconWarning />}>
- Error
- </LemonTag>
- )
- }
- if (run.status === 'running') {
- return <LemonTag type="primary">Running...</LemonTag>
- }
- if (run.result === null) {
- return (
- <LemonTag type="muted" icon={<IconMinus />}>
- N/A
- </LemonTag>
- )
- }
- return (
- <div className="flex items-center gap-2">
- {run.result ? (
- <LemonTag type="success" icon={<IconCheck />}>
- True
- </LemonTag>
- ) : (
- <LemonTag type="danger" icon={<IconX />}>
- False
- </LemonTag>
- )}
- </div>
- )
- },
+ render: (_, run) => <EvaluationResultTag run={run} />,
sorter: (a, b) => {
- if (a.status !== 'completed' || b.status !== 'completed') {
- return a.status.localeCompare(b.status)
- }
- const valA = a.result === null ? 0.5 : Number(a.result)
- const valB = b.result === null ? 0.5 : Number(b.result)
- return valB - valA
+ return getEvaluationResultSortValue(b) - getEvaluationResultSortValue(a)
},
},
{
@@ -123,7 +90,7 @@ export function EvaluationRunsTable(): JSX.Element {
return (
<div className="space-y-4">
<div className="flex justify-between items-center">
- <EvaluationSummaryControls />
+ {showSummary ? <EvaluationSummaryControls /> : <div />}
<LemonButton
type="secondary"
icon={<IconRefresh />}
@@ -136,7 +103,7 @@ export function EvaluationRunsTable(): JSX.Element {
</LemonButton>
</div>
- <EvaluationSummaryPanel runsLookup={runsLookup} />
+ {showSummary && <EvaluationSummaryPanel runsLookup={runsLookup} />}
<LemonTable
columns={columns}
diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
new file mode 100644
index 000000000000..e424a663806f
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts
@@ -0,0 +1,16 @@
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { evaluationTypeCanBeCreated } from './evaluationCapabilities'
+
+describe('evaluationCapabilities', () => {
+ it('gates sentiment creation on the sentiment evaluations feature flag', () => {
+ expect(evaluationTypeCanBeCreated('llm_judge', {})).toBe(true)
+ expect(evaluationTypeCanBeCreated('hog', {})).toBe(true)
+ expect(evaluationTypeCanBeCreated('sentiment', {})).toBe(false)
+ expect(
+ evaluationTypeCanBeCreated('sentiment', {
+ [FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_SENTIMENT]: true,
+ })
+ ).toBe(true)
+ })
+})
diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
new file mode 100644
index 000000000000..bc72eca2cb47
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
@@ -0,0 +1,47 @@
+import { FEATURE_FLAGS } from 'lib/constants'
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+
+import type { EvaluationConfig, EvaluationOutputType, EvaluationType, LLMJudgeEvaluation } from './types'
+
+export function isBooleanEvaluationOutput(outputType: EvaluationOutputType | null | undefined): boolean {
+ return outputType === 'boolean'
+}
+
+export function evaluationSupportsReports(
+ evaluation: Pick<EvaluationConfig, 'output_type'> | null | undefined
+): boolean {
+ return isBooleanEvaluationOutput(evaluation?.output_type)
+}
+
+export function evaluationTypeUsesModelConfiguration(evaluationType: EvaluationType | null | undefined): boolean {
+ return evaluationType === 'llm_judge'
+}
+
+export function isLLMJudgeEvaluation(
+ evaluation: EvaluationConfig | null | undefined
+): evaluation is LLMJudgeEvaluation {
+ return evaluation?.evaluation_type === 'llm_judge'
+}
+
+export function evaluationTypeUsesProviderKey(evaluationType: EvaluationType | null | undefined): boolean {
+ return evaluationTypeUsesModelConfiguration(evaluationType)
+}
+
+export function evaluationTypeDefaultsToBooleanOutput(evaluationType: EvaluationType | null | undefined): boolean {
+ return evaluationType === 'llm_judge' || evaluationType === 'hog'
+}
+
+export function evaluationTypeHasEditableCriteria(evaluationType: EvaluationType | null | undefined): boolean {
+ return evaluationTypeDefaultsToBooleanOutput(evaluationType)
+}
+
+export function evaluationTypeSupportsSignalEmission(evaluationType: EvaluationType | null | undefined): boolean {
+ return evaluationType === 'llm_judge'
+}
+
+export function evaluationTypeCanBeCreated(
+ evaluationType: EvaluationType,
+ featureFlags: FeatureFlagsSet | null | undefined
+): boolean {
+ return evaluationType !== 'sentiment' || !!featureFlags?.[FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_SENTIMENT]
+}
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index 78cdcc6f08b9..7d619625e0dc 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -704,6 +704,33 @@ describe('llmEvaluationLogic', () => {
})
})
+ it('setEvaluationType switches to sentiment config shape', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+
+ 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,
+ }),
+ })
+ })
+
+ it('switching to sentiment moves away from reports tab', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+
+ logic.actions.setActiveTab('reports')
+ logic.actions.setEvaluationType('sentiment')
+
+ await expectLogic(logic).toMatchValues({
+ activeTab: 'configuration',
+ })
+ })
+
it('setHogSource updates source in hog config', async () => {
await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
@@ -749,6 +776,30 @@ describe('llmEvaluationLogic', () => {
await expectLogic(logic).toMatchValues({ formValid: false })
})
+ it('formValid does not require prompt or code for sentiment type', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+
+ logic.actions.setEvaluationType('sentiment')
+ logic.actions.setEvaluationName('Valid Name')
+ logic.actions.setTriggerConditions([{ id: 'c1', rollout_percentage: 50, properties: [] }])
+
+ await expectLogic(logic).toMatchValues({ formValid: true })
+ })
+
+ it('setAllowsNA does not mutate sentiment output config', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+
+ logic.actions.setEvaluationType('sentiment')
+ logic.actions.setAllowsNA(true)
+
+ await expectLogic(logic).toMatchValues({
+ evaluation: expect.objectContaining({
+ output_type: 'sentiment',
+ output_config: {},
+ }),
+ })
+ })
+
it('setEvaluationType marks unsaved changes', async () => {
await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index 30732d6c5fc3..9b6660135380 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -19,18 +19,28 @@ import { getUnhealthyProviderKey } from '../settings/providerKeyStateUtils'
import { queryEvaluationRuns } from '../utils'
import { evaluationErrorMessage } from './apiErrors'
import { EVALUATION_SUMMARY_MAX_RUNS } from './constants'
+import {
+ evaluationSupportsReports,
+ evaluationTypeDefaultsToBooleanOutput,
+ evaluationTypeUsesProviderKey,
+ isBooleanEvaluationOutput,
+ isLLMJudgeEvaluation,
+} from './evaluationCapabilities'
import { evaluationReportLogic, persistReportDraft } from './evaluationReportLogic'
import type { llmEvaluationLogicType } from './llmEvaluationLogicType'
import { EvaluationTemplateKey, defaultEvaluationTemplates } from './templates'
-import {
+import type {
EvaluationConditionSet,
EvaluationConfig,
EvaluationRun,
EvaluationSummary,
EvaluationSummaryFilter,
EvaluationType,
+ HogEvaluation,
+ LLMJudgeEvaluation,
HogTestResult,
ModelConfiguration,
+ SentimentEvaluation,
} from './types'
export const DEFAULT_HOG_SOURCE = `// Check that the output is not empty
@@ -40,6 +50,40 @@ if (not result) {
}
return result`
+const DEFAULT_SENTIMENT_SOURCE = 'user_messages' as const
+
+function toLLMJudgeEvaluation(evaluation: EvaluationConfig): LLMJudgeEvaluation {
+ return {
+ ...evaluation,
+ evaluation_type: 'llm_judge',
+ evaluation_config: { prompt: '' },
+ output_type: 'boolean',
+ output_config: { allows_na: false },
+ }
+}
+
+function toHogEvaluation(evaluation: EvaluationConfig): HogEvaluation {
+ return {
+ ...evaluation,
+ evaluation_type: 'hog',
+ evaluation_config: { source: DEFAULT_HOG_SOURCE },
+ output_type: 'boolean',
+ model_configuration: null,
+ output_config: { ...evaluation.output_config, allows_na: false },
+ }
+}
+
+function toSentimentEvaluation(evaluation: EvaluationConfig): SentimentEvaluation {
+ return {
+ ...evaluation,
+ evaluation_type: 'sentiment',
+ evaluation_config: { source: DEFAULT_SENTIMENT_SOURCE },
+ output_type: 'sentiment',
+ output_config: {},
+ model_configuration: null,
+ }
+}
+
export interface LLMEvaluationLogicProps {
evaluationId: string
templateKey?: EvaluationTemplateKey
@@ -181,6 +225,9 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
if (!teamId || !props.evaluationId || props.evaluationId === 'new') {
return null
}
+ if (!evaluationSupportsReports(values.evaluation)) {
+ return null
+ }
const requestFilter = values.evaluationSummaryFilter
@@ -217,12 +264,14 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
setEvaluationName: (state, { name }) => (state ? { ...state, name } : null),
setEvaluationDescription: (state, { description }) => (state ? { ...state, description } : null),
setEvaluationPrompt: (state, { prompt }) =>
- state && state.evaluation_type === 'llm_judge'
+ state && isLLMJudgeEvaluation(state)
? { ...state, evaluation_config: { ...state.evaluation_config, prompt } }
: state,
setEvaluationEnabled: (state, { enabled }) => (state ? { ...state, enabled } : null),
setAllowsNA: (state, { allowsNA }) =>
- state ? { ...state, output_config: { ...state.output_config, allows_na: allowsNA } } : null,
+ state && isBooleanEvaluationOutput(state.output_type)
+ ? { ...state, output_config: { ...state.output_config, allows_na: allowsNA } }
+ : state,
setTriggerConditions: (state, { conditions }) =>
state
? {
@@ -235,25 +284,20 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
}
: null,
setModelConfiguration: (state, { modelConfiguration }) =>
- state ? { ...state, model_configuration: modelConfiguration } : null,
+ state && isLLMJudgeEvaluation(state)
+ ? { ...state, model_configuration: modelConfiguration }
+ : state,
setEvaluationType: (state, { evaluationType }) => {
if (!state) {
return null
}
if (evaluationType === 'hog') {
- return {
- ...state,
- evaluation_type: 'hog',
- evaluation_config: { source: DEFAULT_HOG_SOURCE },
- model_configuration: null,
- output_config: { ...state.output_config, allows_na: false },
- }
+ return toHogEvaluation(state)
}
- return {
- ...state,
- evaluation_type: 'llm_judge',
- evaluation_config: { prompt: '' },
+ if (evaluationType === 'sentiment') {
+ return toSentimentEvaluation(state)
}
+ return toLLMJudgeEvaluation(state)
},
setHogSource: (state, { source }) =>
state && state.evaluation_type === 'hog'
@@ -553,7 +597,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
// reading .values on an unmounted keyed logic would throw.
const reportLogicKey = isNew ? 'new' : props.evaluationId
const reportLogic = evaluationReportLogic({ evaluationId: reportLogicKey })
- if (response?.id && reportLogic.isMounted()) {
+ if (response?.id && evaluationSupportsReports(response) && reportLogic.isMounted()) {
try {
await persistReportDraft(
teamId,
@@ -599,6 +643,11 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
})
}
},
+ setEvaluationType: ({ evaluationType }) => {
+ if (!evaluationTypeDefaultsToBooleanOutput(evaluationType) && values.activeTab === 'reports') {
+ actions.setActiveTab('configuration')
+ }
+ },
})),
selectors({
@@ -639,7 +688,9 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
let hasValidConfig = false
if (evaluation.evaluation_type === 'hog') {
hasValidConfig = evaluation.evaluation_config.source.trim().length > 0
- } else {
+ } else if (evaluation.evaluation_type === 'sentiment') {
+ hasValidConfig = true
+ } else if (isLLMJudgeEvaluation(evaluation)) {
hasValidConfig = evaluation.evaluation_config.prompt.length > 0
}
@@ -653,8 +704,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
if (!evaluation || !isTrialLimitReached) {
return true
}
- // Hog evals don't call an LLM and never consume trial quota
- if (evaluation.evaluation_type === 'hog') {
+ if (!evaluationTypeUsesProviderKey(evaluation.evaluation_type)) {
return true
}
// Can enable if the evaluation has a BYOK key
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
index 1806dc9ee618..be10caf590c4 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
@@ -1,11 +1,14 @@
import { expectLogic } from 'kea-test-utils'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'
import { llmEvaluationsLogic } from './llmEvaluationsLogic'
-import { EvaluationConfig } from './types'
+import { HogEvaluation, LLMJudgeEvaluation, SentimentEvaluation } from './types'
const mockProviderKeys: LLMProviderKey[] = [
{
@@ -49,7 +52,7 @@ const mockProviderKeys: LLMProviderKey[] = [
},
]
-const evaluationWithKey = (id: string, providerKeyId: string | null): EvaluationConfig => ({
+const evaluationWithKey = (id: string, providerKeyId: string | null): LLMJudgeEvaluation => ({
id,
name: `Evaluation ${id}`,
description: '',
@@ -73,6 +76,22 @@ const evaluationWithKey = (id: string, providerKeyId: string | null): Evaluation
updated_at: '2024-01-01T00:00:00Z',
})
+const hogEvaluation = (id: string): HogEvaluation => ({
+ ...evaluationWithKey(id, null),
+ evaluation_type: 'hog',
+ evaluation_config: { source: 'return true' },
+ model_configuration: null,
+})
+
+const sentimentEvaluation = (id: string): SentimentEvaluation => ({
+ ...evaluationWithKey(id, null),
+ evaluation_type: 'sentiment',
+ evaluation_config: { source: 'user_messages' },
+ output_type: 'sentiment',
+ output_config: {},
+ model_configuration: null,
+})
+
describe('llmEvaluationsLogic', () => {
let logic: ReturnType<typeof llmEvaluationsLogic.build>
let keysLogic: ReturnType<typeof llmProviderKeysLogic.build>
@@ -115,6 +134,24 @@ describe('llmEvaluationsLogic', () => {
})
describe('unhealthyProviderKeysUsedByEvaluations', () => {
+ it('allows Hog and sentiment evaluations when trial limit is reached', async () => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_SENTIMENT], {
+ [FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS_SENTIMENT]: true,
+ })
+ keysLogic.actions.loadEvaluationConfigSuccess({
+ trial_eval_limit: 100,
+ trial_evals_used: 100,
+ trial_evals_remaining: 0,
+ active_provider_key: null,
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ })
+
+ expect(logic.values.canEnableEvaluation(hogEvaluation('hog'))).toBe(true)
+ expect(logic.values.canEnableEvaluation(sentimentEvaluation('sentiment'))).toBe(true)
+ expect(logic.values.canEnableEvaluation(evaluationWithKey('llm-default', null))).toBe(false)
+ })
+
it('returns unhealthy keys used by evaluations without duplicates', async () => {
logic.actions.loadEvaluations()
keysLogic.actions.loadProviderKeys()
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
index 67eca10ea708..1c3ac0981218 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
@@ -15,6 +15,7 @@ import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-genera
import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'
import { getUnhealthyProviderKey } from '../settings/providerKeyStateUtils'
import { evaluationErrorMessage } from './apiErrors'
+import { evaluationTypeCanBeCreated, evaluationTypeUsesProviderKey } from './evaluationCapabilities'
import type { llmEvaluationsLogicType } from './llmEvaluationsLogicType'
import { EvaluationConfig } from './types'
@@ -186,6 +187,10 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
if (!original) {
return
}
+ if (!evaluationTypeCanBeCreated(original.evaluation_type, values.featureFlags)) {
+ lemonToast.error('Sentiment evaluations are not available for this project.')
+ return
+ }
const duplicate = {
name: `${original.name} (Copy)`,
@@ -262,8 +267,7 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
if (!isTrialLimitReached) {
return true
}
- // Hog evals don't call an LLM and never consume trial quota
- if (evaluation.evaluation_type === 'hog') {
+ if (!evaluationTypeUsesProviderKey(evaluation.evaluation_type)) {
return true
}
return !!evaluation.model_configuration?.provider_key_id
diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.ts
index fa1a1e593e2d..84a7e28cefaf 100644
--- a/products/ai_observability/frontend/evaluations/types.ts
+++ b/products/ai_observability/frontend/evaluations/types.ts
@@ -2,8 +2,8 @@ import { AnyPropertyFilter } from '~/types'
import { LLMProvider } from '../settings/llmProviderKeysLogic'
-export type EvaluationType = 'llm_judge' | 'hog'
-export type EvaluationOutputType = 'boolean'
+export type EvaluationType = 'llm_judge' | 'hog' | 'sentiment'
+export type EvaluationOutputType = 'boolean' | 'sentiment'
export type EvaluationStatus = 'active' | 'paused' | 'error'
export type EvaluationStatusReason = 'trial_limit_reached' | 'model_not_allowed' | 'provider_key_deleted'
@@ -27,6 +27,10 @@ export interface HogEvaluationConfig {
bytecode?: unknown[]
}
+export interface SentimentEvaluationConfig {
+ source: 'user_messages'
+}
+
export interface BaseEvaluationConfig {
id: string
name: string
@@ -47,15 +51,24 @@ export interface BaseEvaluationConfig {
export interface LLMJudgeEvaluation extends BaseEvaluationConfig {
evaluation_type: 'llm_judge'
+ output_type: 'boolean'
evaluation_config: LLMJudgeEvaluationConfig
}
export interface HogEvaluation extends BaseEvaluationConfig {
evaluation_type: 'hog'
+ output_type: 'boolean'
evaluation_config: HogEvaluationConfig
}
-export type EvaluationConfig = LLMJudgeEvaluation | HogEvaluation
+export interface SentimentEvaluation extends BaseEvaluationConfig {
+ evaluation_type: 'sentiment'
+ output_type: 'sentiment'
+ evaluation_config: SentimentEvaluationConfig
+ model_configuration: null
+}
+
+export type EvaluationConfig = LLMJudgeEvaluation | HogEvaluation | SentimentEvaluation
export interface EvaluationConditionSet {
id: string
@@ -74,7 +87,11 @@ export interface EvaluationRun {
generation_id: string | null
trace_id: string
timestamp: string
+ evaluation_type?: EvaluationType
+ result_type?: EvaluationOutputType
result: boolean | null
+ sentiment_label?: string | null
+ sentiment_score?: number | null
applicable?: boolean
reasoning: string
status: 'completed' | 'failed' | 'running'
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index 36df5d2927e2..f5748cc85da0 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -341,21 +341,25 @@ export const StatusReasonEnumApi = {
/**
* * `llm_judge` - LLM as a judge
* * `hog` - Hog
+ * * `sentiment` - Sentiment analysis
*/
export type EvaluationTypeEnumApi = (typeof EvaluationTypeEnumApi)[keyof typeof EvaluationTypeEnumApi]
export const EvaluationTypeEnumApi = {
LlmJudge: 'llm_judge',
Hog: 'hog',
+ Sentiment: 'sentiment',
} as const
/**
* * `boolean` - Boolean (Pass/Fail)
+ * * `sentiment` - Sentiment
*/
export type OutputTypeEnumApi = (typeof OutputTypeEnumApi)[keyof typeof OutputTypeEnumApi]
export const OutputTypeEnumApi = {
Boolean: 'boolean',
+ Sentiment: 'sentiment',
} as const
export type EvaluationConditionApiPropertiesItem = { [key: string]: unknown }
@@ -414,7 +418,7 @@ export interface ModelConfigurationApi {
}
/**
- * Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}.
+ * Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}.
*/
export type EvaluationApiEvaluationConfig =
| {
@@ -431,6 +435,10 @@ export type EvaluationApiEvaluationConfig =
*/
source: string
}
+ | {
+ /** Classify sentiment from user messages in the generation input. */
+ source?: 'user_messages'
+ }
/**
* Output config. For 'boolean' output_type: {allows_na} to permit N/A results.
@@ -453,16 +461,18 @@ export interface EvaluationApi {
enabled?: boolean
readonly status: EvaluationStatusEnumApi
readonly status_reason: StatusReasonEnumApi | null
- /** 'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code.
+ /** 'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.
*
* * `llm_judge` - LLM as a judge
- * * `hog` - Hog */
+ * * `hog` - Hog
+ * * `sentiment` - Sentiment analysis */
evaluation_type: EvaluationTypeEnumApi
- /** Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}. */
+ /** Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}. */
evaluation_config?: EvaluationApiEvaluationConfig
- /** Output format. Currently only 'boolean' is supported.
+ /** Output format. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.
*
- * * `boolean` - Boolean (Pass/Fail) */
+ * * `boolean` - Boolean (Pass/Fail)
+ * * `sentiment` - Sentiment */
output_type: OutputTypeEnumApi
/** Output config. For 'boolean' output_type: {allows_na} to permit N/A results. */
output_config?: EvaluationApiOutputConfig
@@ -486,7 +496,7 @@ export interface PaginatedEvaluationListApi {
}
/**
- * Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}.
+ * Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}.
*/
export type PatchedEvaluationApiEvaluationConfig =
| {
@@ -503,6 +513,10 @@ export type PatchedEvaluationApiEvaluationConfig =
*/
source: string
}
+ | {
+ /** Classify sentiment from user messages in the generation input. */
+ source?: 'user_messages'
+ }
/**
* Output config. For 'boolean' output_type: {allows_na} to permit N/A results.
@@ -525,16 +539,18 @@ export interface PatchedEvaluationApi {
enabled?: boolean
readonly status?: EvaluationStatusEnumApi
readonly status_reason?: StatusReasonEnumApi | null
- /** 'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code.
+ /** 'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.
*
* * `llm_judge` - LLM as a judge
- * * `hog` - Hog */
+ * * `hog` - Hog
+ * * `sentiment` - Sentiment analysis */
evaluation_type?: EvaluationTypeEnumApi
- /** Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}. */
+ /** Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}. */
evaluation_config?: PatchedEvaluationApiEvaluationConfig
- /** Output format. Currently only 'boolean' is supported.
+ /** Output format. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.
*
- * * `boolean` - Boolean (Pass/Fail) */
+ * * `boolean` - Boolean (Pass/Fail)
+ * * `sentiment` - Sentiment */
output_type?: OutputTypeEnumApi
/** Output config. For 'boolean' output_type: {allows_na} to permit N/A results. */
output_config?: PatchedEvaluationApiOutputConfig
diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.ts
index 4d3871513b77..07000f51719e 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -104,6 +104,7 @@ export const EvaluationRunsCreateBody = /* @__PURE__ */ zod.object({
export const evaluationsCreateBodyNameMax = 400
+export const evaluationsCreateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsCreateBodyOutputConfigAllowsNaDefault = false
export const evaluationsCreateBodyConditionsItemIdMax = 100
@@ -121,10 +122,10 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('Whether the evaluation runs automatically on new $ai_generation events.'),
evaluation_type: zod
- .enum(['llm_judge', 'hog'])
- .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog')
+ .enum(['llm_judge', 'hog', 'sentiment'])
+ .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis')
.describe(
- "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code.\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog"
+ "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis"
),
evaluation_config: zod
.union([
@@ -140,13 +141,23 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({
.min(1)
.describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),
}),
+ zod.object({
+ source: zod
+ .enum(['user_messages'])
+ .default(evaluationsCreateBodyEvaluationConfigThreeSourceDefault)
+ .describe('Classify sentiment from user messages in the generation input.'),
+ }),
])
.optional()
- .describe("Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}."),
+ .describe(
+ "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
+ ),
output_type: zod
- .enum(['boolean'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)')
- .describe("Output format. Currently only 'boolean' is supported.\n\n\* `boolean` - Boolean (Pass\/Fail)"),
+ .enum(['boolean', 'sentiment'])
+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')
+ .describe(
+ "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"
+ ),
output_config: zod
.object({
allows_na: zod
@@ -215,6 +226,7 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({
export const evaluationsUpdateBodyNameMax = 400
+export const evaluationsUpdateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsUpdateBodyOutputConfigAllowsNaDefault = false
export const evaluationsUpdateBodyConditionsItemIdMax = 100
@@ -232,10 +244,10 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('Whether the evaluation runs automatically on new $ai_generation events.'),
evaluation_type: zod
- .enum(['llm_judge', 'hog'])
- .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog')
+ .enum(['llm_judge', 'hog', 'sentiment'])
+ .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis')
.describe(
- "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code.\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog"
+ "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis"
),
evaluation_config: zod
.union([
@@ -251,13 +263,23 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod.object({
.min(1)
.describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),
}),
+ zod.object({
+ source: zod
+ .enum(['user_messages'])
+ .default(evaluationsUpdateBodyEvaluationConfigThreeSourceDefault)
+ .describe('Classify sentiment from user messages in the generation input.'),
+ }),
])
.optional()
- .describe("Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}."),
+ .describe(
+ "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
+ ),
output_type: zod
- .enum(['boolean'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)')
- .describe("Output format. Currently only 'boolean' is supported.\n\n\* `boolean` - Boolean (Pass\/Fail)"),
+ .enum(['boolean', 'sentiment'])
+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')
+ .describe(
+ "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"
+ ),
output_config: zod
.object({
allows_na: zod
@@ -326,6 +348,7 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod.object({
export const evaluationsPartialUpdateBodyNameMax = 400
+export const evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsPartialUpdateBodyOutputConfigAllowsNaDefault = false
export const evaluationsPartialUpdateBodyConditionsItemIdMax = 100
@@ -343,11 +366,11 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('Whether the evaluation runs automatically on new $ai_generation events.'),
evaluation_type: zod
- .enum(['llm_judge', 'hog'])
- .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog')
+ .enum(['llm_judge', 'hog', 'sentiment'])
+ .describe('\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis')
.optional()
.describe(
- "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code.\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog"
+ "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.\n\n\* `llm_judge` - LLM as a judge\n\* `hog` - Hog\n\* `sentiment` - Sentiment analysis"
),
evaluation_config: zod
.union([
@@ -363,14 +386,24 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({
.min(1)
.describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),
}),
+ zod.object({
+ source: zod
+ .enum(['user_messages'])
+ .default(evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault)
+ .describe('Classify sentiment from user messages in the generation input.'),
+ }),
])
.optional()
- .describe("Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}."),
+ .describe(
+ "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
+ ),
output_type: zod
- .enum(['boolean'])
- .describe('\* `boolean` - Boolean (Pass\/Fail)')
+ .enum(['boolean', 'sentiment'])
+ .describe('\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment')
.optional()
- .describe("Output format. Currently only 'boolean' is supported.\n\n\* `boolean` - Boolean (Pass\/Fail)"),
+ .describe(
+ "Output format. Use 'boolean' for pass\/fail evaluations and 'sentiment' for sentiment analysis.\n\n\* `boolean` - Boolean (Pass\/Fail)\n\* `sentiment` - Sentiment"
+ ),
output_config: zod
.object({
allows_na: zod
diff --git a/products/ai_observability/frontend/utils.test.ts b/products/ai_observability/frontend/utils.test.ts
index 0be49e6a2dcd..6c83e25f65d9 100644
--- a/products/ai_observability/frontend/utils.test.ts
+++ b/products/ai_observability/frontend/utils.test.ts
@@ -21,11 +21,105 @@ import {
isToolResult,
isToolStepItem,
looksLikeXml,
+ mapEvaluationRunRow,
parsePartialJSON,
parseToolArgumentsForDisplay,
sanitizeTraceUrlSearchParams,
} from './utils'
+type EvaluationRunRow = Parameters<typeof mapEvaluationRunRow>[0]
+
+interface EvaluationRunRowOverrides {
+ result?: EvaluationRunRow[6]
+ applicable?: EvaluationRunRow[8]
+ evaluationType?: EvaluationRunRow[9]
+ resultType?: EvaluationRunRow[10]
+ sentimentLabel?: EvaluationRunRow[11]
+ sentimentScore?: EvaluationRunRow[12]
+}
+
+function makeEvaluationRunRow({
+ result = true,
+ applicable = true,
+ evaluationType = 'llm_judge',
+ resultType = 'boolean',
+ sentimentLabel = null,
+ sentimentScore = null,
+}: EvaluationRunRowOverrides = {}): EvaluationRunRow {
+ return [
+ 'run-1',
+ '2026-04-10T12:00:00Z',
+ 'eval-1',
+ 'Test Eval',
+ 'gen-1',
+ 'trace-1',
+ result,
+ 'Looks good',
+ applicable,
+ evaluationType,
+ resultType,
+ sentimentLabel,
+ sentimentScore,
+ ]
+}
+
+describe('mapEvaluationRunRow', () => {
+ it('maps sentiment rows without coercing missing boolean results to false', () => {
+ const run = mapEvaluationRunRow(
+ makeEvaluationRunRow({
+ result: null,
+ applicable: null,
+ evaluationType: 'sentiment',
+ resultType: 'sentiment',
+ sentimentLabel: 'positive',
+ sentimentScore: '0.91',
+ })
+ )
+
+ expect(run.result).toBeNull()
+ expect(run.evaluation_type).toBe('sentiment')
+ expect(run.result_type).toBe('sentiment')
+ expect(run.sentiment_label).toBe('positive')
+ expect(run.sentiment_score).toBe(0.91)
+ })
+
+ it('falls back to sentiment result type for older sentiment rows', () => {
+ const run = mapEvaluationRunRow(
+ makeEvaluationRunRow({
+ result: null,
+ applicable: null,
+ evaluationType: 'sentiment',
+ resultType: null,
+ sentimentLabel: 'negative',
+ })
+ )
+
+ expect(run.result_type).toBe('sentiment')
+ expect(run.result).toBeNull()
+ })
+
+ it('keeps absent boolean results as null instead of false', () => {
+ const run = mapEvaluationRunRow(makeEvaluationRunRow({ result: null }))
+
+ expect(run.result).toBeNull()
+ })
+
+ it.each([true, 'true', 'True', '1'])('maps explicit pass result %p', (result) => {
+ expect(mapEvaluationRunRow(makeEvaluationRunRow({ result })).result).toBe(true)
+ })
+
+ it.each([false, 'false', 'False', '0'])('maps explicit fail result %p', (result) => {
+ expect(mapEvaluationRunRow(makeEvaluationRunRow({ result })).result).toBe(false)
+ })
+
+ it('maps explicitly non-applicable rows to null', () => {
+ const run = mapEvaluationRunRow(makeEvaluationRunRow({ result: false, applicable: 'false' }))
+
+ expect(run.result).toBeNull()
+ expect(run.applicable).toBe(false)
+ })
+})
+
// The recipe-based `RecipeNormalizer` in `./normalizer` is the production code path.
const recipe = new RecipeNormalizer()
const IMPLS = [
diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.ts
index 6b121927dce2..b3ffad8f26aa 100644
--- a/products/ai_observability/frontend/utils.ts
+++ b/products/ai_observability/frontend/utils.ts
@@ -9,7 +9,7 @@ import { hogql } from '~/queries/utils'
import type { SpanAggregation } from './aiObservabilityTraceDataLogic'
import { EVALUATION_SUMMARY_MAX_RUNS } from './evaluations/constants'
-import type { EvaluationRun } from './evaluations/types'
+import type { EvaluationOutputType, EvaluationRun, EvaluationType } from './evaluations/types'
import {
AnthropicDocumentMessage,
AnthropicImageMessage,
@@ -1023,20 +1023,103 @@ type RawEvaluationRunRow = [
result: boolean | string | null,
reasoning: string | null,
applicable: boolean | string | null,
+ evaluation_type: string | null,
+ result_type: string | null,
+ sentiment_label: string | null,
+ sentiment_score: number | string | null,
]
-export function mapEvaluationRunRow(row: RawEvaluationRunRow): EvaluationRun {
- const rawResult = row[6]
- const applicable = row[8]
+export function normalizeEvaluationType(value: unknown): EvaluationType | undefined {
+ if (value === 'llm_judge' || value === 'hog' || value === 'sentiment') {
+ return value
+ }
+ return undefined
+}
+
+export function normalizeEvaluationOutputType(value: unknown): EvaluationOutputType | undefined {
+ if (value === 'boolean' || value === 'sentiment') {
+ return value
+ }
+ return undefined
+}
+
+export function normalizeOptionalNumber(value: unknown): number | null {
+ if (value === null || value === undefined) {
+ return null
+ }
+ const parsed = typeof value === 'number' ? value : Number(value)
+ return Number.isFinite(parsed) ? parsed : null
+}
+
+export function isExplicitEvaluationPass(value: unknown): boolean {
+ return value === true || value === 'true' || value === 'True' || value === '1'
+}
+
+function isExplicitEvaluationNotApplicable(value: unknown): boolean {
+ return value === false || value === 'false'
+}
+
+function normalizeEvaluationApplicable(value: unknown): boolean | undefined {
+ if (value === null || value === undefined) {
+ return undefined
+ }
+ return isExplicitEvaluationPass(value)
+}
+
+export interface NormalizedEvaluationResultProperties {
+ rawResult: unknown
+ rawApplicable?: unknown
+ rawEvaluationType?: unknown
+ rawResultType?: unknown
+ rawSentimentLabel?: unknown
+ rawSentimentScore?: unknown
+}
+
+export function normalizeEvaluationResultProperties({
+ rawResult,
+ rawApplicable,
+ rawEvaluationType,
+ rawResultType,
+ rawSentimentLabel,
+ rawSentimentScore,
+}: NormalizedEvaluationResultProperties): Pick<
+ EvaluationRun,
+ 'evaluation_type' | 'result_type' | 'result' | 'sentiment_label' | 'sentiment_score' | 'applicable'
+> {
+ const evaluationType = normalizeEvaluationType(rawEvaluationType)
+ const sentimentLabel =
+ typeof rawSentimentLabel === 'string' && rawSentimentLabel.length > 0 ? rawSentimentLabel : null
+ const resultType =
+ normalizeEvaluationOutputType(rawResultType) ??
+ (evaluationType === 'sentiment' || sentimentLabel ? 'sentiment' : 'boolean')
+
+ const result =
+ resultType === 'sentiment' ||
+ isExplicitEvaluationNotApplicable(rawApplicable) ||
+ rawResult === null ||
+ rawResult === undefined
+ ? null
+ : isExplicitEvaluationPass(rawResult)
- // N/A only when backend explicitly sets applicable=false
- // Otherwise, convert result to boolean (handle string 'false' from HogQL)
- let result: boolean | null
- if (applicable === false || applicable === 'false') {
- result = null
- } else {
- result = rawResult === true || rawResult === 'true'
+ return {
+ evaluation_type: evaluationType,
+ result_type: resultType,
+ result,
+ sentiment_label: sentimentLabel,
+ sentiment_score: normalizeOptionalNumber(rawSentimentScore),
+ applicable: normalizeEvaluationApplicable(rawApplicable),
}
+}
+
+export function mapEvaluationRunRow(row: RawEvaluationRunRow): EvaluationRun {
+ const normalizedResult = normalizeEvaluationResultProperties({
+ rawResult: row[6],
+ rawApplicable: row[8],
+ rawEvaluationType: row[9],
+ rawResultType: row[10],
+ rawSentimentLabel: row[11],
+ rawSentimentScore: row[12],
+ })
return {
id: row[0],
@@ -1045,10 +1128,9 @@ export function mapEvaluationRunRow(row: RawEvaluationRunRow): EvaluationRun {
evaluation_name: row[3] || 'Unknown Evaluation',
generation_id: row[4],
trace_id: row[5],
- result,
+ ...normalizedResult,
reasoning: row[7] || 'No reasoning provided',
status: 'completed' as const,
- applicable: applicable === null ? undefined : applicable === 'true' || applicable === true,
}
}
@@ -1076,7 +1158,11 @@ export async function queryEvaluationRuns(params: {
properties.$ai_trace_id as trace_id,
properties.$ai_evaluation_result as result,
properties.$ai_evaluation_reasoning as reasoning,
- properties.$ai_evaluation_applicable as applicable
+ properties.$ai_evaluation_applicable as applicable,
+ properties.$ai_evaluation_runtime as evaluation_type,
+ properties.$ai_evaluation_result_type as result_type,
+ properties.$ai_sentiment_label as sentiment_label,
+ properties.$ai_sentiment_score as sentiment_score
FROM events
WHERE
event = '$ai_evaluation'
diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yaml
index 673f408a6978..410b8f5d0e89 100644
--- a/products/ai_observability/mcp/tools.yaml
+++ b/products/ai_observability/mcp/tools.yaml
@@ -161,10 +161,11 @@ tools:
idempotent: false
title: Create evaluation
description: >
- Create a new LLM evaluation. For 'llm_judge' type, provide evaluation_config.prompt and model_configuration
- (provider + model). For 'hog' type, provide evaluation_config.source (Hog code returning a boolean). When
- enabled, the evaluation runs automatically on new $ai_generation events. Results appear as '$ai_evaluation'
- events.
+ Create a new AI observability evaluation. For 'llm_judge' type, provide evaluation_config.prompt and
+ model_configuration (provider + model). For 'hog' type, provide evaluation_config.source (Hog code returning
+ a boolean). For 'sentiment' type, use output_type='sentiment', omit model_configuration, and optionally set
+ evaluation_config.source='user_messages'. When enabled, the evaluation runs automatically on new
+ $ai_generation events. Results appear as '$ai_evaluation' events.
llma-evaluation-delete:
operation: evaluations_destroy
enabled: true
@@ -176,8 +177,8 @@ tools:
idempotent: true
title: Delete evaluation
description: >
- Soft-delete an LLM evaluation. The evaluation stops running and is hidden from list views. Historical
- evaluation results ($ai_evaluation events) are preserved.
+ Soft-delete an AI observability evaluation. The evaluation stops running and is hidden from list views.
+ Historical evaluation results ($ai_evaluation events) are preserved.
soft_delete: true
llma-evaluation-get:
operation: evaluations_retrieve
@@ -190,8 +191,8 @@ tools:
idempotent: true
title: Get evaluation
description: >
- Get a specific LLM evaluation by its UUID. Returns the full evaluation configuration including type, config,
- output type, enabled status, and model configuration.
+ Get a specific AI observability evaluation by its UUID. Returns the full evaluation configuration including
+ type, config, output type, enabled status, and model configuration.
llma-evaluation-judge-models:
operation: llm_analytics_models_retrieve
enabled: true
@@ -220,10 +221,11 @@ tools:
idempotent: true
title: List evaluations
description: >
- List all LLM evaluations for the current project. Optionally filter by name/description search or enabled
- status. Evaluations automatically score $ai_generation events for quality, relevance, safety, and other
- criteria. Two types are supported: 'llm_judge' (LLM scores outputs against a prompt) and 'hog'
- (deterministic Hog code). Results are stored as '$ai_evaluation' events.
+ List all AI observability evaluations for the current project. Optionally filter by name/description search
+ or enabled status. Evaluations automatically score $ai_generation events for quality, relevance, safety,
+ sentiment, and other criteria. Supported types are 'llm_judge' (LLM scores outputs against a prompt), 'hog'
+ (deterministic Hog code), and 'sentiment' (user-message sentiment analysis). Results are stored as
+ '$ai_evaluation' events.
llma-evaluation-report-create:
operation: llm_analytics_evaluation_reports_create
enabled: true
@@ -380,9 +382,9 @@ tools:
idempotent: true
title: Summarize evaluation results
description: >
- Generate an AI-powered summary of LLM evaluation results for a given evaluation config. Pass an
- evaluation_id and an optional filter ("all", "pass", "fail", or "na") to scope which runs are analyzed.
- Returns an overall assessment, pattern groups for passing, failing, and N/A runs (each with title,
+ Generate an AI-powered summary of boolean AI observability evaluation results for a given evaluation config.
+ Pass an evaluation_id and an optional filter ("all", "pass", "fail", or "na") to scope which runs are
+ analyzed. Returns an overall assessment, pattern groups for passing, failing, and N/A runs (each with title,
description, frequency, and example generation IDs), actionable recommendations, and run statistics.
Optionally pass generation_ids to restrict the analysis to specific runs. Results are cached for one hour —
use force_refresh to recompute. Rate-limited; requires AI data processing approval for the organization.
@@ -412,8 +414,9 @@ tools:
idempotent: true
title: Update evaluation
description: >
- Update an existing LLM evaluation (partial update). Toggle enabled/disabled, update the evaluation config
- (prompt or Hog source), or change the model configuration.
+ Update an existing AI observability evaluation (partial update). Toggle enabled/disabled, update the
+ evaluation config (prompt, Hog source, or sentiment source), or change the model configuration for llm_judge
+ evaluations.
llma-evaluation-update-full:
operation: evaluations_update
enabled: false
diff --git a/products/ai_observability/skills/README.md b/products/ai_observability/skills/README.md
index ad3e7bc159b8..3403b6a54d29 100644
--- a/products/ai_observability/skills/README.md
+++ b/products/ai_observability/skills/README.md
@@ -15,8 +15,8 @@ Also available to Claude Code / Codex via `hogli sync:skill`.
by model/provider/user/trace/custom dimension, token and cache economics,
cost regressions, and materializing cost insights, dashboards, and alerts.
- **exploring-llm-evaluations** — how to manage and investigate AI observability
- evaluations (both `hog` and `llm_judge` types), run them on specific generations,
- query individual results, and generate AI-powered summaries of pass/fail/N/A patterns.
+ evaluations (`hog`, `llm_judge`, and `sentiment`), run them on specific generations,
+ query individual results, and generate AI-powered summaries of pass/fail/N/A patterns for boolean evaluations.
Skills for managing skills themselves (`skills-store`, `working-with-skills`) now live in
the standalone Skills product — see `products/skills/skills/`.
diff --git a/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md b/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
index 49cc44f7588f..e82d957b52ba 100644
--- a/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
+++ b/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
@@ -1,20 +1,20 @@
---
name: exploring-llm-evaluations
description: >
- Investigate AI observability evaluations of both types — `hog` (deterministic
- code-based) and `llm_judge` (LLM-prompt-based). Find existing evaluations,
- inspect their configuration, run them against specific generations, query
- individual pass/fail results, and generate AI-powered summaries of patterns
- across many runs. Use when the user asks to debug why an evaluation is
- failing, surface common failure modes, compare results across filters,
- dry-run a Hog evaluator, prototype a new LLM-judge prompt, or manage the
- evaluation lifecycle (create, update, enable/disable, delete).
+ Investigate AI observability evaluations — `hog` (deterministic code-based),
+ `llm_judge` (LLM-prompt-based), and `sentiment` (user-message sentiment).
+ Find existing evaluations, inspect their configuration, run them against
+ specific generations, query individual results, and generate AI-powered
+ summaries for boolean pass/fail runs. Use when the user asks to debug why an
+ evaluation is failing, surface common failure modes, compare results across
+ filters, dry-run a Hog evaluator, prototype a new LLM-judge prompt, inspect
+ sentiment classifications, or manage the evaluation lifecycle.
---
-# Exploring LLM evaluations
+# Exploring AI observability evaluations
-PostHog evaluations score `$ai_generation` events. Each evaluation is one of two types,
-both first-class:
+PostHog evaluations score `$ai_generation` events. Each evaluation is one of three
+types:
- **`hog`** — deterministic Hog code that returns `true`/`false` (and optionally N/A).
Best for objective rule-based checks: format validation (JSON parses, schema matches),
@@ -25,15 +25,16 @@ both first-class:
subjective or fuzzy checks: tone, helpfulness, hallucination detection, off-topic
drift, instruction-following. Costs an LLM call per run and requires AI data
processing approval at the org level.
+- **`sentiment`** — classifies sentiment from user messages on each matching
+ generation. Returns a sentiment label and score, not a pass/fail verdict.
-Results from both types land in ClickHouse as `$ai_evaluation` events with the same
-schema, so the read/query/summary workflows are identical regardless of evaluator type —
-the only thing that changes is whether `$ai_evaluation_reasoning` was written by Hog
-code or by an LLM.
+Results from all types land in ClickHouse as `$ai_evaluation` events. Boolean
+evaluations (`llm_judge` and `hog`) set `$ai_evaluation_result`; sentiment
+evaluations set `$ai_sentiment_*` properties instead.
-This skill covers the full lifecycle: list/inspect/manage evaluation configs (Hog or
-LLM judge), run them on specific generations, query individual results, and get an
-AI-generated summary of pass/fail/N/A patterns across many runs.
+This skill covers the full lifecycle: list/inspect/manage evaluation configs, run
+them on specific generations, query individual results, and get an AI-generated
+summary of pass/fail/N/A patterns across many boolean runs.
## Tools
@@ -41,7 +42,7 @@ AI-generated summary of pass/fail/N/A patterns across many runs.
| ---------------------------------------- | -------------------------------------------------------------- |
| `posthog:llma-evaluation-list` | List/search evaluation configs (filter by name, enabled flag) |
| `posthog:llma-evaluation-get` | Get a single evaluation config by UUID |
-| `posthog:llma-evaluation-create` | Create a new `llm_judge` or `hog` evaluation |
+| `posthog:llma-evaluation-create` | Create a new `llm_judge`, `hog`, or `sentiment` evaluation |
| `posthog:llma-evaluation-update` | Update an existing evaluation (name, prompt, enabled, …) |
| `posthog:llma-evaluation-delete` | Soft-delete an evaluation |
| `posthog:llma-evaluation-run` | Run an evaluation against a specific `$ai_generation` event |
@@ -56,23 +57,28 @@ All `llma-evaluation-*` tools are defined in `products/ai_observability/mcp/tool
Every run of an evaluation emits an `$ai_evaluation` event. Key properties:
-| Property | Meaning |
-| --------------------------- | -------------------------------------------------------- |
-| `$ai_evaluation_id` | UUID of the evaluation config |
-| `$ai_evaluation_name` | Human-readable name |
-| `$ai_target_event_id` | UUID of the `$ai_generation` event being scored |
-| `$ai_trace_id` | Parent trace ID (for jumping to the trace UI) |
-| `$ai_evaluation_result` | `true` = pass, `false` = fail |
-| `$ai_evaluation_reasoning` | Free-text explanation (set by the LLM judge or Hog code) |
-| `$ai_evaluation_applicable` | `false` when the evaluator decided the generation is N/A |
+| Property | Meaning |
+| ---------------------------- | --------------------------------------------------------------- |
+| `$ai_evaluation_id` | UUID of the evaluation config |
+| `$ai_evaluation_name` | Human-readable name |
+| `$ai_target_event_id` | UUID of the `$ai_generation` event being scored |
+| `$ai_trace_id` | Parent trace ID (for jumping to the trace UI) |
+| `$ai_evaluation_result_type` | Result kind: `boolean` or `sentiment` |
+| `$ai_evaluation_result` | For boolean evaluations: `true` = pass, `false` = fail |
+| `$ai_evaluation_reasoning` | Free-text explanation (set by the LLM judge or Hog code) |
+| `$ai_evaluation_applicable` | `false` when the evaluator decided the generation is N/A |
+| `$ai_sentiment_label` | For sentiment evaluations: `positive`, `neutral`, or `negative` |
+| `$ai_sentiment_score` | Confidence score for the winning sentiment label |
When `$ai_evaluation_applicable = false`, the run counts as N/A regardless of `$ai_evaluation_result`.
For evaluations that don't support N/A, this property may be `null` — treat null as "applicable".
## Workflow: investigate why an evaluation is failing
-Works the same way for `llm_judge` and `hog` evaluations — the differences only matter
-when you eventually go to fix the evaluator (edit the prompt vs. edit the Hog source).
+Works the same way for boolean `llm_judge` and `hog` evaluations — the differences
+only matter when you eventually go to fix the evaluator (edit the prompt vs. edit
+the Hog source). Sentiment evaluations should be inspected by sentiment label and
+score rather than pass/fail filters.
### Step 1 — Find the evaluation
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 16d20ac0961c..0953e70da887 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3937,7 +3937,7 @@
}
},
"llma-evaluation-create": {
- "description": "Create a new LLM evaluation. For 'llm_judge' type, provide evaluation_config.prompt and model_configuration (provider + model). For 'hog' type, provide evaluation_config.source (Hog code returning a boolean). When enabled, the evaluation runs automatically on new $ai_generation events. Results appear as '$ai_evaluation' events.",
+ "description": "Create a new AI observability evaluation. For 'llm_judge' type, provide evaluation_config.prompt and model_configuration (provider + model). For 'hog' type, provide evaluation_config.source (Hog code returning a boolean). For 'sentiment' type, use output_type='sentiment', omit model_configuration, and optionally set evaluation_config.source='user_messages'. When enabled, the evaluation runs automatically on new $ai_generation events. Results appear as '$ai_evaluation' events.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Create evaluation",
@@ -3951,7 +3951,7 @@
}
},
"llma-evaluation-delete": {
- "description": "Soft-delete an LLM evaluation. The evaluation stops running and is hidden from list views. Historical evaluation results ($ai_evaluation events) are preserved.",
+ "description": "Soft-delete an AI observability evaluation. The evaluation stops running and is hidden from list views. Historical evaluation results ($ai_evaluation events) are preserved.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Delete evaluation",
@@ -3965,7 +3965,7 @@
}
},
"llma-evaluation-get": {
- "description": "Get a specific LLM evaluation by its UUID. Returns the full evaluation configuration including type, config, output type, enabled status, and model configuration.",
+ "description": "Get a specific AI observability evaluation by its UUID. Returns the full evaluation configuration including type, config, output type, enabled status, and model configuration.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Get evaluation",
@@ -3993,7 +3993,7 @@
}
},
"llma-evaluation-list": {
- "description": "List all LLM evaluations for the current project. Optionally filter by name/description search or enabled status. Evaluations automatically score $ai_generation events for quality, relevance, safety, and other criteria. Two types are supported: 'llm_judge' (LLM scores outputs against a prompt) and 'hog' (deterministic Hog code). Results are stored as '$ai_evaluation' events.",
+ "description": "List all AI observability evaluations for the current project. Optionally filter by name/description search or enabled status. Evaluations automatically score $ai_generation events for quality, relevance, safety, sentiment, and other criteria. Supported types are 'llm_judge' (LLM scores outputs against a prompt), 'hog' (deterministic Hog code), and 'sentiment' (user-message sentiment analysis). Results are stored as '$ai_evaluation' events.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "List evaluations",
@@ -4119,7 +4119,7 @@
}
},
"llma-evaluation-summary-create": {
- "description": "Generate an AI-powered summary of LLM evaluation results for a given evaluation config. Pass an evaluation_id and an optional filter (\"all\", \"pass\", \"fail\", or \"na\") to scope which runs are analyzed. Returns an overall assessment, pattern groups for passing, failing, and N/A runs (each with title, description, frequency, and example generation IDs), actionable recommendations, and run statistics. Optionally pass generation_ids to restrict the analysis to specific runs. Results are cached for one hour — use force_refresh to recompute. Rate-limited; requires AI data processing approval for the organization.",
+ "description": "Generate an AI-powered summary of boolean AI observability evaluation results for a given evaluation config. Pass an evaluation_id and an optional filter (\"all\", \"pass\", \"fail\", or \"na\") to scope which runs are analyzed. Returns an overall assessment, pattern groups for passing, failing, and N/A runs (each with title, description, frequency, and example generation IDs), actionable recommendations, and run statistics. Optionally pass generation_ids to restrict the analysis to specific runs. Results are cached for one hour — use force_refresh to recompute. Rate-limited; requires AI data processing approval for the organization.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Summarize evaluation results",
@@ -4148,7 +4148,7 @@
}
},
"llma-evaluation-update": {
- "description": "Update an existing LLM evaluation (partial update). Toggle enabled/disabled, update the evaluation config (prompt or Hog source), or change the model configuration.",
+ "description": "Update an existing AI observability evaluation (partial update). Toggle enabled/disabled, update the evaluation config (prompt, Hog source, or sentiment source), or change the model configuration for llm_judge evaluations.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Update evaluation",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index ccd4a7d88270..811aa1d83110 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2613,7 +2613,7 @@
}
},
"evaluation-create": {
- "description": "Create a new AI observability evaluation. Two types are supported: 'llm_judge' uses an LLM to score generations against a prompt you define (for subjective checks like tone, helpfulness, hallucination detection), and 'hog' runs deterministic code against each generation (for rule-based checks like format validation, keyword detection, length limits). For llm_judge evaluations, provide a prompt in evaluation_config and a model_configuration. For hog evaluations, provide source code in evaluation_config.",
+ "description": "Create a new AI observability evaluation. Supported types are 'llm_judge' (LLM scores generations against a prompt), 'hog' (deterministic code returning a boolean), and 'sentiment' (user-message sentiment analysis). For llm_judge evaluations, provide evaluation_config.prompt and model_configuration. For hog evaluations, provide evaluation_config.source. For sentiment evaluations, use output_type='sentiment', omit model_configuration, and optionally set evaluation_config.source='user_messages'.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Create a new evaluation.",
@@ -2641,7 +2641,7 @@
}
},
"evaluation-get": {
- "description": "Get a specific AI observability evaluation by its UUID. Returns full details including name, type (llm_judge or hog), configuration, conditions, and enabled status.",
+ "description": "Get a specific AI observability evaluation by its UUID. Returns full details including name, type (llm_judge, hog, or sentiment), configuration, conditions, and enabled status.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Get a specific evaluation by ID.",
@@ -4219,7 +4219,7 @@
}
},
"llma-evaluation-create": {
- "description": "Create a new LLM evaluation. For 'llm_judge' type, provide evaluation_config.prompt and model_configuration (provider + model). For 'hog' type, provide evaluation_config.source (Hog code returning a boolean). When enabled, the evaluation runs automatically on new $ai_generation events. Results appear as '$ai_evaluation' events.",
+ "description": "Create a new AI observability evaluation. For 'llm_judge' type, provide evaluation_config.prompt and model_configuration (provider + model). For 'hog' type, provide evaluation_config.source (Hog code returning a boolean). For 'sentiment' type, use output_type='sentiment', omit model_configuration, and optionally set evaluation_config.source='user_messages'. When enabled, the evaluation runs automatically on new $ai_generation events. Results appear as '$ai_evaluation' events.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Create evaluation",
@@ -4233,7 +4233,7 @@
}
},
"llma-evaluation-delete": {
- "description": "Soft-delete an LLM evaluation. The evaluation stops running and is hidden from list views. Historical evaluation results ($ai_evaluation events) are preserved.",
+ "description": "Soft-delete an AI observability evaluation. The evaluation stops running and is hidden from list views. Historical evaluation results ($ai_evaluation events) are preserved.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Delete evaluation",
@@ -4247,7 +4247,7 @@
}
},
"llma-evaluation-get": {
- "description": "Get a specific LLM evaluation by its UUID. Returns the full evaluation configuration including type, config, output type, enabled status, and model configuration.",
+ "description": "Get a specific AI observability evaluation by its UUID. Returns the full evaluation configuration including type, config, output type, enabled status, and model configuration.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Get evaluation",
@@ -4275,7 +4275,7 @@
}
},
"llma-evaluation-list": {
- "description": "List all LLM evaluations for the current project. Optionally filter by name/description search or enabled status. Evaluations automatically score $ai_generation events for quality, relevance, safety, and other criteria. Two types are supported: 'llm_judge' (LLM scores outputs against a prompt) and 'hog' (deterministic Hog code). Results are stored as '$ai_evaluation' events.",
+ "description": "List all AI observability evaluations for the current project. Optionally filter by name/description search or enabled status. Evaluations automatically score $ai_generation events for quality, relevance, safety, sentiment, and other criteria. Supported types are 'llm_judge' (LLM scores outputs against a prompt), 'hog' (deterministic Hog code), and 'sentiment' (user-message sentiment analysis). Results are stored as '$ai_evaluation' events.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "List evaluations",
@@ -4401,7 +4401,7 @@
}
},
"llma-evaluation-summary-create": {
- "description": "Generate an AI-powered summary of LLM evaluation results for a given evaluation config. Pass an evaluation_id and an optional filter (\"all\", \"pass\", \"fail\", or \"na\") to scope which runs are analyzed. Returns an overall assessment, pattern groups for passing, failing, and N/A runs (each with title, description, frequency, and example generation IDs), actionable recommendations, and run statistics. Optionally pass generation_ids to restrict the analysis to specific runs. Results are cached for one hour — use force_refresh to recompute. Rate-limited; requires AI data processing approval for the organization.",
+ "description": "Generate an AI-powered summary of boolean AI observability evaluation results for a given evaluation config. Pass an evaluation_id and an optional filter (\"all\", \"pass\", \"fail\", or \"na\") to scope which runs are analyzed. Returns an overall assessment, pattern groups for passing, failing, and N/A runs (each with title, description, frequency, and example generation IDs), actionable recommendations, and run statistics. Optionally pass generation_ids to restrict the analysis to specific runs. Results are cached for one hour — use force_refresh to recompute. Rate-limited; requires AI data processing approval for the organization.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Summarize evaluation results",
@@ -4430,7 +4430,7 @@
}
},
"llma-evaluation-update": {
- "description": "Update an existing LLM evaluation (partial update). Toggle enabled/disabled, update the evaluation config (prompt or Hog source), or change the model configuration.",
+ "description": "Update an existing AI observability evaluation (partial update). Toggle enabled/disabled, update the evaluation config (prompt, Hog source, or sentiment source), or change the model configuration for llm_judge evaluations.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Update evaluation",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index 341a08e3659e..761c4f7821c5 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -240,7 +240,7 @@
}
},
"evaluation-get": {
- "description": "Get a specific AI observability evaluation by its UUID. Returns full details including name, type (llm_judge or hog), configuration, conditions, and enabled status.",
+ "description": "Get a specific AI observability evaluation by its UUID. Returns full details including name, type (llm_judge, hog, or sentiment), configuration, conditions, and enabled status.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Get a specific evaluation by ID.",
@@ -254,7 +254,7 @@
}
},
"evaluation-create": {
- "description": "Create a new AI observability evaluation. Two types are supported: 'llm_judge' uses an LLM to score generations against a prompt you define (for subjective checks like tone, helpfulness, hallucination detection), and 'hog' runs deterministic code against each generation (for rule-based checks like format validation, keyword detection, length limits). For llm_judge evaluations, provide a prompt in evaluation_config and a model_configuration. For hog evaluations, provide source code in evaluation_config.",
+ "description": "Create a new AI observability evaluation. Supported types are 'llm_judge' (LLM scores generations against a prompt), 'hog' (deterministic code returning a boolean), and 'sentiment' (user-message sentiment analysis). For llm_judge evaluations, provide evaluation_config.prompt and model_configuration. For hog evaluations, provide evaluation_config.source. For sentiment evaluations, use output_type='sentiment', omit model_configuration, and optionally set evaluation_config.source='user_messages'.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Create a new evaluation.",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ed773cb89bfd..797a8b602cd2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19378,7 +19378,7 @@ export namespace Schemas {
}
/**
- * Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}.
+ * Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}.
*/
export type EvaluationEvaluationConfig = {
/**
@@ -19392,6 +19392,9 @@ export namespace Schemas {
* @minLength 1
*/
source: string;
+ } | {
+ /** Classify sentiment from user messages in the generation input. */
+ source?: 'user_messages';
};
/**
@@ -19433,6 +19436,7 @@ export namespace Schemas {
/**
* * `llm_judge` - LLM as a judge
* * `hog` - Hog
+ * * `sentiment` - Sentiment analysis
*/
export type EvaluationTypeEnum = typeof EvaluationTypeEnum[keyof typeof EvaluationTypeEnum];
@@ -19440,16 +19444,19 @@ export namespace Schemas {
export const EvaluationTypeEnum = {
LlmJudge: 'llm_judge',
Hog: 'hog',
+ Sentiment: 'sentiment',
} as const;
/**
* * `boolean` - Boolean (Pass/Fail)
+ * * `sentiment` - Sentiment
*/
export type OutputTypeEnum = typeof OutputTypeEnum[keyof typeof OutputTypeEnum];
export const OutputTypeEnum = {
Boolean: 'boolean',
+ Sentiment: 'sentiment',
} as const;
export type EvaluationConditionPropertiesItem = { [key: string]: unknown };
@@ -19521,16 +19528,18 @@ export namespace Schemas {
enabled?: boolean;
readonly status: EvaluationStatusEnum;
readonly status_reason: StatusReasonEnum | null;
- /** 'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code.
+ /** 'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.
*
* * `llm_judge` - LLM as a judge
- * * `hog` - Hog */
+ * * `hog` - Hog
+ * * `sentiment` - Sentiment analysis */
evaluation_type: EvaluationTypeEnum;
- /** Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}. */
+ /** Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}. */
evaluation_config?: EvaluationEvaluationConfig;
- /** Output format. Currently only 'boolean' is supported.
+ /** Output format. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.
*
- * * `boolean` - Boolean (Pass/Fail) */
+ * * `boolean` - Boolean (Pass/Fail)
+ * * `sentiment` - Sentiment */
output_type: OutputTypeEnum;
/** Output config. For 'boolean' output_type: {allows_na} to permit N/A results. */
output_config?: EvaluationOutputConfig;
@@ -34745,7 +34754,7 @@ export namespace Schemas {
}
/**
- * Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}.
+ * Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}.
*/
export type PatchedEvaluationEvaluationConfig = {
/**
@@ -34759,6 +34768,9 @@ export namespace Schemas {
* @minLength 1
*/
source: string;
+ } | {
+ /** Classify sentiment from user messages in the generation input. */
+ source?: 'user_messages';
};
/**
@@ -34782,16 +34794,18 @@ export namespace Schemas {
enabled?: boolean;
readonly status?: EvaluationStatusEnum;
readonly status_reason?: StatusReasonEnum | null;
- /** 'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code.
+ /** 'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.
*
* * `llm_judge` - LLM as a judge
- * * `hog` - Hog */
+ * * `hog` - Hog
+ * * `sentiment` - Sentiment analysis */
evaluation_type?: EvaluationTypeEnum;
- /** Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}. */
+ /** Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}. */
evaluation_config?: PatchedEvaluationEvaluationConfig;
- /** Output format. Currently only 'boolean' is supported.
+ /** Output format. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.
*
- * * `boolean` - Boolean (Pass/Fail) */
+ * * `boolean` - Boolean (Pass/Fail)
+ * * `sentiment` - Sentiment */
output_type?: OutputTypeEnum;
/** Output config. For 'boolean' output_type: {allows_na} to permit N/A results. */
output_config?: PatchedEvaluationOutputConfig;
diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.ts
index db6a31b8e77d..1b682293c434 100644
--- a/services/mcp/src/generated/ai_observability/api.ts
+++ b/services/mcp/src/generated/ai_observability/api.ts
@@ -119,6 +119,7 @@ export const EvaluationsCreateParams = /* @__PURE__ */ zod.object({
export const evaluationsCreateBodyNameMax = 400
+export const evaluationsCreateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsCreateBodyOutputConfigAllowsNaDefault = false
export const evaluationsCreateBodyConditionsItemIdMax = 100
@@ -136,10 +137,10 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('Whether the evaluation runs automatically on new $ai_generation events.'),
evaluation_type: zod
- .enum(['llm_judge', 'hog'])
- .describe('* `llm_judge` - LLM as a judge\n* `hog` - Hog')
+ .enum(['llm_judge', 'hog', 'sentiment'])
+ .describe('* `llm_judge` - LLM as a judge\n* `hog` - Hog\n* `sentiment` - Sentiment analysis')
.describe(
- "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code.\n\n* `llm_judge` - LLM as a judge\n* `hog` - Hog"
+ "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.\n\n* `llm_judge` - LLM as a judge\n* `hog` - Hog\n* `sentiment` - Sentiment analysis"
),
evaluation_config: zod
.union([
@@ -155,13 +156,23 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({
.min(1)
.describe('Hog source code. Must return true (pass), false (fail), or null for N/A.'),
}),
+ zod.object({
+ source: zod
+ .enum(['user_messages'])
+ .default(evaluationsCreateBodyEvaluationConfigThreeSourceDefault)
+ .describe('Classify sentiment from user messages in the generation input.'),
+ }),
])
.optional()
- .describe("Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}."),
+ .describe(
+ "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
+ ),
output_type: zod
- .enum(['boolean'])
- .describe('* `boolean` - Boolean (Pass/Fail)')
- .describe("Output format. Currently only 'boolean' is supported.\n\n* `boolean` - Boolean (Pass/Fail)"),
+ .enum(['boolean', 'sentiment'])
+ .describe('* `boolean` - Boolean (Pass/Fail)\n* `sentiment` - Sentiment')
+ .describe(
+ "Output format. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.\n\n* `boolean` - Boolean (Pass/Fail)\n* `sentiment` - Sentiment"
+ ),
output_config: zod
.object({
allows_na: zod
@@ -248,6 +259,7 @@ export const EvaluationsPartialUpdateParams = /* @__PURE__ */ zod.object({
export const evaluationsPartialUpdateBodyNameMax = 400
+export const evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsPartialUpdateBodyOutputConfigAllowsNaDefault = false
export const evaluationsPartialUpdateBodyConditionsItemIdMax = 100
@@ -265,11 +277,11 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({
.optional()
.describe('Whether the evaluation runs automatically on new $ai_generation events.'),
evaluation_type: zod
- .enum(['llm_judge', 'hog'])
- .describe('* `llm_judge` - LLM as a judge\n* `hog` - Hog')
+ .enum(['llm_judge', 'hog', 'sentiment'])
+ .describe('* `llm_judge` - LLM as a judge\n* `hog` - Hog\n* `sentiment` - Sentiment analysis')
.optional()
.describe(
- "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code.\n\n* `llm_judge` - LLM as a judge\n* `hog` - Hog"
+ "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.\n\n* `llm_judge` - LLM as a judge\n* `hog` - Hog\n* `sentiment` - Sentiment analysis"
),
evaluation_config: zod
.union([
@@ -285,14 +297,24 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({
.min(1)
.describe('Hog source code. Must return true (pass), false (fail), or null for N/A.'),
}),
+ zod.object({
+ source: zod
+ .enum(['user_messages'])
+ .default(evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault)
+ .describe('Classify sentiment from user messages in the generation input.'),
+ }),
])
.optional()
- .describe("Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}."),
+ .describe(
+ "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
+ ),
output_type: zod
- .enum(['boolean'])
- .describe('* `boolean` - Boolean (Pass/Fail)')
+ .enum(['boolean', 'sentiment'])
+ .describe('* `boolean` - Boolean (Pass/Fail)\n* `sentiment` - Sentiment')
.optional()
- .describe("Output format. Currently only 'boolean' is supported.\n\n* `boolean` - Boolean (Pass/Fail)"),
+ .describe(
+ "Output format. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.\n\n* `boolean` - Boolean (Pass/Fail)\n* `sentiment` - Sentiment"
+ ),
output_config: zod
.object({
allows_na: zod
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json
index b9a25fc5c766..6ba584f9e216 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json
@@ -70,13 +70,24 @@
},
"required": ["source"],
"type": "object"
+ },
+ {
+ "properties": {
+ "source": {
+ "default": "user_messages",
+ "description": "Classify sentiment from user messages in the generation input.",
+ "enum": ["user_messages"],
+ "type": "string"
+ }
+ },
+ "type": "object"
}
],
- "description": "Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}."
+ "description": "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
},
"evaluation_type": {
- "description": "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code.\n\n* `llm_judge` - LLM as a judge\n* `hog` - Hog",
- "enum": ["llm_judge", "hog"],
+ "description": "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.\n\n* `llm_judge` - LLM as a judge\n* `hog` - Hog\n* `sentiment` - Sentiment analysis",
+ "enum": ["llm_judge", "hog", "sentiment"],
"type": "string"
},
"model_configuration": {
@@ -149,8 +160,8 @@
"type": "object"
},
"output_type": {
- "description": "Output format. Currently only 'boolean' is supported.\n\n* `boolean` - Boolean (Pass/Fail)",
- "enum": ["boolean"],
+ "description": "Output format. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.\n\n* `boolean` - Boolean (Pass/Fail)\n* `sentiment` - Sentiment",
+ "enum": ["boolean", "sentiment"],
"type": "string"
}
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json
index 9720e4518f33..f3a35c1a8b64 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json
@@ -70,13 +70,24 @@
},
"required": ["source"],
"type": "object"
+ },
+ {
+ "properties": {
+ "source": {
+ "default": "user_messages",
+ "description": "Classify sentiment from user messages in the generation input.",
+ "enum": ["user_messages"],
+ "type": "string"
+ }
+ },
+ "type": "object"
}
],
- "description": "Configuration dict. For 'llm_judge': {prompt}. For 'hog': {source}."
+ "description": "Configuration dict. For 'llm_judge': {prompt}; for 'hog': {source}; for 'sentiment': {source: 'user_messages'}."
},
"evaluation_type": {
- "description": "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code.\n\n* `llm_judge` - LLM as a judge\n* `hog` - Hog",
- "enum": ["llm_judge", "hog"],
+ "description": "'llm_judge' uses an LLM to score outputs against a prompt; 'hog' runs deterministic Hog code; 'sentiment' classifies user-message sentiment.\n\n* `llm_judge` - LLM as a judge\n* `hog` - Hog\n* `sentiment` - Sentiment analysis",
+ "enum": ["llm_judge", "hog", "sentiment"],
"type": "string"
},
"id": {
@@ -153,8 +164,8 @@
"type": "object"
},
"output_type": {
- "description": "Output format. Currently only 'boolean' is supported.\n\n* `boolean` - Boolean (Pass/Fail)",
- "enum": ["boolean"],
+ "description": "Output format. Use 'boolean' for pass/fail evaluations and 'sentiment' for sentiment analysis.\n\n* `boolean` - Boolean (Pass/Fail)\n* `sentiment` - Sentiment",
+ "enum": ["boolean", "sentiment"],
"type": "string"
}
},