:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(llma): add Tags scene with list, detail, and kea logics (4/5) (#54591)
Andrew Maguire9f7a597bc2d2
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 8ba32647cf69..8bc1e8b5aebb 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -339,6 +339,7 @@ export const FEATURE_FLAGS = {LLM_ANALYTICS_SESSIONS_VIEW: 'llm-analytics-sessions-view', // owner: #team-llm-analyticsLLM_ANALYTICS_SKILLS: 'llm-analytics-skills', // owner: #team-llm-analyticsLLM_ANALYTICS_SUMMARIZATION: 'llm-analytics-summarization', // owner: #team-llm-analytics+ LLM_ANALYTICS_TAGS: 'llm-analytics-tags', // owner: #team-llm-analyticsLLM_ANALYTICS_TEXT_VIEW: 'llm-analytics-text-view', // owner: #team-llm-analyticsLLM_ANALYTICS_TOOLS_CHARTS: 'llm-analytics-tools-charts', // owner: #team-llm-analyticsLLM_ANALYTICS_TOOLS_TAB: 'llm-analytics-tools-tab', // owner: #team-llm-analyticsdiff --git a/frontend/src/products.json b/frontend/src/products.jsonindex 954edd42dd18..300987505456 100644--- a/frontend/src/products.json+++ b/frontend/src/products.json@@ -120,6 +120,13 @@"type": "llm_evaluations","intents": ["llm_evaluations"]},+ {+ "path": "Tags",+ "category": "AI engineering",+ "iconType": null,+ "type": "llm_tags",+ "intents": ["llm_analytics"]+ },{"path": "Prompts","category": "AI engineering",diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex aaacd2168299..c7ef2536671d 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -98,6 +98,8 @@ export const productScenes: Record<string, () => Promise<any>> = {LLMAnalyticsEvaluation: () => import('../../products/llm_analytics/frontend/evaluations/LLMAnalyticsEvaluation'),LLMAnalyticsEvaluationTemplates: () =>import('../../products/llm_analytics/frontend/evaluations/EvaluationTemplates'),+ LLMAnalyticsTags: () => import('../../products/llm_analytics/frontend/tags/LLMAnalyticsTagsScene'),+ LLMAnalyticsTag: () => import('../../products/llm_analytics/frontend/tags/LLMAnalyticsTag'),LLMAnalyticsPrompts: () => import('../../products/llm_analytics/frontend/prompts/LLMPromptsScene'),LLMAnalyticsPrompt: () => import('../../products/llm_analytics/frontend/prompts/LLMPromptScene'),LLMAnalyticsSkills: () => import('../../products/llm_analytics/frontend/skills/LLMSkillsScene'),@@ -195,6 +197,8 @@ export const productRoutes: Record<string, [string, string]> = {'/llm-analytics/playground': ['LLMAnalyticsPlayground', 'llmAnalyticsPlayground'],'/llm-analytics/datasets': ['LLMAnalyticsDatasets', 'llmAnalyticsDatasets'],'/llm-analytics/datasets/:id': ['LLMAnalyticsDataset', 'llmAnalyticsDataset'],+ '/llm-analytics/tags': ['LLMAnalyticsTags', 'llmAnalyticsTags'],+ '/llm-analytics/tags/:id': ['LLMAnalyticsTag', 'llmAnalyticsTag'],'/llm-analytics/evaluations': ['LLMAnalyticsEvaluations', 'llmAnalyticsEvaluations'],'/llm-analytics/evaluations/offline/experiments': ['LLMAnalyticsEvaluations', 'llmAnalyticsOfflineEvaluations'],'/llm-analytics/evaluations/offline/experiments/:experimentId': [@@ -451,6 +455,21 @@ export const productConfiguration: Record<string, any> = {layout: 'app-container',iconType: 'llm_evaluations',},+ LLMAnalyticsTags: {+ projectBased: true,+ name: 'Tags',+ description: 'Add custom tags to your LLM generations automatically.',+ activityScope: 'LLMAnalytics',+ layout: 'app-container',+ iconType: 'llm_tags',+ },+ LLMAnalyticsTag: {+ projectBased: true,+ name: 'LLM analytics tag',+ activityScope: 'LLMAnalytics',+ layout: 'app-container',+ iconType: 'llm_tags',+ },LLMAnalyticsPrompts: {projectBased: true,name: 'Prompts',@@ -821,6 +840,8 @@ export const productUrls = {item?: string}): string => combineUrl(`/llm-analytics/datasets/${id}`, params).url,+ llmAnalyticsTags: (): string => '/llm-analytics/tags',+ llmAnalyticsTag: (id: string): string => `/llm-analytics/tags/${id}`,llmAnalyticsEvaluations: (): string => '/llm-analytics/evaluations',llmAnalyticsOfflineEvaluations: (): string => '/llm-analytics/evaluations/offline/experiments',llmAnalyticsOfflineEvaluationExperiment: (experimentId: string, encode: boolean = true): string =>@@ -1297,6 +1318,8 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['LLMAnalyticsEvaluations','LLMAnalyticsEvaluation','LLMAnalyticsEvaluationTemplates',+ 'LLMAnalyticsTags',+ 'LLMAnalyticsTag','LLMAnalyticsPrompts','LLMAnalyticsPrompt','LLMAnalyticsSkills',@@ -1370,6 +1393,8 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['LLMAnalyticsEvaluations','LLMAnalyticsEvaluation','LLMAnalyticsEvaluationTemplates',+ 'LLMAnalyticsTags',+ 'LLMAnalyticsTag','LLMAnalyticsPrompts','LLMAnalyticsPrompt','LLMAnalyticsSkills',@@ -1439,6 +1464,8 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['LLMAnalyticsEvaluations','LLMAnalyticsEvaluation','LLMAnalyticsEvaluationTemplates',+ 'LLMAnalyticsTags',+ 'LLMAnalyticsTag','LLMAnalyticsPrompts','LLMAnalyticsPrompt','LLMAnalyticsSkills',@@ -1505,6 +1532,8 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['LLMAnalyticsEvaluations','LLMAnalyticsEvaluation','LLMAnalyticsEvaluationTemplates',+ 'LLMAnalyticsTags',+ 'LLMAnalyticsTag','LLMAnalyticsPrompts','LLMAnalyticsPrompt','LLMAnalyticsSkills',@@ -1600,6 +1629,8 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['LLMAnalyticsEvaluations','LLMAnalyticsEvaluation','LLMAnalyticsEvaluationTemplates',+ 'LLMAnalyticsTags',+ 'LLMAnalyticsTag','LLMAnalyticsPrompts','LLMAnalyticsPrompt','LLMAnalyticsSkills',@@ -1653,6 +1684,8 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['LLMAnalyticsEvaluations','LLMAnalyticsEvaluation','LLMAnalyticsEvaluationTemplates',+ 'LLMAnalyticsTags',+ 'LLMAnalyticsTag','LLMAnalyticsPrompts','LLMAnalyticsPrompt','LLMAnalyticsSkills',@@ -1716,6 +1749,8 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['LLMAnalyticsEvaluations','LLMAnalyticsEvaluation','LLMAnalyticsEvaluationTemplates',+ 'LLMAnalyticsTags',+ 'LLMAnalyticsTag','LLMAnalyticsPrompts','LLMAnalyticsPrompt','LLMAnalyticsSkills',@@ -1747,6 +1782,38 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [sceneKey: 'Surveys',sceneKeys: ['Survey', 'Surveys'],},+ {+ path: 'Tags',+ intents: [ProductKey.LLM_ANALYTICS],+ category: ProductItemCategory.AI_ENGINEERING,+ type: 'llm_tags',+ iconType: 'llm_tags' as FileSystemIconType,+ iconColor: ['var(--color-product-llm-analytics-light)'] as FileSystemIconColor,+ href: urls.llmAnalyticsTags(),+ flag: FEATURE_FLAGS.LLM_ANALYTICS_TAGS,+ tags: ['alpha'],+ sceneKey: 'LLMAnalyticsTags',+ sceneKeys: [+ 'LLMAnalytics',+ 'LLMAnalyticsTrace',+ 'LLMAnalyticsSession',+ 'LLMAnalyticsUsers',+ 'LLMAnalyticsPlayground',+ 'LLMAnalyticsDatasets',+ 'LLMAnalyticsDataset',+ 'LLMAnalyticsEvaluations',+ 'LLMAnalyticsEvaluation',+ 'LLMAnalyticsEvaluationTemplates',+ 'LLMAnalyticsTags',+ 'LLMAnalyticsTag',+ 'LLMAnalyticsPrompts',+ 'LLMAnalyticsPrompt',+ 'LLMAnalyticsSkills',+ 'LLMAnalyticsSkill',+ 'LLMAnalyticsClusters',+ 'LLMAnalyticsCluster',+ ],+ },{path: 'Tasks',intents: [ProductKey.TASKS],diff --git a/products/llm_analytics/frontend/settings/TrialUsageMeter.tsx b/products/llm_analytics/frontend/settings/TrialUsageMeter.tsxindex 35f25011aeb1..46a60c179729 100644--- a/products/llm_analytics/frontend/settings/TrialUsageMeter.tsx+++ b/products/llm_analytics/frontend/settings/TrialUsageMeter.tsx@@ -6,22 +6,32 @@ import { urls } from 'scenes/urls'import { EvaluationConfig, llmProviderKeysLogic } from './llmProviderKeysLogic'-export function TrialUsageMeter({ showSettingsLink = false }: { showSettingsLink?: boolean }): JSX.Element | null {+export function TrialUsageMeter({+ showSettingsLink = false,+ noun = 'evaluations',+}: {+ showSettingsLink?: boolean+ noun?: string+}): JSX.Element | null {const { evaluationConfig } = useValues(llmProviderKeysLogic)if (!evaluationConfig || evaluationConfig.active_provider_key) {return null}- return <TrialUsageMeterDisplay evaluationConfig={evaluationConfig} showSettingsLink={showSettingsLink} />+ return (+ <TrialUsageMeterDisplay evaluationConfig={evaluationConfig} showSettingsLink={showSettingsLink} noun={noun} />+ )}export function TrialUsageMeterDisplay({evaluationConfig,showSettingsLink = false,+ noun = 'evaluations',}: {evaluationConfig: EvaluationConfigshowSettingsLink?: boolean+ noun?: string}): JSX.Element {const { trial_eval_limit, trial_evals_remaining } = evaluationConfigconst percentUsed = Math.min(((trial_eval_limit - trial_evals_remaining) / trial_eval_limit) * 100, 100)@@ -30,7 +40,7 @@ export function TrialUsageMeterDisplay({return (<div className="rounded-lg p-4 space-y-3 border"><div className="flex justify-between items-center">- <span className="font-medium">Trial evaluations</span>+ <span className="font-medium">Trial {noun}</span><span className={`text-sm ${isExhausted ? 'font-medium' : 'text-muted'}`}>{trial_evals_remaining} of {trial_eval_limit} remaining</span>@@ -44,7 +54,7 @@ export function TrialUsageMeterDisplay({</div>{isExhausted ? (<p className="text-sm">- Trial evaluations exhausted.{' '}+ Trial {noun} exhausted.{' '}{showSettingsLink ? (<Link to={urls.settings('environment-llm-analytics', 'llm-analytics-byok')}>Add your API key@@ -52,11 +62,11 @@ export function TrialUsageMeterDisplay({) : ('Add your API key')}{' '}- to continue running evaluations.+ to continue.</p>) : (<p className="text-sm text-muted">- You have {trial_evals_remaining} evaluations to try things out before{' '}+ You have {trial_evals_remaining} {noun} to try things out before{' '}{showSettingsLink ? (<Link to={urls.settings('environment-llm-analytics', 'llm-analytics-byok')}>adding your own keydiff --git a/products/llm_analytics/frontend/tags/LLMAnalyticsTag.tsx b/products/llm_analytics/frontend/tags/LLMAnalyticsTag.tsxnew file mode 100644index 000000000000..1e35a34dfabd--- /dev/null+++ b/products/llm_analytics/frontend/tags/LLMAnalyticsTag.tsx@@ -0,0 +1,780 @@+import { BindLogic, useActions, useValues } from 'kea'+import { Field, Form } from 'kea-forms'++import { IconArrowLeft, IconCopy, IconPlus, IconTrash } from '@posthog/icons'+import {+ LemonButton,+ LemonInput,+ LemonSelect,+ LemonSkeleton,+ LemonSwitch,+ LemonTable,+ LemonTabs,+ LemonTag,+ LemonTextArea,+ Link,+ Tooltip,+} from '@posthog/lemon-ui'++import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { TZLabel } from 'lib/components/TZLabel'+import { LemonSlider } from 'lib/lemon-ui/LemonSlider'+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'+import { SceneExport } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { Query } from '~/queries/Query/Query'+import { InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-general'++import { getModelPickerFooterLink, ModelPicker } from '../ModelPicker'+import { modelPickerLogic } from '../modelPickerLogic'+import { HOG_TAGGER_EXAMPLES } from './hogTaggerExamples'+import { HogTestResult, TagRun, llmTaggerLogic } from './llmTaggerLogic'++const DEFAULT_HOG_SOURCE = `// Return a list of tag names that apply to this generation+// Available globals: input, output, properties, event, tags+let result := []+if (output ilike '%billing%') {+ result := arrayPushBack(result, 'billing')+ print('Found: billing')+}+return result`+import { TaggerConditionSet } from './types'++export const scene: SceneExport = {+ component: LLMAnalyticsTagScene,+ logic: llmTaggerLogic,+ paramsToProps: ({ params }): { id: string } => ({ id: params.id || 'new' }),+ productKey: ProductKey.LLM_ANALYTICS,+}++function TagDefinitionsEditor({ id }: { id: string }): JSX.Element {+ const { taggerForm } = useValues(llmTaggerLogic({ id }))+ const { addTag, removeTag, updateTag } = useActions(llmTaggerLogic({ id }))++ return (+ <div className="space-y-2">+ <div className="flex justify-between items-center">+ <label className="font-semibold">Tags</label>+ <LemonButton type="secondary" size="small" icon={<IconPlus />} onClick={addTag}>+ Add tag+ </LemonButton>+ </div>+ <p className="text-muted text-sm">+ Define the tags the LLM can assign. Add descriptions to help it tag more accurately.+ </p>+ {taggerForm.tagger_config.tags.map((tag, index) => (+ <div key={index} className="flex gap-2 items-start">+ <div className="flex-1">+ <LemonInput+ placeholder="Tag name"+ value={tag.name}+ onChange={(value) => updateTag(index, 'name', value)}+ size="small"+ />+ </div>+ <div className="flex-2">+ <LemonInput+ placeholder="Description (optional)"+ value={tag.description || ''}+ onChange={(value) => updateTag(index, 'description', value)}+ size="small"+ />+ </div>+ <LemonButton+ type="secondary"+ status="danger"+ size="small"+ icon={<IconTrash />}+ onClick={() => removeTag(index)}+ disabledReason={+ taggerForm.tagger_config.tags.length <= 1 ? 'At least one tag is required' : undefined+ }+ />+ </div>+ ))}+ </div>+ )+}++function TaggerModelPicker({ id }: { id: string }): JSX.Element {+ const {+ hasByokKeys,+ byokModels,+ trialModels,+ providerModelGroups,+ trialProviderModelGroups,+ byokModelsLoading,+ trialModelsLoading,+ providerKeysLoading,+ } = useValues(modelPickerLogic)+ const { selectedModel, selectedPickerProviderKeyId } = useValues(llmTaggerLogic({ id }))+ const { selectModelFromPicker } = useActions(llmTaggerLogic({ id }))++ const allModels = hasByokKeys ? byokModels : trialModels+ const selectedModelName = allModels.find((m) => m.id === selectedModel)?.name+ const groups = hasByokKeys ? providerModelGroups : trialProviderModelGroups+ const loading = hasByokKeys ? byokModelsLoading || providerKeysLoading : trialModelsLoading++ const footerLink = getModelPickerFooterLink(hasByokKeys)++ return (+ <div className="bg-bg-light border rounded p-6">+ <h3 className="text-lg font-semibold mb-2">Model</h3>+ <p className="text-muted text-sm mb-4">+ Select which LLM provider and model to use for running this tagger.+ </p>++ <div className="space-y-4">+ <Field name="model" label="Model">+ <ModelPicker+ model={selectedModel}+ selectedProviderKeyId={selectedPickerProviderKeyId}+ onSelect={selectModelFromPicker}+ groups={groups}+ loading={loading}+ footerLink={footerLink}+ selectedModelName={selectedModelName}+ data-attr="tagger-model-selector"+ />+ </Field>+ </div>+ </div>+ )+}++function TaggerTriggers({ id }: { id: string }): JSX.Element {+ const { taggerForm } = useValues(llmTaggerLogic({ id }))+ const { setConditions } = useActions(llmTaggerLogic({ id }))++ const conditions = taggerForm.conditions++ const addConditionSet = (): void => {+ const newCondition: TaggerConditionSet = {+ id: `cond-${Date.now()}`,+ rollout_percentage: 100,+ properties: [],+ }+ setConditions([...conditions, newCondition])+ }++ const updateConditionSet = (index: number, updates: Partial<TaggerConditionSet>): void => {+ const updated = conditions.map((condition, i) => (i === index ? { ...condition, ...updates } : condition))+ setConditions(updated)+ }++ const removeConditionSet = (index: number): void => {+ if (conditions.length === 1) {+ return+ }+ setConditions(conditions.filter((_, i) => i !== index))+ }++ const duplicateConditionSet = (index: number): void => {+ const duplicated: TaggerConditionSet = {+ ...conditions[index],+ id: `cond-${Date.now()}`,+ }+ const updated = [...conditions]+ updated.splice(index + 1, 0, duplicated)+ setConditions(updated)+ }++ return (+ <div className="space-y-6">+ <div className="text-sm text-muted">+ Each condition set defines when this tagger should trigger. If multiple condition sets exist, the tagger+ will trigger if ANY of them match (OR logic).+ </div>++ {conditions.map((condition, index) => {+ const percentageValue = condition.rollout_percentage || 0++ return (+ <div key={condition.id} className="bg-bg-light border rounded p-4 space-y-4">+ <div className="flex justify-between items-center">+ <div className="flex items-center gap-2">+ <h4 className="font-semibold">Condition set {index + 1}</h4>+ {conditions.length > 1 && (+ <div className="text-sm text-muted">{index === 0 ? 'IF' : 'OR IF'}</div>+ )}+ </div>+ <div className="flex gap-1">+ <LemonButton+ icon={<IconCopy />}+ size="small"+ type="secondary"+ onClick={() => duplicateConditionSet(index)}+ tooltip="Duplicate condition set"+ />+ {conditions.length > 1 && (+ <LemonButton+ icon={<IconTrash />}+ size="small"+ type="secondary"+ status="danger"+ onClick={() => removeConditionSet(index)}+ tooltip="Remove condition set"+ />+ )}+ </div>+ </div>++ <div className="space-y-2">+ <label className="block text-sm font-medium">+ Sampling percentage <span className="text-danger">*</span>+ </label>+ <div className="flex items-center gap-4 max-w-md">+ <div className="flex-1">+ <LemonSlider+ value={percentageValue}+ onChange={(value) => updateConditionSet(index, { rollout_percentage: value })}+ min={0.1}+ max={100}+ step={0.1}+ />+ </div>+ <div className="w-24">+ <LemonInput+ type="number"+ value={percentageValue}+ onChange={(value) =>+ updateConditionSet(index, { rollout_percentage: Number(value) || 0 })+ }+ min={0.1}+ max={100}+ step={0.1}+ suffix={<span>%</span>}+ placeholder="Set percentage"+ status={percentageValue === 0 ? 'danger' : undefined}+ />+ </div>+ </div>+ {percentageValue === 0 ? (+ <div className="text-xs text-danger">+ Please set a sampling percentage between 0.1% and 100%+ </div>+ ) : (+ <div className="text-xs text-muted">+ This tagger will run on {percentageValue.toFixed(2)}% of matching generations+ </div>+ )}+ </div>++ <div className="space-y-2">+ <label className="block text-sm font-medium">Filter conditions</label>+ <div className="text-sm text-muted mb-2">+ Filter by generation event properties or person properties to target specific+ generations. Leave empty to match all generations.+ </div>+ <PropertyFilters+ propertyFilters={condition.properties}+ onChange={(properties) => updateConditionSet(index, { properties })}+ pageKey={`tagger-condition-${condition.id}`}+ taxonomicGroupTypes={[+ TaxonomicFilterGroupType.EventProperties,+ TaxonomicFilterGroupType.EventMetadata,+ TaxonomicFilterGroupType.PersonProperties,+ ]}+ addText="Add filter condition"+ hasRowOperator={false}+ sendAllKeyUpdates+ allowRelativeDateOptions={false}+ />+ </div>+ </div>+ )+ })}++ <div className="flex justify-center">+ <LemonButton type="secondary" icon={<IconPlus />} onClick={addConditionSet}>+ Add condition set+ </LemonButton>+ </div>+ </div>+ )+}++function HogTaggerTestSection({ id }: { id: string }): JSX.Element {+ const { hogTestResults, hogTestLoading } = useValues(llmTaggerLogic({ id }))+ const { testHogTagger, clearHogTestResults } = useActions(llmTaggerLogic({ id }))++ return (+ <div className="mt-4 space-y-3">+ <div className="flex gap-2">+ <LemonButton type="secondary" size="small" onClick={testHogTagger} loading={hogTestLoading}>+ Test on recent generations+ </LemonButton>+ {hogTestResults && (+ <LemonButton type="tertiary" size="small" onClick={clearHogTestResults}>+ Clear+ </LemonButton>+ )}+ </div>++ {hogTestResults && (+ <LemonTable+ columns={[+ {+ title: 'Input',+ key: 'input',+ render: (_, row: HogTestResult) => (+ <div className="max-w-xs text-sm truncate">{row.input_preview}</div>+ ),+ },+ {+ title: 'Output',+ key: 'output',+ render: (_, row: HogTestResult) => (+ <div className="max-w-xs text-sm truncate">{row.output_preview}</div>+ ),+ },+ {+ title: 'Tags',+ key: 'tags',+ render: (_, row: HogTestResult) =>+ row.error ? (+ <LemonTag type="danger">{row.error}</LemonTag>+ ) : (+ <div className="flex flex-wrap gap-1">+ {row.tags.length > 0 ? (+ row.tags.map((tag: string) => (+ <LemonTag key={tag} type="highlight">+ {tag}+ </LemonTag>+ ))+ ) : (+ <span className="text-muted text-sm">No tags</span>+ )}+ </div>+ ),+ },+ {+ title: 'Reasoning',+ key: 'reasoning',+ render: (_, row: HogTestResult) =>+ row.reasoning ? (+ <Tooltip title={row.reasoning} placement="top">+ <div className="max-w-xs text-sm truncate cursor-default">{row.reasoning}</div>+ </Tooltip>+ ) : (+ <span className="text-muted text-sm">-</span>+ ),+ },+ ]}+ dataSource={hogTestResults}+ rowKey="event_uuid"+ size="small"+ emptyState={<span className="text-muted text-sm">No recent generations found</span>}+ />+ )}+ </div>+ )+}++function LLMAnalyticsTaggerForm({ id }: { id: string }): JSX.Element {+ const logic = llmTaggerLogic({ id })+ const { taggerForm, taggerFormChanged, isTaggerFormSubmitting } = useValues(logic)+ const { setTaggerFormValues, submitTaggerForm, deleteTagger } = useActions(logic)++ return (+ <BindLogic logic={llmTaggerLogic} props={{ id }}>+ <Form logic={llmTaggerLogic} props={{ id }} formKey="taggerForm">+ <div className="space-y-6 max-w-3xl">+ <div className="space-y-4">+ <div>+ <label className="font-semibold">Name</label>+ <LemonInput+ placeholder="e.g. Product feature tagger"+ value={taggerForm.name}+ onChange={(value) => setTaggerFormValues({ name: value })}+ />+ </div>++ <div>+ <label className="font-semibold">Description</label>+ <LemonInput+ placeholder="Optional description"+ value={taggerForm.description}+ onChange={(value) => setTaggerFormValues({ description: value })}+ />+ </div>++ <div className="flex items-center gap-2">+ <LemonSwitch+ checked={taggerForm.enabled}+ onChange={(checked) => setTaggerFormValues({ enabled: checked })}+ label="Enabled"+ />+ </div>+ </div>++ <div className="border-t pt-4 space-y-4">+ <h3 className="text-lg font-semibold">Tag config</h3>++ <div>+ <label className="font-semibold">Method</label>+ <LemonSelect+ value={taggerForm.tagger_type}+ onChange={(value) => {+ setTaggerFormValues({ tagger_type: value })+ // Reset config when switching types+ if (value === 'hog') {+ setTaggerFormValues({+ tagger_type: value,+ tagger_config: {+ source: DEFAULT_HOG_SOURCE,+ tags: taggerForm.tagger_config.tags,+ },+ })+ } else {+ setTaggerFormValues({+ tagger_type: value,+ tagger_config: {+ prompt: '',+ tags: taggerForm.tagger_config.tags,+ min_tags: 0,+ max_tags: null,+ },+ })+ }+ }}+ options={[+ { value: 'llm', label: 'LLM' },+ { value: 'hog', label: 'Hog code' },+ ]}+ fullWidth+ />+ <p className="text-muted text-sm mt-1">+ {taggerForm.tagger_type === 'hog'+ ? 'Run deterministic Hog code against each generation. No LLM cost, instant results.'+ : 'Use an LLM to intelligently tag each generation based on a prompt.'}+ </p>+ </div>++ {taggerForm.tagger_type === 'hog' ? (+ <div>+ <label className="font-semibold">Hog code</label>+ <p className="text-muted text-sm mb-2">+ Return a list of tag names. Available globals: input, output, properties, event,+ tags.+ </p>+ <div className="flex flex-wrap gap-1.5 mb-3">+ {HOG_TAGGER_EXAMPLES.map((example) => (+ <LemonButton+ key={example.label}+ type="secondary"+ size="xsmall"+ onClick={() =>+ setTaggerFormValues({+ tagger_config: {+ ...taggerForm.tagger_config,+ source: example.source,+ },+ })+ }+ >+ {example.label}+ </LemonButton>+ ))}+ </div>+ <CodeEditorResizeable+ language="hog"+ value={'source' in taggerForm.tagger_config ? taggerForm.tagger_config.source : ''}+ onChange={(value) =>+ setTaggerFormValues({+ tagger_config: { ...taggerForm.tagger_config, source: value ?? '' },+ })+ }+ height={200}+ />+ <HogTaggerTestSection id={id} />+ </div>+ ) : (+ <div>+ <label className="font-semibold">Prompt</label>+ <p className="text-muted text-sm mb-1">+ Instructions for the LLM on how to tag generations.+ </p>+ <LemonTextArea+ placeholder="e.g. Which product features were discussed or used in this generation?"+ value={'prompt' in taggerForm.tagger_config ? taggerForm.tagger_config.prompt : ''}+ onChange={(value) =>+ setTaggerFormValues({+ tagger_config: { ...taggerForm.tagger_config, prompt: value },+ })+ }+ minRows={3}+ />+ </div>+ )}++ {taggerForm.tagger_type !== 'hog' && <TagDefinitionsEditor id={id} />}++ {taggerForm.tagger_type !== 'hog' && (+ <div className="flex gap-4">+ <div>+ <label className="font-semibold">Min tags</label>+ <LemonInput+ type="number"+ min={0}+ value={+ 'min_tags' in taggerForm.tagger_config+ ? taggerForm.tagger_config.min_tags+ : 0+ }+ onChange={(value) =>+ setTaggerFormValues({+ tagger_config: {+ ...taggerForm.tagger_config,+ min_tags: value ?? 0,+ },+ })+ }+ size="small"+ className="w-24"+ />+ </div>+ <div>+ <label className="font-semibold">Max tags</label>+ <LemonInput+ type="number"+ min={1}+ value={+ 'max_tags' in taggerForm.tagger_config+ ? (taggerForm.tagger_config.max_tags ?? undefined)+ : undefined+ }+ onChange={(value) =>+ setTaggerFormValues({+ tagger_config: {+ ...taggerForm.tagger_config,+ max_tags: value ?? null,+ },+ })+ }+ size="small"+ className="w-24"+ placeholder="No limit"+ />+ </div>+ </div>+ )}+ </div>++ {/* Model Configuration (LLM only) */}+ {taggerForm.tagger_type !== 'hog' && <TaggerModelPicker id={id} />}++ {/* Trigger Configuration */}+ <div className="border-t pt-4 space-y-4">+ <h3 className="text-lg font-semibold">Triggers</h3>+ <TaggerTriggers id={id} />+ </div>++ <div className="flex gap-2 pt-4 border-t">+ <LemonButton+ type="primary"+ onClick={submitTaggerForm}+ loading={isTaggerFormSubmitting}+ disabledReason={!taggerFormChanged && id !== 'new' ? 'No changes to save' : undefined}+ >+ {id === 'new' ? 'Create tagger' : 'Save changes'}+ </LemonButton>+ <LemonButton type="secondary" to={urls.llmAnalyticsTags()}>+ Cancel+ </LemonButton>+ {id !== 'new' && (+ <LemonButton type="secondary" status="danger" className="ml-auto" onClick={deleteTagger}>+ Delete+ </LemonButton>+ )}+ </div>+ </div>+ </Form>+ </BindLogic>+ )+}++function TagRunsChart({ id }: { id: string }): JSX.Element | null {+ const { runsChartQuery } = useValues(llmTaggerLogic({ id }))++ if (!runsChartQuery) {+ return null+ }++ return (+ <div className="bg-bg-light rounded p-4 mb-4 h-72 flex flex-col InsightCard">+ <h3 className="text-base font-semibold mb-1">Tag distribution over time</h3>+ <div className="flex-1 flex flex-col min-h-0">+ <Query+ query={{ kind: NodeKind.InsightVizNode, source: runsChartQuery } as InsightVizNode}+ readOnly+ embedded+ inSharedMode+ context={{+ insightProps: {+ dashboardItemId: `new-tagger-runs-chart-${id}`,+ dataNodeCollectionId: `tagger-runs-${id}`,+ },+ }}+ />+ </div>+ </div>+ )+}++function TagRunsTable({ id }: { id: string }): JSX.Element {+ const { tagRuns, tagRunsLoading, dateFilter } = useValues(llmTaggerLogic({ id }))+ const { loadTagRuns, setDates } = useActions(llmTaggerLogic({ id }))++ const columns: LemonTableColumns<TagRun> = [+ {+ title: 'Timestamp',+ key: 'timestamp',+ render: (_, run) => <TZLabel time={run.timestamp} />,+ sorter: (a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),+ },+ {+ title: 'Generation',+ key: 'generation',+ render: (_, run) =>+ run.trace_id && run.target_event_id ? (+ <div className="font-mono text-sm">+ <Link+ to={urls.llmAnalyticsTrace(run.trace_id, { event: run.target_event_id })}+ className="text-primary"+ >+ {run.target_event_id.slice(0, 12)}...+ </Link>+ </div>+ ) : (+ <span className="text-muted text-sm">-</span>+ ),+ },+ {+ title: 'Tags',+ key: 'tags',+ render: (_, run) => (+ <div className="flex flex-wrap gap-1">+ {run.tags.length > 0 ? (+ run.tags.map((tag: string) => (+ <LemonTag key={tag} type="highlight">+ {tag}+ </LemonTag>+ ))+ ) : (+ <span className="text-muted text-sm">No tags</span>+ )}+ </div>+ ),+ },+ {+ title: 'Reasoning',+ key: 'reasoning',+ render: (_, run) =>+ run.reasoning ? (+ <Tooltip title={run.reasoning} placement="top">+ <div className="max-w-md text-sm truncate cursor-default">{run.reasoning}</div>+ </Tooltip>+ ) : (+ <span className="text-muted text-sm">-</span>+ ),+ },+ ]++ return (+ <div className="space-y-4">+ <div className="flex justify-between items-center">+ <div className="flex items-center gap-3">+ <p className="text-muted text-sm m-0">Tag runs for this tagger.</p>+ <DateFilter dateFrom={dateFilter.dateFrom} dateTo={dateFilter.dateTo} onChange={setDates} />+ </div>+ <LemonButton type="secondary" size="small" onClick={loadTagRuns}>+ Refresh+ </LemonButton>+ </div>+ <LemonTable+ columns={columns}+ dataSource={tagRuns}+ loading={tagRunsLoading}+ rowKey="target_event_id"+ pagination={{ pageSize: 20 }}+ nouns={['run', 'runs']}+ emptyState={+ <div className="text-center py-8 text-muted">+ No tag runs yet. Enable this tagger and send some generations to see results.+ </div>+ }+ />+ </div>+ )+}++export function LLMAnalyticsTagScene({ id }: { id?: string }): JSX.Element {+ const taggerId = id || 'new'+ const isNew = taggerId === 'new'+ const { tagger, taggerLoading, activeTab } = useValues(llmTaggerLogic({ id: taggerId }))+ const { setActiveTab } = useActions(llmTaggerLogic({ id: taggerId }))++ if (taggerLoading) {+ return (+ <SceneContent>+ <LemonSkeleton className="w-full h-96" />+ </SceneContent>+ )+ }++ return (+ <SceneContent>+ <div className="space-y-6">+ {/* Header */}+ <div className="flex justify-between items-start pb-4 border-b">+ <div className="space-y-2">+ <h1 className="text-2xl font-semibold">{isNew ? 'New tagger' : tagger?.name || 'Tagger'}</h1>+ {!isNew && tagger && (+ <div className="flex items-center gap-2">+ <LemonTag type={tagger.enabled ? 'success' : 'default'}>+ {tagger.enabled ? 'Enabled' : 'Disabled'}+ </LemonTag>+ </div>+ )}+ </div>+ <LemonButton type="secondary" icon={<IconArrowLeft />} to={urls.llmAnalyticsTags()}>+ Back+ </LemonButton>+ </div>++ <LemonTabs+ activeKey={isNew ? 'configuration' : activeTab}+ onChange={(key) => setActiveTab(key as 'runs' | 'configuration')}+ data-attr="llma-tagger-tabs"+ tabs={[+ ...(!isNew+ ? [+ {+ key: 'runs',+ label: 'Runs',+ content: (+ <div className="max-w-6xl">+ <TagRunsChart id={taggerId} />+ <TagRunsTable id={taggerId} />+ </div>+ ),+ },+ ]+ : []),+ {+ key: 'configuration',+ label: 'Configuration',+ content: <LLMAnalyticsTaggerForm id={taggerId} />,+ },+ ]}+ />+ </div>+ </SceneContent>+ )+}diff --git a/products/llm_analytics/frontend/tags/LLMAnalyticsTagsScene.tsx b/products/llm_analytics/frontend/tags/LLMAnalyticsTagsScene.tsxnew file mode 100644index 000000000000..86c9a1532014--- /dev/null+++ b/products/llm_analytics/frontend/tags/LLMAnalyticsTagsScene.tsx@@ -0,0 +1,311 @@+import { useActions, useValues } from 'kea'+import { combineUrl, router } from 'kea-router'++import { IconPencil, IconPlus, IconSearch, IconTrash } from '@posthog/icons'+import {+ LemonButton,+ LemonInput,+ LemonSkeleton,+ LemonSwitch,+ LemonTable,+ LemonTag,+ Link,+ Tooltip,+} from '@posthog/lemon-ui'++import { AccessControlAction } from 'lib/components/AccessControlAction'+import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { deleteWithUndo } from 'lib/utils/deleteWithUndo'+import { SceneExport } from 'scenes/sceneTypes'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { Query } from '~/queries/Query/Query'+import { InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-general'+import { AccessControlLevel, AccessControlResourceType } from '~/types'++import { TrialUsageMeter } from '../settings/TrialUsageMeter'+import { llmTaggersLogic } from './llmTaggersLogic'+import { Tagger } from './types'++export const scene: SceneExport = {+ component: LLMAnalyticsTagsScene,+ logic: llmTaggersLogic,+ productKey: ProductKey.LLM_ANALYTICS,+}++function TaggerMetrics({ tabId }: { tabId?: string }): JSX.Element {+ const { chartQuery, totalRuns, taggers, runStatsLoading } = useValues(llmTaggersLogic({ tabId }))++ const enabledCount = taggers.filter((t) => t.enabled && !t.deleted).length++ if (runStatsLoading) {+ return <LemonSkeleton className="h-80 w-full mb-6" />+ }++ return (+ <div className="mb-6">+ <div className="flex gap-4 h-80">+ {chartQuery ? (+ <div className="flex-[2] bg-bg-light rounded p-4 flex flex-col InsightCard h-full">+ <h3 className="text-lg font-semibold mb-1">Tags over time</h3>+ <p className="text-muted text-sm mb-3">Tag counts broken down by tagger and tag name</p>+ <div className="flex-1 flex flex-col min-h-0">+ <Query+ query={{ kind: NodeKind.InsightVizNode, source: chartQuery } as InsightVizNode}+ readOnly+ embedded+ inSharedMode+ context={{+ insightProps: {+ dashboardItemId: 'new-tagger-metrics-chart',+ dataNodeCollectionId: 'tagger-metrics',+ },+ }}+ />+ </div>+ </div>+ ) : (+ <div className="flex-[2] bg-bg-light border rounded p-8 flex items-center justify-center">+ <div className="text-muted text-center">+ No enabled taggers to display. Create and enable taggers to see metrics.+ </div>+ </div>+ )}++ <div className="flex-1 grid grid-cols-1 gap-4">+ <div className="bg-bg-light border rounded p-4 flex flex-col">+ <div className="text-muted text-xs font-medium uppercase mb-2">Enabled taggers</div>+ <div className="text-3xl font-semibold">{enabledCount}</div>+ <div className="text-muted text-sm mt-1">{taggers.length} total</div>+ </div>+ <div className="bg-bg-light border rounded p-4 flex flex-col">+ <div className="text-muted text-xs font-medium uppercase mb-2">Total runs</div>+ <div className="text-3xl font-semibold">{totalRuns}</div>+ {totalRuns === 0 && <div className="text-muted text-sm mt-1">No activity</div>}+ </div>+ </div>+ </div>+ </div>+ )+}++function LLMAnalyticsTagsContent({ tabId }: { tabId?: string }): JSX.Element {+ const taggersLogic = llmTaggersLogic({ tabId })+ const { filteredTaggers, taggersLoading, taggersFilter, dateFilter, runStatsMap, tagDistributionMap } =+ useValues(taggersLogic)+ const { setTaggersFilter, toggleTaggerEnabled, loadTaggers, setDates } = useActions(taggersLogic)+ const { currentTeamId } = useValues(teamLogic)+ const { push } = useActions(router)+ const { searchParams } = useValues(router)+ const taggerUrl = (id: string): string => combineUrl(urls.llmAnalyticsTag(id), searchParams).url++ const columns: LemonTableColumns<Tagger> = [+ {+ title: 'Name',+ key: 'name',+ render: (_, tagger) => (+ <div className="flex flex-col">+ <Link to={taggerUrl(tagger.id)} className="font-semibold text-primary">+ {tagger.name}+ </Link>+ {tagger.description && <div className="text-muted text-sm">{tagger.description}</div>}+ </div>+ ),+ sorter: (a, b) => a.name.localeCompare(b.name),+ },+ {+ title: 'Status',+ key: 'enabled',+ render: (_, tagger) => (+ <div className="flex items-center gap-2">+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmAnalytics}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonSwitch+ checked={tagger.enabled}+ onChange={() => toggleTaggerEnabled(tagger.id)}+ size="small"+ data-attr="toggle-tagger-enabled"+ />+ </AccessControlAction>+ <span className={tagger.enabled ? 'text-success' : 'text-muted'}>+ {tagger.enabled ? 'Enabled' : 'Disabled'}+ </span>+ </div>+ ),+ sorter: (a, b) => Number(b.enabled) - Number(a.enabled),+ },+ {+ title: 'Runs',+ key: 'runs',+ render: (_, tagger) => {+ const count = runStatsMap[tagger.id] ?? 0+ return <span className={count > 0 ? 'font-medium' : 'text-muted'}>{count}</span>+ },+ sorter: (a, b) => (runStatsMap[a.id] ?? 0) - (runStatsMap[b.id] ?? 0),+ },+ {+ title: 'Tags',+ key: 'tags',+ render: (_, tagger) => {+ const dist = tagDistributionMap[tagger.id]+ if (dist && dist.length > 0) {+ return (+ <div className="flex flex-wrap gap-1">+ {dist.slice(0, 5).map((t) => (+ <LemonTag key={t.name} type="option">+ {t.name} ({t.percent}%)+ </LemonTag>+ ))}+ {dist.length > 5 && <LemonTag type="muted">+{dist.length - 5}</LemonTag>}+ </div>+ )+ }+ return <span className="text-muted italic">No data</span>+ },+ },+ {+ title: 'Method',+ key: 'method',+ render: (_, tagger) => (+ <LemonTag type={tagger.tagger_type === 'hog' ? 'option' : 'caution'}>+ {tagger.tagger_type === 'hog' ? 'Hog' : 'LLM'}+ </LemonTag>+ ),+ },+ {+ title: 'Config',+ key: 'config',+ render: (_, tagger) => {+ const preview =+ tagger.tagger_type === 'hog'+ ? 'source' in tagger.tagger_config+ ? tagger.tagger_config.source+ : ''+ : 'prompt' in tagger.tagger_config+ ? tagger.tagger_config.prompt+ : ''+ return (+ <Tooltip title={preview} placement="top">+ <div className="max-w-md">+ <div className="text-sm font-mono bg-bg-light border rounded px-2 py-1 truncate cursor-default">+ {preview || '(empty)'}+ </div>+ </div>+ </Tooltip>+ )+ },+ },+ {+ title: 'Actions',+ key: 'actions',+ render: (_, tagger) => (+ <div className="flex gap-1">+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmAnalytics}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconPencil />}+ onClick={() =>+ push(+ combineUrl(urls.llmAnalyticsTag(tagger.id), {+ ...searchParams,+ tab: 'configuration',+ }).url+ )+ }+ />+ </AccessControlAction>+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmAnalytics}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ size="small"+ type="secondary"+ status="danger"+ icon={<IconTrash />}+ onClick={() => {+ deleteWithUndo({+ endpoint: `environments/${currentTeamId}/taggers`,+ object: tagger,+ callback: () => loadTaggers(),+ })+ }}+ />+ </AccessControlAction>+ </div>+ ),+ },+ ]++ return (+ <div className="space-y-4">+ <TrialUsageMeter showSettingsLink={false} noun="runs" />++ <DateFilter dateFrom={dateFilter.dateFrom} dateTo={dateFilter.dateTo} onChange={setDates} />++ <TaggerMetrics tabId={tabId} />++ <div className="flex items-center gap-2">+ <LemonInput+ type="search"+ placeholder="Search taggers..."+ value={taggersFilter}+ onChange={setTaggersFilter}+ prefix={<IconSearch />}+ className="max-w-sm"+ />+ </div>++ <LemonTable+ columns={columns}+ dataSource={filteredTaggers}+ loading={taggersLoading}+ rowKey="id"+ pagination={{+ pageSize: 50,+ }}+ nouns={['tagger', 'taggers']}+ emptyState={<div className="text-center p-8 text-muted">No taggers found.</div>}+ />+ </div>+ )+}++export function LLMAnalyticsTagsScene({ tabId }: { tabId?: string }): JSX.Element {+ const { searchParams } = useValues(router)+ return (+ <SceneContent>+ <SceneTitleSection+ name="Tags"+ description="Set up taggers to automatically add custom tags to your LLM generations."+ resourceType={{ type: 'llm_tags' }}+ actions={+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmAnalytics}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ type="primary"+ icon={<IconPlus />}+ to={combineUrl(urls.llmAnalyticsTag('new'), searchParams).url}+ data-attr="create-tagger-button"+ >+ Create tagger+ </LemonButton>+ </AccessControlAction>+ }+ />+ <LLMAnalyticsTagsContent tabId={tabId} />+ </SceneContent>+ )+}diff --git a/products/llm_analytics/frontend/tags/TagMetrics.tsx b/products/llm_analytics/frontend/tags/TagMetrics.tsxnew file mode 100644index 000000000000..29a5dd61e942--- /dev/null+++ b/products/llm_analytics/frontend/tags/TagMetrics.tsx@@ -0,0 +1,112 @@+import { useValues } from 'kea'++import { LemonSkeleton, LemonTag } from '@posthog/lemon-ui'++import { Query } from '~/queries/Query/Query'+import { InsightVizNode, NodeKind } from '~/queries/schema/schema-general'++import { llmTaggersLogic } from './llmTaggersLogic'+import { tagMetricsLogic } from './tagMetricsLogic'++export const TAG_METRICS_COLLECTION_ID = 'tag-metrics'++function SummaryCard({+ title,+ value,+ subtitle,+ colorClass,+}: {+ title: string+ value: string | number+ subtitle?: string+ colorClass?: string+}): JSX.Element {+ return (+ <div className="bg-bg-light border rounded p-4 flex flex-col">+ <div className="text-muted text-xs font-medium uppercase mb-2">{title}</div>+ <div className={`text-3xl font-semibold ${colorClass || ''}`}>{value}</div>+ {subtitle && <div className="text-muted text-sm mt-1">{subtitle}</div>}+ </div>+ )+}++function TopTagsCard({ tags }: { tags: { tag: string; count: number }[] }): JSX.Element {+ return (+ <div className="bg-bg-light border rounded p-4 flex flex-col col-span-2">+ <div className="text-muted text-xs font-medium uppercase mb-2">Top tags</div>+ {tags.length === 0 ? (+ <div className="text-muted text-sm">No tag data yet</div>+ ) : (+ <div className="flex flex-wrap gap-2 mt-1">+ {tags.slice(0, 10).map((tagStat) => (+ <LemonTag key={tagStat.tag} type="highlight" size="small">+ {tagStat.tag} ({tagStat.count})+ </LemonTag>+ ))}+ </div>+ )}+ </div>+ )+}++export function TagMetrics({ tabId }: { tabId?: string }): JSX.Element {+ const { summaryMetrics, tagStats, tagStatsLoading, enabledTaggerCount, chartQuery } = useValues(+ tagMetricsLogic({ tabId })+ )+ const { taggers } = useValues(llmTaggersLogic({ tabId }))++ if (tagStatsLoading) {+ return (+ <div className="space-y-4 mb-6">+ <LemonSkeleton className="h-96 w-full" />+ </div>+ )+ }++ return (+ <div className="mb-6">+ <div className="flex gap-4 h-96">+ {chartQuery ? (+ <div className="flex-1 bg-bg-light rounded p-4 flex flex-col InsightCard h-full">+ <h3 className="text-lg font-semibold mb-2">Tag frequency over time</h3>+ <p className="text-muted text-sm mb-4">Showing how often each tag is applied</p>+ <div className="flex-1 flex flex-col min-h-0">+ <Query+ query={{ kind: NodeKind.InsightVizNode, source: chartQuery } as InsightVizNode}+ readOnly+ embedded+ inSharedMode+ context={{+ insightProps: {+ dashboardItemId: 'new-tag-metrics-chart',+ dataNodeCollectionId: TAG_METRICS_COLLECTION_ID,+ },+ }}+ />+ </div>+ </div>+ ) : (+ <div className="flex-1 bg-bg-light border rounded p-8 flex items-center justify-center">+ <div className="text-muted text-center">+ No tag data yet. Enable taggers and send some generations to see metrics.+ </div>+ </div>+ )}++ <div className="flex-1 grid grid-cols-2 gap-4">+ <SummaryCard+ title="Enabled taggers"+ value={enabledTaggerCount}+ subtitle={`${taggers.length} total`}+ />+ <SummaryCard+ title="Tag runs"+ value={summaryMetrics.total_runs}+ subtitle={summaryMetrics.total_runs === 0 ? 'No activity' : undefined}+ />+ <TopTagsCard tags={tagStats} />+ </div>+ </div>+ </div>+ )+}diff --git a/products/llm_analytics/frontend/tags/hogTaggerExamples.ts b/products/llm_analytics/frontend/tags/hogTaggerExamples.tsnew file mode 100644index 000000000000..ea2540210b9b--- /dev/null+++ b/products/llm_analytics/frontend/tags/hogTaggerExamples.ts@@ -0,0 +1,136 @@+export interface HogTaggerExample {+ label: string+ source: string+}++export const HOG_TAGGER_EXAMPLES: HogTaggerExample[] = [+ {+ label: 'Keyword matching',+ source: `// Tag based on keywords in the output+// Globals: input, output, properties, event, tags+let result := []+if (output ilike '%billing%' or output ilike '%invoice%' or output ilike '%payment%') {+ result := arrayPushBack(result, 'billing')+}+if (output ilike '%feature flag%' or output ilike '%flag%' or output ilike '%rollout%') {+ result := arrayPushBack(result, 'feature-flags')+}+if (output ilike '%analytics%' or output ilike '%dashboard%' or output ilike '%insight%') {+ result := arrayPushBack(result, 'analytics')+}+print(concat('Found ', toString(length(result)), ' tags'))+return result`,+ },+ {+ label: 'Error detection',+ source: `// Tag generations that contain error patterns+let result := []+let patterns := [+ ['error', 'contains-error'],+ ['exception', 'contains-error'],+ ['traceback', 'contains-error'],+ ['sorry', 'apology'],+ ['I cannot', 'refusal'],+ ['I can\\'t', 'refusal']+]+for (let i, pair in patterns) {+ if (output ilike concat('%', pair.1, '%') and not has(result, pair.2)) {+ result := arrayPushBack(result, pair.2)+ print(concat('Matched "', pair.1, '" -> ', pair.2))+ }+}+return result`,+ },+ {+ label: 'Response length',+ source: `// Tag by response length+let len := length(output)+if (len == 0) {+ print('Empty response')+ return ['empty']+} else if (len < 50) {+ print(concat('Short: ', toString(len), ' chars'))+ return ['short']+} else if (len > 2000) {+ print(concat('Long: ', toString(len), ' chars'))+ return ['long']+} else {+ print(concat('Medium: ', toString(len), ' chars'))+ return ['medium']+}`,+ },+ {+ label: 'Model-based',+ source: `// Tag based on which model was used+let model := ifNull(properties.$ai_model, 'unknown')+let result := []+if (model ilike '%gpt%') {+ result := arrayPushBack(result, 'openai')+} else if (model ilike '%claude%') {+ result := arrayPushBack(result, 'anthropic')+} else if (model ilike '%gemini%') {+ result := arrayPushBack(result, 'google')+} else {+ result := arrayPushBack(result, 'other')+}+print(concat('Model: ', model))+return result`,+ },+ {+ label: 'Cost tiers',+ source: `// Tag by cost tier+let cost := ifNull(properties.$ai_total_cost_usd, 0)+if (cost == 0) {+ return ['free']+} else if (cost < 0.01) {+ return ['cheap']+} else if (cost < 0.10) {+ return ['moderate']+} else {+ print(concat('Expensive: $', toString(cost)))+ return ['expensive']+}`,+ },+ {+ label: 'Roles found',+ source: `// Tag which message roles and features appear in the conversation+let result := []+let combined := concat(input, ' ', output)+let roles := ['system', 'user', 'assistant', 'tool', 'function']+for (let i, role in roles) {+ if (combined ilike concat('%"role": "', role, '"%') or combined ilike concat('%"role":"', role, '"%')) {+ result := arrayPushBack(result, concat('has-', role))+ print(concat('Found role: ', role))+ }+}+if (combined ilike '%"tool_calls"%' or combined ilike '%"function_call"%') {+ result := arrayPushBack(result, 'has-tool-calls')+ print('Found tool calls')+}+if (length(result) == 0) {+ result := arrayPushBack(result, 'no-roles')+}+return result`,+ },+ {+ label: 'Language detection',+ source: `// Simple language detection based on common words+let result := []+if (output ilike '% the %' or output ilike '% is %' or output ilike '% and %') {+ result := arrayPushBack(result, 'english')+}+if (output ilike '% le %' or output ilike '% est %' or output ilike '% les %') {+ result := arrayPushBack(result, 'french')+}+if (output ilike '% der %' or output ilike '% ist %' or output ilike '% und %') {+ result := arrayPushBack(result, 'german')+}+if (output ilike '% el %' or output ilike '% es %' or output ilike '% los %') {+ result := arrayPushBack(result, 'spanish')+}+if (length(result) == 0) {+ result := arrayPushBack(result, 'other')+}+return result`,+ },+]diff --git a/products/llm_analytics/frontend/tags/llmTaggerLogic.test.ts b/products/llm_analytics/frontend/tags/llmTaggerLogic.test.tsnew file mode 100644index 000000000000..674866d03797--- /dev/null+++ b/products/llm_analytics/frontend/tags/llmTaggerLogic.test.ts@@ -0,0 +1,527 @@+let uuidCounter = 0+Object.defineProperty(globalThis, 'crypto', {+ value: {+ randomUUID: () => `mock-uuid-${String(uuidCounter++).padStart(4, '0')}`,+ },+})++import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'+import { llmTaggerLogic } from './llmTaggerLogic'+import { Tagger, TaggerType } from './types'++const mockProviderKeys: LLMProviderKey[] = [+ {+ id: 'key-1',+ provider: 'openai',+ name: 'OpenAI Key',+ state: 'ok',+ error_message: null,+ api_key_masked: 'sk-...1234',+ azure_endpoint_display: null,+ api_version_display: null,+ created_at: '2024-01-01T00:00:00Z',+ created_by: null,+ last_used_at: null,+ },+ {+ id: 'key-2',+ provider: 'anthropic',+ name: 'Anthropic Key',+ state: 'ok',+ error_message: null,+ api_key_masked: 'sk-ant-...5678',+ azure_endpoint_display: null,+ api_version_display: null,+ created_at: '2024-01-02T00:00:00Z',+ created_by: null,+ last_used_at: null,+ },+]++const mockTagger: Tagger = {+ id: 'tagger-123',+ name: 'Test Tagger',+ description: 'A test tagger',+ enabled: true,+ tagger_type: 'llm' as TaggerType,+ tagger_config: {+ prompt: 'Tag this generation',+ tags: [+ { name: 'billing', description: 'Billing related' },+ { name: 'support', description: 'Support related' },+ ],+ min_tags: 0,+ max_tags: null,+ },+ conditions: [{ id: 'cond-1', rollout_percentage: 50, properties: [] }],+ model_configuration: {+ provider: 'openai',+ model: 'gpt-5-mini',+ provider_key_id: 'key-1',+ },+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+}++describe('llmTaggerLogic', () => {+ let logic: ReturnType<typeof llmTaggerLogic.build>+ let keysLogic: ReturnType<typeof llmProviderKeysLogic.build>++ beforeEach(() => {+ uuidCounter = 0+ useMocks({+ get: {+ '/api/environments/:team_id/llm_analytics/provider_keys/': { results: mockProviderKeys },+ '/api/environments/:team_id/taggers/:id/': mockTagger,+ },+ post: {+ '/api/environments/:team_id/query/:kind': { results: [] },+ },+ })+ initKeaTests()+ keysLogic = llmProviderKeysLogic()+ keysLogic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ keysLogic?.unmount()+ })++ describe('new tagger', () => {+ beforeEach(() => {+ logic = llmTaggerLogic({ id: 'new' })+ logic.mount()+ })++ it('isNewTagger is true', () => {+ expect(logic.values.isNewTagger).toBe(true)+ })++ it('has default form values', () => {+ expect(logic.values.taggerForm).toMatchObject({+ name: '',+ description: '',+ enabled: false,+ tagger_type: 'llm',+ tagger_config: {+ prompt: '',+ tags: [{ name: '', description: '' }],+ min_tags: 0,+ max_tags: null,+ },+ model_configuration: null,+ })+ })++ it('does not load tagger from API', async () => {+ await expectLogic(logic).toNotHaveDispatchedActions(['loadTaggerSuccess'])+ })+ })++ describe('existing tagger', () => {+ beforeEach(() => {+ logic = llmTaggerLogic({ id: 'tagger-123' })+ logic.mount()+ })++ it('isNewTagger is false', () => {+ expect(logic.values.isNewTagger).toBe(false)+ })++ it('loads tagger and populates form', async () => {+ await expectLogic(logic).toDispatchActions(['loadTaggerSuccess'])++ expect(logic.values.tagger).toEqual(mockTagger)+ expect(logic.values.taggerForm).toMatchObject({+ name: 'Test Tagger',+ description: 'A test tagger',+ enabled: true,+ tagger_type: 'llm',+ tagger_config: mockTagger.tagger_config,+ })+ })++ it('loads tag runs on mount', async () => {+ await expectLogic(logic).toDispatchActions(['loadTagRuns'])+ })+ })++ describe('reducers', () => {+ beforeEach(() => {+ logic = llmTaggerLogic({ id: 'tagger-123' })+ logic.mount()+ })++ it('selectedModel is set from loaded tagger', async () => {+ await expectLogic(logic).toDispatchActions(['loadTaggerSuccess']).toMatchValues({+ selectedModel: 'gpt-5-mini',+ })+ })++ it('selectedPickerProviderKeyId is set from loaded tagger', async () => {+ await expectLogic(logic).toDispatchActions(['loadTaggerSuccess']).toMatchValues({+ selectedPickerProviderKeyId: 'key-1',+ })+ })++ it('activeTab defaults to runs', () => {+ expect(logic.values.activeTab).toBe('runs')+ })++ it('setActiveTab updates active tab', async () => {+ logic.actions.setActiveTab('configuration')++ await expectLogic(logic).toMatchValues({ activeTab: 'configuration' })+ })++ it('hogTestResults starts as null', () => {+ expect(logic.values.hogTestResults).toBeNull()+ })++ it('clearHogTestResults resets to null', async () => {+ logic.actions.testHogTaggerSuccess([+ {+ event_uuid: 'e1',+ input_preview: 'hello',+ output_preview: 'world',+ tags: ['billing'],+ reasoning: 'matched',+ error: null,+ },+ ])++ await expectLogic(logic).toMatchValues({+ hogTestResults: expect.arrayContaining([expect.objectContaining({ event_uuid: 'e1' })]),+ })++ logic.actions.clearHogTestResults()++ await expectLogic(logic).toMatchValues({ hogTestResults: null })+ })++ it('hogTestLoading tracks test lifecycle', async () => {+ expect(logic.values.hogTestLoading).toBe(false)++ logic.actions.testHogTagger()++ expect(logic.values.hogTestLoading).toBe(true)++ logic.actions.testHogTaggerSuccess([])++ await expectLogic(logic).toMatchValues({ hogTestLoading: false })+ })+ })++ describe('tag management', () => {+ beforeEach(() => {+ logic = llmTaggerLogic({ id: 'new' })+ logic.mount()+ })++ it('addTag appends an empty tag', async () => {+ logic.actions.addTag()++ await expectLogic(logic).toMatchValues({+ taggerForm: expect.objectContaining({+ tagger_config: expect.objectContaining({+ tags: [+ { name: '', description: '' },+ { name: '', description: '' },+ ],+ }),+ }),+ })+ })++ it('removeTag removes tag at index', async () => {+ logic.actions.addTag()+ logic.actions.updateTag(0, 'name', 'first')+ logic.actions.updateTag(1, 'name', 'second')++ logic.actions.removeTag(0)++ await expectLogic(logic).toMatchValues({+ taggerForm: expect.objectContaining({+ tagger_config: expect.objectContaining({+ tags: [{ name: 'second', description: '' }],+ }),+ }),+ })+ })++ it('updateTag updates name field', async () => {+ logic.actions.updateTag(0, 'name', 'billing')++ await expectLogic(logic).toMatchValues({+ taggerForm: expect.objectContaining({+ tagger_config: expect.objectContaining({+ tags: [{ name: 'billing', description: '' }],+ }),+ }),+ })+ })++ it('updateTag updates description field', async () => {+ logic.actions.updateTag(0, 'description', 'Billing related queries')++ await expectLogic(logic).toMatchValues({+ taggerForm: expect.objectContaining({+ tagger_config: expect.objectContaining({+ tags: [{ name: '', description: 'Billing related queries' }],+ }),+ }),+ })+ })+ })++ describe('condition management', () => {+ beforeEach(() => {+ logic = llmTaggerLogic({ id: 'new' })+ logic.mount()+ })++ it('starts with one default condition', () => {+ expect(logic.values.taggerForm.conditions).toHaveLength(1)+ expect(logic.values.taggerForm.conditions[0]).toMatchObject({+ rollout_percentage: 100,+ properties: [],+ })+ })++ it('addCondition appends a new condition', async () => {+ logic.actions.addCondition()++ expect(logic.values.taggerForm.conditions).toHaveLength(2)+ expect(logic.values.taggerForm.conditions[1]).toMatchObject({+ rollout_percentage: 100,+ properties: [],+ })+ })++ it('removeCondition removes condition at index', async () => {+ logic.actions.addCondition()++ expect(logic.values.taggerForm.conditions).toHaveLength(2)+ const secondCondition = logic.values.taggerForm.conditions[1]++ logic.actions.removeCondition(0)++ expect(logic.values.taggerForm.conditions).toHaveLength(1)+ expect(logic.values.taggerForm.conditions[0].id).toBe(secondCondition.id)+ })++ it('setConditions replaces all conditions', async () => {+ const newConditions = [+ { id: 'custom-1', rollout_percentage: 25, properties: [] },+ { id: 'custom-2', rollout_percentage: 75, properties: [] },+ ]+ logic.actions.setConditions(newConditions)++ await expectLogic(logic).toMatchValues({+ taggerForm: expect.objectContaining({+ conditions: newConditions,+ }),+ })+ })+ })++ describe('form validation', () => {+ const submitAndGetErrors = async (): Promise<any> => {+ try {+ await expectLogic(logic, () => {+ logic.actions.submitTaggerForm()+ }).toFinishAllListeners()+ } catch {+ // Expected to fail validation+ }+ return (logic.values as any).taggerFormErrors+ }++ describe('LLM tagger', () => {+ beforeEach(() => {+ logic = llmTaggerLogic({ id: 'new' })+ logic.mount()+ })++ it('requires name', async () => {+ const errors = await submitAndGetErrors()+ expect(errors.name).toBe('Name is required')+ })++ it('requires prompt', async () => {+ const errors = await submitAndGetErrors()+ expect(errors.tagger_config.prompt).toBe('Prompt is required')+ })++ it('reports error when tag name is empty', async () => {+ const errors = await submitAndGetErrors()+ expect(errors.tagger_config.tags).toEqual([{ name: 'All tags must have a name' }])+ })++ it('reports error when no tags exist', async () => {+ logic.actions.removeTag(0)+ const errors = await submitAndGetErrors()+ expect(errors.tagger_config.tags).toEqual([{ name: 'At least one tag is required' }])+ })++ it('clears errors with valid form', async () => {+ logic.actions.setTaggerFormValues({+ name: 'Valid Tagger',+ tagger_config: {+ prompt: 'Tag this',+ tags: [{ name: 'test', description: '' }],+ min_tags: 0,+ max_tags: null,+ },+ })++ const errors = await submitAndGetErrors()+ expect(errors.name).toBeUndefined()+ expect(errors.tagger_config.prompt).toBeUndefined()+ expect(errors.tagger_config.tags).toBeUndefined()+ })+ })++ describe('Hog tagger', () => {+ beforeEach(() => {+ logic = llmTaggerLogic({ id: 'new' })+ logic.mount()+ logic.actions.setTaggerFormValues({ tagger_type: 'hog' })+ })++ it('requires source code', async () => {+ logic.actions.setTaggerFormValues({+ tagger_config: { source: '', tags: [] },+ })+ const errors = await submitAndGetErrors()+ expect(errors.tagger_config.source).toBe('Hog source code is required')+ })++ it('does not require prompt or tags', async () => {+ logic.actions.setTaggerFormValues({+ name: 'Hog Tagger',+ tagger_config: { source: 'return []', tags: [] },+ })+ const errors = await submitAndGetErrors()+ expect(errors.name).toBeUndefined()+ expect(errors.tagger_config.source).toBeUndefined()+ expect(errors.tagger_config).not.toHaveProperty('prompt')+ expect(errors.tagger_config).not.toHaveProperty('tags')+ })+ })+ })++ describe('selectModelFromPicker', () => {+ beforeEach(() => {+ logic = llmTaggerLogic({ id: 'new' })+ logic.mount()+ })++ it('sets model configuration from BYOK provider key', async () => {+ await expectLogic(keysLogic).toDispatchActions(['loadProviderKeysSuccess'])++ logic.actions.selectModelFromPicker('gpt-5', 'key-1')++ await expectLogic(logic).toMatchValues({+ selectedModel: 'gpt-5',+ taggerForm: expect.objectContaining({+ model_configuration: {+ provider: 'openai',+ model: 'gpt-5',+ provider_key_id: 'key-1',+ },+ }),+ })+ })++ it('sets model configuration from trial provider key', async () => {+ logic.actions.selectModelFromPicker('gpt-5', 'trial:openai')++ await expectLogic(logic).toMatchValues({+ selectedModel: 'gpt-5',+ taggerForm: expect.objectContaining({+ model_configuration: {+ provider: 'openai',+ model: 'gpt-5',+ provider_key_id: null,+ },+ }),+ })+ })++ it('ignores empty modelId', async () => {+ logic.actions.selectModelFromPicker('', 'key-1')++ await expectLogic(logic).toMatchValues({+ selectedModel: '',+ taggerForm: expect.objectContaining({+ model_configuration: null,+ }),+ })+ })+ })++ describe('loadTagRuns', () => {+ it('returns empty for new tagger', async () => {+ logic = llmTaggerLogic({ id: 'new' })+ logic.mount()++ logic.actions.loadTagRuns()++ await expectLogic(logic).toDispatchActions(['loadTagRunsSuccess']).toMatchValues({+ tagRuns: [],+ })+ })++ it('parses query results into TagRun objects', async () => {+ logic = llmTaggerLogic({ id: 'tagger-123' })+ logic.mount()++ // Wait for initial load (returns empty from default mock)+ await expectLogic(logic).toDispatchActions(['loadTagRunsSuccess'])++ // Now override the query mock and reload+ useMocks({+ post: {+ '/api/environments/:team_id/query/:kind': {+ results: [+ [+ '2024-01-01T12:00:00Z',+ '["billing","support"]',+ 'Found billing keyword',+ 'trace-1',+ 'event-1',+ 'tagger-123',+ 'Test Tagger',+ ],+ ],+ },+ },+ })++ logic.actions.loadTagRuns()++ await expectLogic(logic)+ .toDispatchActions(['loadTagRunsSuccess'])+ .toMatchValues({+ tagRuns: [+ {+ timestamp: '2024-01-01T12:00:00Z',+ tags: ['billing', 'support'],+ reasoning: 'Found billing keyword',+ trace_id: 'trace-1',+ target_event_id: 'event-1',+ tagger_id: 'tagger-123',+ tagger_name: 'Test Tagger',+ },+ ],+ })+ })+ })+})diff --git a/products/llm_analytics/frontend/tags/llmTaggerLogic.ts b/products/llm_analytics/frontend/tags/llmTaggerLogic.tsnew file mode 100644index 000000000000..1ff1d1473d3b--- /dev/null+++ b/products/llm_analytics/frontend/tags/llmTaggerLogic.ts@@ -0,0 +1,477 @@+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { forms } from 'kea-forms'+import { router } from 'kea-router'++import api from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { HogQLQuery, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'+import { ChartDisplayType, PropertyFilterType, PropertyOperator } from '~/types'++import { llmAnalyticsSharedLogic } from '../llmAnalyticsSharedLogic'+import { parseTrialProviderKeyId } from '../ModelPicker'+import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'+import type { llmTaggerLogicType } from './llmTaggerLogicType'+import { llmTaggersLogic } from './llmTaggersLogic'+import {+ getIntervalFromDateRange,+ ModelConfiguration,+ Tagger,+ TaggerConditionSet,+ TaggerConfig,+ TaggerType,+} from './types'++export interface HogTestResult {+ event_uuid: string+ trace_id?: string | null+ input_preview: string+ output_preview: string+ tags: string[]+ reasoning: string+ error: string | null+}++export interface TagRun {+ timestamp: string+ tags: string[]+ reasoning: string+ trace_id: string+ target_event_id: string+ tagger_id: string+ tagger_name: string+}++export interface LLMTaggerLogicProps {+ id: string | 'new'+}++const DEFAULT_TAGGER_CONFIG: TaggerConfig = {+ prompt: '',+ tags: [{ name: '', description: '' }],+ min_tags: 0,+ max_tags: null,+}++const DEFAULT_CONDITION: TaggerConditionSet = {+ id: crypto.randomUUID(),+ rollout_percentage: 100,+ properties: [],+}++export interface TaggerForm {+ name: string+ description: string+ enabled: boolean+ tagger_type: TaggerType+ tagger_config: TaggerConfig+ conditions: TaggerConditionSet[]+ model_configuration: ModelConfiguration | null+}++const DEFAULT_FORM: TaggerForm = {+ name: '',+ description: '',+ enabled: false,+ tagger_type: 'llm',+ tagger_config: DEFAULT_TAGGER_CONFIG,+ conditions: [DEFAULT_CONDITION],+ model_configuration: null,+}++export const llmTaggerLogic = kea<llmTaggerLogicType>([+ path(['products', 'llm_analytics', 'taggers', 'llmTaggerLogic']),+ props({} as LLMTaggerLogicProps),+ key((props) => props.id),++ connect(() => ({+ values: [llmProviderKeysLogic, ['providerKeys'], llmAnalyticsSharedLogic, ['dateFilter']],+ actions: [llmProviderKeysLogic, ['loadProviderKeys'], llmAnalyticsSharedLogic, ['setDates']],+ })),++ actions({+ selectModelFromPicker: (modelId: string, providerKeyId: string) => ({ modelId, providerKeyId }),+ setConditions: (conditions: TaggerConditionSet[]) => ({ conditions }),+ loadTagger: true,+ loadTaggerSuccess: (tagger: Tagger) => ({ tagger }),+ deleteTagger: true,+ addTag: true,+ removeTag: (index: number) => ({ index }),+ updateTag: (index: number, field: 'name' | 'description', value: string) => ({ index, field, value }),+ addCondition: true,+ removeCondition: (index: number) => ({ index }),+ setActiveTab: (tab: 'runs' | 'configuration') => ({ tab }),+ loadTagRuns: true,+ loadTagRunsSuccess: (runs: TagRun[]) => ({ runs }),+ testHogTagger: true,+ testHogTaggerSuccess: (results: HogTestResult[]) => ({ results }),+ clearHogTestResults: true,+ }),++ reducers({+ tagger: [+ null as Tagger | null,+ {+ loadTaggerSuccess: (_, { tagger }) => tagger,+ },+ ],+ taggerLoading: [+ false,+ {+ loadTagger: () => true,+ loadTaggerSuccess: () => false,+ },+ ],+ selectedModel: [+ '' as string,+ {+ selectModelFromPicker: (_, { modelId }) => modelId,+ loadTaggerSuccess: (_, { tagger }) => tagger?.model_configuration?.model || '',+ },+ ],+ selectedPickerProviderKeyId: [+ null as string | null,+ {+ selectModelFromPicker: (_, { providerKeyId }) => providerKeyId,+ loadTaggerSuccess: (_, { tagger }) => tagger?.model_configuration?.provider_key_id || null,+ },+ ],+ activeTab: [+ 'runs' as string,+ {+ setActiveTab: (_, { tab }) => tab,+ },+ ],+ tagRuns: [+ [] as TagRun[],+ {+ loadTagRunsSuccess: (_, { runs }) => runs,+ },+ ],+ tagRunsLoading: [+ false,+ {+ loadTagRuns: () => true,+ loadTagRunsSuccess: () => false,+ },+ ],+ hogTestResults: [+ null as HogTestResult[] | null,+ {+ testHogTaggerSuccess: (_, { results }) => results,+ clearHogTestResults: () => null,+ },+ ],+ hogTestLoading: [+ false,+ {+ testHogTagger: () => true,+ testHogTaggerSuccess: () => false,+ },+ ],+ }),++ selectors({+ isNewTagger: [(_, props) => [props.id], (id: string) => id === 'new'],++ runsChartQuery: [+ (s, props) => [props.id, s.dateFilter],+ (id: string, dateFilter: { dateFrom: string | null; dateTo: string | null }): TrendsQuery | null => {+ if (id === 'new') {+ return null+ }++ const dateFrom = dateFilter.dateFrom || '-7d'+ const dateTo = dateFilter.dateTo || null+ const interval = getIntervalFromDateRange(dateFrom)++ return {+ kind: NodeKind.TrendsQuery,+ series: [+ {+ kind: NodeKind.EventsNode,+ event: '$ai_tag',+ math: 'total' as any,+ properties: [+ {+ key: '$ai_tagger_id',+ value: id,+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ },+ ],+ },+ ],+ breakdownFilter: {+ // Emit one breakdown row per event. If $ai_tags is empty, bucket under+ // "(no tag)" so the chart still reflects that the tagger is running even+ // when no tags matched (otherwise arrayJoin on [] drops the event).+ breakdown:+ "arrayJoin(if(length(JSONExtract(ifNull(properties.$ai_tags, '[]'), 'Array(String)')) = 0, ['(no tag)'], JSONExtract(ifNull(properties.$ai_tags, '[]'), 'Array(String)')))",+ breakdown_type: 'hogql',+ },+ trendsFilter: {+ // Stacked area makes the composition read naturally: total height = run+ // volume, colored bands = tag share. Handles the "(no tag)" bucket cleanly+ // without it looking like a stray zero-line.+ display: ChartDisplayType.ActionsAreaGraph,+ },+ dateRange: {+ date_from: dateFrom,+ date_to: dateTo,+ },+ interval,+ }+ },+ ],+ }),++ forms(({ props }) => ({+ taggerForm: {+ defaults: DEFAULT_FORM,+ errors: (values: TaggerForm) => ({+ name: !values.name ? 'Name is required' : undefined,+ tagger_config:+ values.tagger_type === 'hog'+ ? {+ source: !('source' in values.tagger_config && values.tagger_config.source?.trim())+ ? 'Hog source code is required'+ : undefined,+ }+ : {+ prompt: !('prompt' in values.tagger_config && values.tagger_config.prompt)+ ? 'Prompt is required'+ : undefined,+ // kea-forms expects per-tag errors as an array matching tags[]. The+ // array type does not allow `undefined` slots, so use `{}` for+ // tags with no error. Synthesize a single-entry error for the+ // empty-tags case so the form stays invalid (the UI guardrail+ // blocks reaching this state, but a programmatic removeTag could).+ tags:+ values.tagger_config.tags.length === 0+ ? [{ name: 'At least one tag is required' }]+ : values.tagger_config.tags.some((t) => !t.name.trim())+ ? values.tagger_config.tags.map((t) =>+ !t.name.trim() ? { name: 'All tags must have a name' } : {}+ )+ : undefined,+ },+ }),+ submit: async (values: TaggerForm) => {+ const payload = {+ ...values,+ tagger_config: {+ ...values.tagger_config,+ tags: values.tagger_config.tags.filter((t) => t.name.trim()),+ },+ }++ if (props.id === 'new') {+ await api.create('api/environments/@current/taggers/', payload)+ lemonToast.success('Tagger created')+ } else {+ await api.update(`api/environments/@current/taggers/${props.id}/`, payload)+ lemonToast.success('Tagger updated')+ }+ // Reload list before navigating so the new/updated tagger is visible+ llmTaggersLogic.findMounted()?.actions.loadTaggers()+ router.actions.push(urls.llmAnalyticsTags())+ },+ },+ })),++ listeners(({ props, actions, values }) => ({+ testHogTagger: async () => {+ const config = values.taggerForm.tagger_config+ const source = 'source' in config ? config.source : ''+ if (!source) {+ return+ }+ try {+ const teamId = teamLogic.values.currentTeamId+ const response = await api.create(`/api/environments/${teamId}/taggers/test_hog/`, {+ source,+ sample_count: 5,+ tags: config.tags.filter((t: { name: string }) => t.name.trim()),+ })+ actions.testHogTaggerSuccess(response.results || [])+ } catch (error) {+ console.error('Hog tagger test failed:', error)+ actions.testHogTaggerSuccess([])+ }+ },+ loadTagRuns: async () => {+ if (props.id === 'new') {+ actions.loadTagRunsSuccess([])+ return+ }+ const dateFrom = values.dateFilter?.dateFrom || '-24h'+ const dateTo = values.dateFilter?.dateTo || null+ // Use a HogQL parameter placeholder rather than string interpolation —+ // props.id comes from the URL path, so interpolating it directly into+ // the query text would open an injection vector.+ const query: HogQLQuery = {+ kind: NodeKind.HogQLQuery,+ query: `+ SELECT+ timestamp,+ properties.$ai_tags as tags,+ properties.$ai_tag_reasoning as reasoning,+ properties.$ai_trace_id as trace_id,+ properties.$ai_target_event_id as target_event_id,+ properties.$ai_tagger_id as tagger_id,+ properties.$ai_tagger_name as tagger_name+ FROM events+ WHERE event = '$ai_tag'+ AND properties.$ai_tagger_id = {tagger_id}+ AND {filters}+ ORDER BY timestamp DESC+ LIMIT 100+ `,+ values: { tagger_id: props.id },+ filters: {+ dateRange: {+ date_from: dateFrom,+ date_to: dateTo,+ },+ },+ }+ try {+ const response = await api.query(query)+ const runs = (response.results || []).map((row: any[]) => ({+ timestamp: row[0],+ tags: typeof row[1] === 'string' ? JSON.parse(row[1]) : row[1] || [],+ reasoning: row[2] || '',+ trace_id: row[3] || '',+ target_event_id: row[4] || '',+ tagger_id: row[5] || '',+ tagger_name: row[6] || '',+ }))+ actions.loadTagRunsSuccess(runs)+ } catch {+ actions.loadTagRunsSuccess([])+ }+ },+ loadTagger: async () => {+ if (props.id === 'new') {+ return+ }+ // Wrap in try/catch so a failed fetch clears taggerLoading — otherwise+ // the UI is stuck on the skeleton indefinitely on any API error.+ try {+ const tagger = await api.get(`api/environments/@current/taggers/${props.id}/`)+ actions.loadTaggerSuccess(tagger)+ actions.setTaggerFormValues({+ name: tagger.name,+ description: tagger.description || '',+ enabled: tagger.enabled,+ tagger_type: tagger.tagger_type || 'llm',+ tagger_config: tagger.tagger_config,+ conditions: tagger.conditions.length > 0 ? tagger.conditions : [DEFAULT_CONDITION],+ model_configuration: tagger.model_configuration,+ })+ } catch (error) {+ lemonToast.error(`Failed to load tagger: ${error instanceof Error ? error.message : String(error)}`)+ actions.loadTaggerSuccess(null as any)+ }+ },+ deleteTagger: async () => {+ if (props.id === 'new') {+ return+ }+ await api.update(`api/environments/@current/taggers/${props.id}/`, { deleted: true })+ lemonToast.success('Tagger deleted')+ router.actions.push(urls.llmAnalyticsTags())+ },+ addTag: () => {+ const current = values.taggerForm.tagger_config+ actions.setTaggerFormValues({+ tagger_config: {+ ...current,+ tags: [...current.tags, { name: '', description: '' }],+ },+ })+ },+ removeTag: ({ index }) => {+ const current = values.taggerForm.tagger_config+ actions.setTaggerFormValues({+ tagger_config: {+ ...current,+ tags: current.tags.filter((_, i) => i !== index),+ },+ })+ },+ updateTag: ({ index, field, value }) => {+ const current = values.taggerForm.tagger_config+ const tags = [...current.tags]+ tags[index] = { ...tags[index], [field]: value }+ actions.setTaggerFormValues({+ tagger_config: {+ ...current,+ tags,+ },+ })+ },+ addCondition: () => {+ actions.setTaggerFormValues({+ conditions: [+ ...values.taggerForm.conditions,+ { id: crypto.randomUUID(), rollout_percentage: 100, properties: [] },+ ],+ })+ },+ removeCondition: ({ index }) => {+ actions.setTaggerFormValues({+ conditions: values.taggerForm.conditions.filter((_, i) => i !== index),+ })+ },+ setConditions: ({ conditions }) => {+ actions.setTaggerFormValues({ conditions })+ },+ selectModelFromPicker: ({ modelId, providerKeyId }) => {+ if (!modelId) {+ return+ }+ const trialProvider = parseTrialProviderKeyId(providerKeyId)+ if (trialProvider) {+ actions.setTaggerFormValues({+ model_configuration: {+ provider: trialProvider,+ model: modelId,+ provider_key_id: null,+ },+ })+ return+ }+ const key = values.providerKeys.find((k: LLMProviderKey) => k.id === providerKeyId)+ if (key) {+ actions.setTaggerFormValues({+ model_configuration: {+ provider: key.provider,+ model: modelId,+ provider_key_id: providerKeyId,+ },+ })+ }+ },+ setDates: () => {+ if (props.id !== 'new') {+ actions.loadTagRuns()+ }+ },+ })),++ afterMount(({ actions, props }) => {+ if (props.id !== 'new') {+ actions.loadTagger()+ actions.loadTagRuns()+ }+ // Read initial tab from URL search params+ const { searchParams } = router.values+ if (searchParams.tab === 'configuration' || searchParams.tab === 'runs') {+ actions.setActiveTab(searchParams.tab)+ }+ }),+])diff --git a/products/llm_analytics/frontend/tags/llmTaggersLogic.test.ts b/products/llm_analytics/frontend/tags/llmTaggersLogic.test.tsnew file mode 100644index 000000000000..3aab5ceb3e95--- /dev/null+++ b/products/llm_analytics/frontend/tags/llmTaggersLogic.test.ts@@ -0,0 +1,235 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { llmTaggersLogic } from './llmTaggersLogic'+import { defaultTaggerTemplates } from './templates'+import { Tagger, TaggerType } from './types'++const makeTagger = (overrides: Partial<Tagger> & { id: string; name: string }): Tagger => ({+ enabled: true,+ tagger_type: 'llm' as TaggerType,+ tagger_config: {+ prompt: 'Test prompt',+ tags: [{ name: 'test-tag', description: 'A test tag' }],+ min_tags: 0,+ max_tags: null,+ },+ conditions: [{ id: 'cond-1', rollout_percentage: 100, properties: [] }],+ model_configuration: null,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ ...overrides,+})++const mockTaggers: Tagger[] = [+ makeTagger({ id: 'tagger-1', name: 'Topic tags', description: 'Tag topics' }),+ makeTagger({+ id: 'tagger-2',+ name: 'Safety flags',+ description: 'Flag safety issues',+ tagger_config: {+ prompt: 'Check safety',+ tags: [+ { name: 'pii', description: 'PII detected' },+ { name: 'harmful', description: 'Harmful content' },+ ],+ min_tags: 0,+ max_tags: null,+ },+ }),+ makeTagger({+ id: 'tagger-3',+ name: 'Hog classifier',+ tagger_type: 'hog',+ tagger_config: {+ source: 'return []',+ tags: [{ name: 'billing', description: 'Billing related' }],+ },+ }),+]++describe('llmTaggersLogic', () => {+ let logic: ReturnType<typeof llmTaggersLogic.build>++ describe('loading existing taggers', () => {+ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:team_id/taggers/': { results: mockTaggers },+ },+ })+ initKeaTests()+ logic = llmTaggersLogic()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('loads taggers on mount', async () => {+ await expectLogic(logic).toDispatchActions(['loadTaggers', 'loadTaggersSuccess']).toMatchValues({+ taggers: mockTaggers,+ taggersLoading: false,+ })+ })++ it('sets taggersLoading while loading', async () => {+ await expectLogic(logic).toMatchValues({+ taggersLoading: true,+ })++ await expectLogic(logic).toDispatchActions(['loadTaggersSuccess']).toMatchValues({+ taggersLoading: false,+ })+ })+ })++ describe('seeding defaults', () => {+ let createCalls: Record<string, unknown>[]++ beforeEach(() => {+ createCalls = []+ let firstGet = true+ useMocks({+ get: {+ '/api/environments/:team_id/taggers/': () => {+ if (firstGet) {+ firstGet = false+ return [200, { results: [] }]+ }+ return [200, { results: mockTaggers }]+ },+ },+ post: {+ '/api/environments/:team_id/taggers/': (req: any) => {+ createCalls.push(req.body)+ return [200, { id: `new-${createCalls.length}`, ...req.body }]+ },+ },+ })+ initKeaTests()+ logic = llmTaggersLogic()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('seeds default taggers when none exist and creates them disabled', async () => {+ await expectLogic(logic).toDispatchActions(['loadTaggersSuccess'])++ expect(createCalls).toHaveLength(defaultTaggerTemplates.length)+ for (const call of createCalls) {+ expect(call).toMatchObject({ enabled: false })+ }+ })+ })++ describe('filteredTaggers selector', () => {+ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:team_id/taggers/': { results: mockTaggers },+ },+ })+ initKeaTests()+ logic = llmTaggersLogic()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('returns all taggers when filter is empty', async () => {+ await expectLogic(logic).toDispatchActions(['loadTaggersSuccess'])++ expect(logic.values.filteredTaggers).toHaveLength(3)+ })++ it('filters by tagger name', async () => {+ await expectLogic(logic).toDispatchActions(['loadTaggersSuccess'])++ logic.actions.setTaggersFilter('topic')++ await expectLogic(logic).toMatchValues({+ filteredTaggers: [expect.objectContaining({ id: 'tagger-1', name: 'Topic tags' })],+ })+ })++ it('filters by tagger description', async () => {+ await expectLogic(logic).toDispatchActions(['loadTaggersSuccess'])++ logic.actions.setTaggersFilter('safety issues')++ await expectLogic(logic).toMatchValues({+ filteredTaggers: [expect.objectContaining({ id: 'tagger-2' })],+ })+ })++ it('filters by tag name', async () => {+ await expectLogic(logic).toDispatchActions(['loadTaggersSuccess'])++ logic.actions.setTaggersFilter('billing')++ await expectLogic(logic).toMatchValues({+ filteredTaggers: [expect.objectContaining({ id: 'tagger-3' })],+ })+ })++ it('filter is case-insensitive', async () => {+ await expectLogic(logic).toDispatchActions(['loadTaggersSuccess'])++ logic.actions.setTaggersFilter('TOPIC')++ await expectLogic(logic).toMatchValues({+ filteredTaggers: [expect.objectContaining({ id: 'tagger-1' })],+ })+ })++ it('returns empty when no match', async () => {+ await expectLogic(logic).toDispatchActions(['loadTaggersSuccess'])++ logic.actions.setTaggersFilter('nonexistent')++ await expectLogic(logic).toMatchValues({+ filteredTaggers: [],+ })+ })+ })++ describe('toggleTaggerEnabled', () => {+ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:team_id/taggers/': { results: mockTaggers },+ '/api/environments/:team_id/taggers/:id/': mockTaggers[0],+ },+ patch: {+ '/api/environments/:team_id/taggers/:id/': () => {+ return [200, { ...mockTaggers[0], enabled: !mockTaggers[0].enabled }]+ },+ },+ })+ initKeaTests()+ logic = llmTaggersLogic()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('reloads taggers after toggling', async () => {+ await expectLogic(logic).toDispatchActions(['loadTaggersSuccess'])++ logic.actions.toggleTaggerEnabled('tagger-1')++ await expectLogic(logic).toDispatchActions(['toggleTaggerEnabled', 'loadTaggers', 'loadTaggersSuccess'])+ })+ })+})diff --git a/products/llm_analytics/frontend/tags/llmTaggersLogic.ts b/products/llm_analytics/frontend/tags/llmTaggersLogic.tsnew file mode 100644index 000000000000..3f2af5ac25ed--- /dev/null+++ b/products/llm_analytics/frontend/tags/llmTaggersLogic.ts@@ -0,0 +1,298 @@+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { teamLogic } from 'scenes/teamLogic'++import { HogQLQuery, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'+import { ChartDisplayType } from '~/types'++import { llmAnalyticsSharedLogic } from '../llmAnalyticsSharedLogic'+import type { llmTaggersLogicType } from './llmTaggersLogicType'+import { defaultTaggerTemplates } from './templates'+import { getIntervalFromDateRange, Tagger } from './types'++export interface LLMTaggersLogicProps {+ tabId?: string+}++export interface TaggerRunStats {+ tagger_id: string+ runs_count: number+}++export interface TaggerTagCount {+ tagger_id: string+ tag_name: string+ count: number+}++type RawStatsRow = [tagger_id: string, runs_count: number]+type RawTagCountRow = [tagger_id: string, tag_name: string, count: number]++export const llmTaggersLogic = kea<llmTaggersLogicType>([+ path(['products', 'llm_analytics', 'taggers', 'llmTaggersLogic']),+ props({} as LLMTaggersLogicProps),+ key((props) => props.tabId ?? 'default'),+ connect(() => ({+ values: [featureFlagLogic, ['featureFlags'], llmAnalyticsSharedLogic, ['dateFilter']],+ actions: [teamLogic, ['addProductIntent'], llmAnalyticsSharedLogic, ['setDates']],+ })),++ actions({+ loadTaggers: true,+ loadTaggersSuccess: (taggers: Tagger[]) => ({ taggers }),+ toggleTaggerEnabled: (id: string) => ({ id }),+ setTaggersFilter: (filter: string) => ({ filter }),+ }),++ reducers({+ taggers: [+ [] as Tagger[],+ {+ loadTaggersSuccess: (_, { taggers }) => taggers,+ },+ ],+ taggersLoading: [+ false,+ {+ loadTaggers: () => true,+ loadTaggersSuccess: () => false,+ },+ ],+ taggersFilter: [+ '',+ {+ setTaggersFilter: (_, { filter }) => filter,+ },+ ],+ hasSeededDefaults: [+ false,+ {+ loadTaggersSuccess: () => true,+ },+ ],+ }),++ loaders(({ values }) => ({+ runStats: [+ [] as TaggerRunStats[],+ {+ loadRunStats: async () => {+ const dateFrom = values.dateFilter.dateFrom || '-7d'+ const dateTo = values.dateFilter.dateTo || null++ const query: HogQLQuery = {+ kind: NodeKind.HogQLQuery,+ query: `+ SELECT+ properties.$ai_tagger_id as tagger_id,+ count() as runs_count+ FROM events+ WHERE event = '$ai_tag' AND {filters}+ GROUP BY tagger_id+ `,+ filters: {+ dateRange: {+ date_from: dateFrom,+ date_to: dateTo,+ },+ },+ }++ try {+ const response = await api.query(query)+ return (response.results || []).map((row: RawStatsRow) => ({+ tagger_id: row[0],+ runs_count: row[1],+ }))+ } catch {+ return []+ }+ },+ },+ ],+ tagCounts: [+ [] as TaggerTagCount[],+ {+ loadTagCounts: async () => {+ const dateFrom = values.dateFilter.dateFrom || '-7d'+ const dateTo = values.dateFilter.dateTo || null++ const query: HogQLQuery = {+ kind: NodeKind.HogQLQuery,+ query: `+ SELECT+ properties.$ai_tagger_id as tagger_id,+ arrayJoin(JSONExtract(ifNull(properties.$ai_tags, '[]'), 'Array(String)')) as tag_name,+ count() as cnt+ FROM events+ WHERE event = '$ai_tag' AND {filters}+ GROUP BY tagger_id, tag_name+ ORDER BY tagger_id, cnt DESC+ `,+ filters: {+ dateRange: {+ date_from: dateFrom,+ date_to: dateTo,+ },+ },+ }++ try {+ const response = await api.query(query)+ return (response.results || []).map((row: RawTagCountRow) => ({+ tagger_id: row[0],+ tag_name: row[1],+ count: row[2],+ }))+ } catch {+ return []+ }+ },+ },+ ],+ })),++ selectors({+ filteredTaggers: [+ (s) => [s.taggers, s.taggersFilter],+ (taggers: Tagger[], filter: string): Tagger[] => {+ if (!filter) {+ return taggers+ }+ const lowerFilter = filter.toLowerCase()+ return taggers.filter(+ (tagger) =>+ tagger.name.toLowerCase().includes(lowerFilter) ||+ tagger.description?.toLowerCase().includes(lowerFilter) ||+ tagger.tagger_config.tags.some((tag) => tag.name.toLowerCase().includes(lowerFilter))+ )+ },+ ],++ runStatsMap: [+ (s) => [s.runStats],+ (runStats: TaggerRunStats[]): Record<string, number> => {+ const map: Record<string, number> = {}+ for (const stat of runStats) {+ map[stat.tagger_id] = stat.runs_count+ }+ return map+ },+ ],++ tagDistributionMap: [+ (s) => [s.tagCounts],+ (tagCounts: TaggerTagCount[]): Record<string, Array<{ name: string; percent: number }>> => {+ const byTagger: Record<string, TaggerTagCount[]> = {}+ for (const tc of tagCounts) {+ if (!byTagger[tc.tagger_id]) {+ byTagger[tc.tagger_id] = []+ }+ byTagger[tc.tagger_id].push(tc)+ }+ const result: Record<string, Array<{ name: string; percent: number }>> = {}+ for (const [taggerId, counts] of Object.entries(byTagger)) {+ const total = counts.reduce((sum, c) => sum + c.count, 0)+ result[taggerId] = counts.map((c) => ({+ name: c.tag_name,+ percent: total > 0 ? Math.round((c.count / total) * 100) : 0,+ }))+ }+ return result+ },+ ],++ totalRuns: [+ (s) => [s.runStats],+ (runStats: TaggerRunStats[]): number => runStats.reduce((sum, s) => sum + s.runs_count, 0),+ ],++ chartQuery: [+ (s) => [s.taggers, s.dateFilter],+ (taggers: Tagger[], dateFilter: { dateFrom: string | null; dateTo: string | null }): TrendsQuery | null => {+ if (taggers.filter((t) => t.enabled && !t.deleted).length === 0) {+ return null+ }++ const dateFrom = dateFilter.dateFrom || '-7d'+ const dateTo = dateFilter.dateTo || null+ const interval = getIntervalFromDateRange(dateFrom)++ return {+ kind: NodeKind.TrendsQuery,+ series: [+ {+ kind: NodeKind.EventsNode,+ event: '$ai_tag',+ math: 'total' as any,+ },+ ],+ breakdownFilter: {+ // Bucket runs with no tags under "(no tag)" so taggers still appear+ // on the chart when they ran but produced no matches.+ breakdown:+ "concat(properties.$ai_tagger_name, ' — ', arrayJoin(if(length(JSONExtract(ifNull(properties.$ai_tags, '[]'), 'Array(String)')) = 0, ['(no tag)'], JSONExtract(ifNull(properties.$ai_tags, '[]'), 'Array(String)'))))",+ breakdown_type: 'hogql',+ },+ trendsFilter: {+ display: ChartDisplayType.ActionsLineGraph,+ },+ dateRange: {+ date_from: dateFrom,+ date_to: dateTo,+ },+ interval,+ }+ },+ ],+ }),++ listeners(({ actions, values }) => ({+ loadTaggers: async () => {+ const response = await api.get('api/environments/@current/taggers/')+ if (response.results.length === 0 && !values.hasSeededDefaults) {+ for (const template of defaultTaggerTemplates) {+ await api.create('api/environments/@current/taggers/', {+ name: template.name,+ description: template.description,+ enabled: false,+ tagger_config: template.tagger_config,+ conditions: [{ id: `cond-${Date.now()}`, rollout_percentage: 100, properties: [] }],+ })+ }+ const seeded = await api.get('api/environments/@current/taggers/')+ actions.loadTaggersSuccess(seeded.results)+ } else {+ actions.loadTaggersSuccess(response.results)+ }+ },+ loadTaggersSuccess: () => {+ actions.loadRunStats()+ actions.loadTagCounts()+ },+ toggleTaggerEnabled: async ({ id }, breakpoint) => {+ const tagger = values.taggers.find((t) => t.id === id)+ if (!tagger) {+ return+ }+ await api.update(`api/environments/@current/taggers/${id}/`, { enabled: !tagger.enabled })+ await breakpoint(100)+ actions.loadTaggers()+ },+ setDates: () => {+ actions.loadRunStats()+ actions.loadTagCounts()+ },+ })),++ afterMount(({ actions, values }) => {+ // Default to last 24h if no date range has been set via URL+ if (values.dateFilter.dateFrom === '-1h') {+ actions.setDates('-24h', null)+ }+ actions.loadTaggers()+ }),+])diff --git a/products/llm_analytics/frontend/tags/tagMetricsLogic.ts b/products/llm_analytics/frontend/tags/tagMetricsLogic.tsnew file mode 100644index 000000000000..4c2d8a4f537c--- /dev/null+++ b/products/llm_analytics/frontend/tags/tagMetricsLogic.ts@@ -0,0 +1,198 @@+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'++import { HogQLQuery, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'+import { ChartDisplayType, PropertyFilterType, PropertyOperator } from '~/types'++import { llmTaggersLogic } from './llmTaggersLogic'+import type { tagMetricsLogicType } from './tagMetricsLogicType'+import { getIntervalFromDateRange, Tagger } from './types'++export interface TagStats {+ tagger_id: string+ runs_count: number+ tag_counts: Record<string, number>+}++export interface TagSummaryMetrics {+ total_runs: number+ top_tags: { tag: string; count: number }[]+ unique_tags_applied: number+}++export interface TagMetricsLogicProps {+ tabId?: string+}++export const tagMetricsLogic = kea<tagMetricsLogicType>([+ path(['products', 'llm_analytics', 'frontend', 'tags', 'tagMetricsLogic']),+ props({} as TagMetricsLogicProps),+ key((props) => props.tabId ?? 'default'),++ connect((props: TagMetricsLogicProps) => ({+ values: [llmTaggersLogic({ tabId: props.tabId }), ['taggers']],+ })),++ actions({+ setDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),+ }),++ reducers({+ dateFilter: [+ { dateFrom: '-7d' as string | null, dateTo: null as string | null },+ {+ setDates: (_, { dateFrom, dateTo }) => ({ dateFrom, dateTo }),+ },+ ],+ }),++ loaders(({ values }) => ({+ tagStats: [+ [] as { tag: string; count: number }[],+ {+ loadTagStats: async () => {+ const dateFrom = values.dateFilter.dateFrom || '-7d'+ const dateTo = values.dateFilter.dateTo || null++ const query: HogQLQuery = {+ kind: NodeKind.HogQLQuery,+ query: `+ SELECT+ tag,+ count() as cnt+ FROM events+ ARRAY JOIN JSONExtractArrayRaw(properties, '$ai_tags') as tag+ WHERE event = '$ai_tag' AND {filters}+ GROUP BY tag+ ORDER BY cnt DESC+ LIMIT 50+ `,+ filters: {+ dateRange: {+ date_from: dateFrom,+ date_to: dateTo,+ },+ },+ }++ try {+ const response = await api.query(query)+ return (response.results || []).map((row: [string, number]) => ({+ tag: row[0].replace(/^"|"$/g, ''),+ count: row[1],+ }))+ } catch (error) {+ console.error('Failed to load tag stats:', error)+ return []+ }+ },+ },+ ],+ totalRuns: [+ 0,+ {+ loadTotalRuns: async () => {+ const dateFrom = values.dateFilter.dateFrom || '-7d'+ const dateTo = values.dateFilter.dateTo || null++ const query: HogQLQuery = {+ kind: NodeKind.HogQLQuery,+ query: `+ SELECT count() as cnt+ FROM events+ WHERE event = '$ai_tag' AND {filters}+ `,+ filters: {+ dateRange: {+ date_from: dateFrom,+ date_to: dateTo,+ },+ },+ }++ try {+ const response = await api.query(query)+ return response.results?.[0]?.[0] ?? 0+ } catch {+ return 0+ }+ },+ },+ ],+ })),++ selectors({+ summaryMetrics: [+ (s) => [s.tagStats, s.totalRuns],+ (tagStats: { tag: string; count: number }[], totalRuns: number): TagSummaryMetrics => {+ return {+ total_runs: totalRuns,+ top_tags: tagStats.slice(0, 10),+ unique_tags_applied: tagStats.length,+ }+ },+ ],++ enabledTaggerCount: [+ (s) => [s.taggers],+ (taggers: Tagger[]): number => taggers.filter((t) => t.enabled && !t.deleted).length,+ ],++ chartQuery: [+ (s) => [s.tagStats, s.dateFilter],+ (+ tagStats: { tag: string; count: number }[],+ dateFilter: { dateFrom: string | null; dateTo: string | null }+ ): TrendsQuery | null => {+ if (tagStats.length === 0) {+ return null+ }++ const dateFrom = dateFilter.dateFrom || '-7d'+ const dateTo = dateFilter.dateTo || null+ const interval = getIntervalFromDateRange(dateFrom)++ const topTags = tagStats.slice(0, 10)++ return {+ kind: NodeKind.TrendsQuery,+ series: topTags.map((tagStat) => ({+ kind: NodeKind.EventsNode,+ event: '$ai_tag',+ custom_name: tagStat.tag,+ properties: [+ {+ key: '$ai_tags',+ value: tagStat.tag,+ operator: PropertyOperator.IContains,+ type: PropertyFilterType.Event,+ },+ ],+ })),+ trendsFilter: {+ display: ChartDisplayType.ActionsLineGraph,+ },+ dateRange: {+ date_from: dateFrom,+ date_to: dateTo,+ },+ interval,+ }+ },+ ],+ }),++ listeners(({ actions }) => ({+ setDates: () => {+ actions.loadTagStats()+ actions.loadTotalRuns()+ },+ })),++ afterMount(({ actions }) => {+ actions.loadTagStats()+ actions.loadTotalRuns()+ }),+])diff --git a/products/llm_analytics/frontend/tags/templates.ts b/products/llm_analytics/frontend/tags/templates.tsnew file mode 100644index 000000000000..5926c01c7549--- /dev/null+++ b/products/llm_analytics/frontend/tags/templates.ts@@ -0,0 +1,106 @@+import { TaggerConfig } from './types'++export interface TaggerTemplate {+ key: string+ name: string+ description: string+ icon: 'tag' | 'message-circle' | 'shield' | 'zap' | 'users'+ tagger_config: TaggerConfig+}++export const defaultTaggerTemplates: readonly TaggerTemplate[] = [+ {+ key: 'topic',+ name: 'Topic tags',+ description: 'Tag each generation with the topics or subject areas it covers',+ icon: 'tag',+ tagger_config: {+ prompt: 'Tag this AI generation with the topics or subject areas it covers. Select all that substantively apply.',+ tags: [+ { name: 'technical-support', description: 'Troubleshooting, debugging, or fixing technical issues' },+ { name: 'how-to', description: 'Step-by-step instructions or tutorials' },+ { name: 'general-knowledge', description: 'Factual questions or explanations about concepts' },+ { name: 'creative', description: 'Creative writing, brainstorming, or ideation' },+ { name: 'data-analysis', description: 'Working with data, charts, queries, or analytics' },+ { name: 'code-generation', description: 'Writing or modifying code' },+ ],+ min_tags: 0,+ max_tags: null,+ },+ },+ {+ key: 'intent',+ name: 'User intent',+ description: 'Tag what the user is trying to accomplish',+ icon: 'message-circle',+ tagger_config: {+ prompt: "Tag the primary intent behind the user's message in this generation. What is the user trying to accomplish?",+ tags: [+ { name: 'question', description: 'Asking a question or seeking information' },+ { name: 'task', description: 'Requesting the AI to perform a specific task' },+ { name: 'conversation', description: 'Casual conversation or chat' },+ { name: 'feedback', description: 'Providing feedback or corrections to the AI' },+ { name: 'follow-up', description: 'Following up on a previous response or asking for clarification' },+ ],+ min_tags: 0,+ max_tags: null,+ },+ },+ {+ key: 'safety',+ name: 'Safety flags',+ description: 'Flag generations that may contain sensitive or risky content',+ icon: 'shield',+ tagger_config: {+ prompt: 'Review this AI generation and flag any safety concerns. Only select tags that clearly apply — most generations should have no flags.',+ tags: [+ {+ name: 'pii',+ description: 'Contains personally identifiable information (names, emails, addresses, etc.)',+ },+ { name: 'medical-advice', description: 'Provides specific medical or health advice' },+ { name: 'financial-advice', description: 'Provides specific financial or investment advice' },+ { name: 'legal-advice', description: 'Provides specific legal advice' },+ { name: 'controversial', description: 'Discusses politically sensitive or controversial topics' },+ ],+ min_tags: 0,+ max_tags: null,+ },+ },+ {+ key: 'complexity',+ name: 'Response complexity',+ description: 'Tag the complexity level of each AI response',+ icon: 'zap',+ tagger_config: {+ prompt: "Assess the complexity of the AI's response. Select the single best-fitting complexity level.",+ tags: [+ { name: 'simple', description: 'Short, straightforward answer with no technical depth' },+ { name: 'moderate', description: 'Detailed explanation requiring some domain knowledge' },+ { name: 'complex', description: 'In-depth technical or analytical response with multiple parts' },+ { name: 'expert', description: 'Highly specialized response requiring deep expertise' },+ ],+ min_tags: 0,+ max_tags: null,+ },+ },+ {+ key: 'sentiment',+ name: 'User sentiment',+ description: 'Tag the emotional tone of the user in each conversation',+ icon: 'users',+ tagger_config: {+ prompt: "Analyze the emotional tone of the user's messages (not the AI's response) in this generation. What sentiment is the user expressing?",+ tags: [+ { name: 'satisfied', description: 'User seems happy or satisfied with the interaction' },+ { name: 'neutral', description: 'User shows no strong emotion' },+ { name: 'frustrated', description: 'User seems frustrated, confused, or dissatisfied' },+ { name: 'urgent', description: 'User seems to need help urgently or is under time pressure' },+ ],+ min_tags: 0,+ max_tags: null,+ },+ },+] as const++export type TaggerTemplateKey = (typeof defaultTaggerTemplates)[number]['key']diff --git a/products/llm_analytics/frontend/tags/types.ts b/products/llm_analytics/frontend/tags/types.tsnew file mode 100644index 000000000000..137fdc7dbda7--- /dev/null+++ b/products/llm_analytics/frontend/tags/types.ts@@ -0,0 +1,78 @@+import { dayjs } from 'lib/dayjs'++import { AnyPropertyFilter } from '~/types'++import { LLMProvider } from '../settings/llmProviderKeysLogic'++/**+ * Pick an hour-vs-day bucket interval for a chart series based on the+ * date-from string. Shared across tagger logics so list/detail/metrics+ * charts all bucket identically.+ */+export function getIntervalFromDateRange(dateFrom: string | null): 'hour' | 'day' {+ if (!dateFrom) {+ return 'day'+ }+ if (dateFrom === 'dStart' || dateFrom === '-0d' || dateFrom === '-0dStart') {+ return 'hour'+ }+ const match = dateFrom.match(/^-(\d+)([hdwmy])/i)+ if (match) {+ const value = parseInt(match[1])+ const unit = match[2].toLowerCase()+ const hoursMap: Record<string, number> = { h: 1, d: 24, w: 168, m: 720, y: 8760 }+ const hours = value * (hoursMap[unit] || 24)+ return hours <= 24 ? 'hour' : 'day'+ }+ const duration = dayjs.duration(dayjs().diff(dayjs(dateFrom)))+ return duration.asDays() <= 1 ? 'hour' : 'day'+}++export interface TagDefinition {+ name: string+ description?: string+}++export type TaggerType = 'llm' | 'hog'++export interface LLMTaggerConfig {+ prompt: string+ tags: TagDefinition[]+ min_tags: number+ max_tags: number | null+}++export interface HogTaggerConfig {+ source: string+ bytecode?: unknown[]+ tags: TagDefinition[]+}++export type TaggerConfig = LLMTaggerConfig | HogTaggerConfig++export interface ModelConfiguration {+ provider: LLMProvider+ model: string+ provider_key_id: string | null+ provider_key_name?: string | null+}++export interface TaggerConditionSet {+ id: string+ rollout_percentage: number+ properties: AnyPropertyFilter[]+}++export interface Tagger {+ id: string+ name: string+ description?: string+ enabled: boolean+ tagger_type: TaggerType+ tagger_config: TaggerConfig+ conditions: TaggerConditionSet[]+ model_configuration: ModelConfiguration | null+ created_at: string+ updated_at: string+ deleted?: boolean+}diff --git a/products/llm_analytics/manifest.tsx b/products/llm_analytics/manifest.tsxindex 1734e43712df..b8ec5f3ef940 100644--- a/products/llm_analytics/manifest.tsx+++ b/products/llm_analytics/manifest.tsx@@ -84,6 +84,23 @@ export const manifest: ProductManifest = {layout: 'app-container',iconType: 'llm_evaluations',},+ LLMAnalyticsTags: {+ import: () => import('./frontend/tags/LLMAnalyticsTagsScene'),+ projectBased: true,+ name: 'Tags',+ description: 'Add custom tags to your LLM generations automatically.',+ activityScope: 'LLMAnalytics',+ layout: 'app-container',+ iconType: 'llm_tags',+ },+ LLMAnalyticsTag: {+ import: () => import('./frontend/tags/LLMAnalyticsTag'),+ projectBased: true,+ name: 'LLM analytics tag',+ activityScope: 'LLMAnalytics',+ layout: 'app-container',+ iconType: 'llm_tags',+ },LLMAnalyticsPrompts: {import: () => import('./frontend/prompts/LLMPromptsScene'),projectBased: true,@@ -145,6 +162,8 @@ export const manifest: ProductManifest = {'/llm-analytics/playground': ['LLMAnalyticsPlayground', 'llmAnalyticsPlayground'],'/llm-analytics/datasets': ['LLMAnalyticsDatasets', 'llmAnalyticsDatasets'],'/llm-analytics/datasets/:id': ['LLMAnalyticsDataset', 'llmAnalyticsDataset'],+ '/llm-analytics/tags': ['LLMAnalyticsTags', 'llmAnalyticsTags'],+ '/llm-analytics/tags/:id': ['LLMAnalyticsTag', 'llmAnalyticsTag'],'/llm-analytics/evaluations': ['LLMAnalyticsEvaluations', 'llmAnalyticsEvaluations'],'/llm-analytics/evaluations/offline/experiments': ['LLMAnalyticsEvaluations', 'llmAnalyticsOfflineEvaluations'],'/llm-analytics/evaluations/offline/experiments/:experimentId': [@@ -224,6 +243,8 @@ export const manifest: ProductManifest = {llmAnalyticsDatasets: (): string => '/llm-analytics/datasets',llmAnalyticsDataset: (id: string, params?: { item?: string }): string =>combineUrl(`/llm-analytics/datasets/${id}`, params).url,+ llmAnalyticsTags: (): string => '/llm-analytics/tags',+ llmAnalyticsTag: (id: string): string => `/llm-analytics/tags/${id}`,llmAnalyticsEvaluations: (): string => '/llm-analytics/evaluations',llmAnalyticsOfflineEvaluations: (): string => '/llm-analytics/evaluations/offline/experiments',llmAnalyticsOfflineEvaluationExperiment: (experimentId: string, encode: boolean = true): string =>@@ -302,6 +323,18 @@ export const manifest: ProductManifest = {flag: FEATURE_FLAGS.LLM_ANALYTICS_EVALUATIONS,sceneKey: 'LLMAnalyticsEvaluations',},+ {+ path: 'Tags',+ intents: [ProductKey.LLM_ANALYTICS],+ category: ProductItemCategory.AI_ENGINEERING,+ type: 'llm_tags',+ iconType: 'llm_tags' as FileSystemIconType,+ iconColor: ['var(--color-product-llm-analytics-light)'] as FileSystemIconColor,+ href: urls.llmAnalyticsTags(),+ flag: FEATURE_FLAGS.LLM_ANALYTICS_TAGS,+ tags: ['alpha'],+ sceneKey: 'LLMAnalyticsTags',+ },{path: 'Prompts',intents: [ProductKey.LLM_PROMPTS],