Skip to content

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

feat(workflows): add a classify with ai workflow action (#114006)

Harley Alexander9c2dd2a81e98
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 97c26a850553..d815a8baa6c5 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -636,6 +636,7 @@ export const FEATURE_FLAGS = {
WIZARD_RUN_SYNC: 'wizard-run-sync', // owner: #team-growth multivariate=wizard-session,wizard-run — selects the Wizard sync widget
WIZARD_UI_ENABLED: 'wizard-ui-enabled', // owner: @fercgomes #team-growth — gates the /wizard/runs interface
WORKFLOW_AI_TASK_ACTION: 'workflow-ai-task-action', // owner: @mayteio #team-workflows
+ WORKFLOW_CLASSIFY_ACTION: 'workflow-classify-action', // owner: #team-workflows
WORKFLOW_RUN_SCOUT_ACTION: 'workflow-run-scout-action', // owner: #team-workflows
WORKFLOWS_AI_FIRST_NEW: 'workflows-ai-first-new', // owner: @mayteio #team-workflows
WORKFLOWS_DELAY_UNTIL_DATE: 'workflows-delay-until-date', // owner: @dmarchuk #team-workflows
diff --git a/nodejs/src/cdp/async-functions/classify.test.ts b/nodejs/src/cdp/async-functions/classify.test.ts
new file mode 100644
index 000000000000..d6c47b59e871
--- /dev/null
+++ b/nodejs/src/cdp/async-functions/classify.test.ts
@@ -0,0 +1,114 @@
+import jwt from 'jsonwebtoken'
+
+import { defaultConfig } from '~/common/config/config'
+import { parseJSON } from '~/common/utils/json-parse'
+import * as requestModule from '~/common/utils/request'
+
+import { createExampleInvocation } from '../_tests/fixtures'
+import { AsyncFunctionContext, getAsyncFunctionHandler } from '../async-function-registry'
+import { MinimalLogEntry } from '../types'
+import { createInvocationResult } from '../utils/invocation-utils'
+import './classify'
+
+describe('postHogClassify', () => {
+ const payload = {
+ question: 'Is this ticket spam?',
+ context: { subject: 'Buy SEO' },
+ categories: { spam: 'Cold outreach', support: 'A customer asking for help' },
+ }
+
+ const invokeLive = async (args: Record<string, unknown>): Promise<void> => {
+ const invocation = { ...createExampleInvocation(), hogFlow: { id: 'flow-1' } }
+ await getAsyncFunctionHandler('postHogClassify')!.execute(
+ [args],
+ {
+ invocation,
+ internalApiBaseUrl: defaultConfig.INTERNAL_API_BASE_URL,
+ consumeInlineAsyncBudget: () => {},
+ } as unknown as AsyncFunctionContext,
+ createInvocationResult<typeof invocation>(invocation)
+ )
+ }
+
+ let fetchSpy: jest.SpyInstance
+ beforeEach(() => {
+ fetchSpy = jest.spyOn(requestModule, 'internalFetch').mockResolvedValue({
+ status: 200,
+ text: () => Promise.resolve(JSON.stringify({ category: 'spam', confidence: 0.9 })),
+ } as requestModule.FetchResponse)
+ })
+ afterEach(() => jest.restoreAllMocks())
+
+ it('posts the inputs with a token scoped to the workflow', async () => {
+ await invokeLive(payload)
+
+ const [url, options] = fetchSpy.mock.calls[0]
+ expect(url).toMatch(/\/api\/projects\/1\/workflow_classifications\/$/)
+ expect(parseJSON(options.body)).toEqual(payload)
+ // Must exceed Django's 5 second gateway timeout so the worker receives its 503 instead of aborting first.
+ expect(options.timeoutMs).toBeGreaterThan(5000)
+ const token = options.headers.Authorization.replace('Bearer ', '')
+ // The literal pins the dev default shared with Django's WORKFLOW_CLASSIFY_JWT_SECRETS.
+ // nosemgrep: javascript.jsonwebtoken.security.jwt-hardcode.hardcoded-jwt-secret
+ const claims = jwt.verify(token, 'local-dev-workflow-classify-jwt', {
+ audience: 'posthog:workflows:classify',
+ algorithms: ['HS256'],
+ }) as jwt.JwtPayload
+ expect(claims).toMatchObject({ team_id: 1, hog_flow_id: 'flow-1' })
+ })
+
+ it.each([
+ ['a timeout, which may still be answering', new DOMException('The operation timed out.', 'TimeoutError'), 1],
+ ['a refused connection, which never reached Django', new Error('connect ECONNREFUSED 127.0.0.1:8000'), 3],
+ ])('retries after %s only when no answer can still arrive', async (_name, error, expectedCalls) => {
+ jest.useFakeTimers()
+ try {
+ fetchSpy.mockRejectedValue(error)
+ const invoked = invokeLive(payload)
+ await jest.runAllTimersAsync()
+ await invoked
+
+ expect(fetchSpy).toHaveBeenCalledTimes(expectedCalls)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it.each([
+ ['a blank question', { ...payload, question: ' ' }, /Enter a question/],
+ ['a long question', { ...payload, question: 'x'.repeat(2001) }, /2000 characters or fewer/],
+ [
+ 'a blank category name',
+ { ...payload, categories: { ' ': 'Spam', support: 'Help' } },
+ /Give every category a name/,
+ ],
+ [
+ 'a long category name',
+ { ...payload, categories: { ['x'.repeat(101)]: 'Spam', support: 'Help' } },
+ /category names to 100 characters or fewer/,
+ ],
+ ['one category', { ...payload, categories: { spam: 'Spam' } }, /at least two categories/],
+ [
+ 'seventeen categories',
+ { ...payload, categories: Object.fromEntries(Array.from({ length: 17 }, (_, i) => [`c${i}`, 'x'])) },
+ /at most 16 categories/,
+ ],
+ [
+ 'a long category description',
+ { ...payload, categories: { spam: 'x'.repeat(501), support: 'Help' } },
+ /500 characters or fewer/,
+ ],
+ ['an oversized context', { ...payload, context: { message: 'x'.repeat(65_536) } }, /65536 characters of JSON/],
+ [
+ 'a deeply nested context',
+ { ...payload, context: Array.from({ length: 255 }).reduce<unknown>((inner) => ({ a: inner }), 'x') },
+ /100 levels of nesting or fewer/,
+ ],
+ ])('rejects %s in both mocked and live calls', async (_name, args, expected) => {
+ expect(() => getAsyncFunctionHandler('postHogClassify')!.mock([args], [] as MinimalLogEntry[])).toThrow(
+ expected
+ )
+ await expect(invokeLive(args)).rejects.toThrow(expected)
+ expect(fetchSpy).not.toHaveBeenCalled()
+ })
+})
diff --git a/nodejs/src/cdp/async-functions/classify.ts b/nodejs/src/cdp/async-functions/classify.ts
new file mode 100644
index 000000000000..e6a085704286
--- /dev/null
+++ b/nodejs/src/cdp/async-functions/classify.ts
@@ -0,0 +1,132 @@
+import { DateTime } from 'luxon'
+
+import { HogFlow } from '~/cdp/schema/hogflow'
+import { defaultConfig } from '~/common/config/config'
+
+import { registerAsyncFunction } from '../async-function-registry'
+import { PosthogJwtAudience } from '../utils/jwt-utils'
+import { ScopedServiceJwt } from '../utils/scoped-service-jwt'
+import { callInternalApi } from './internal-api-call'
+
+let classifyJwt: ScopedServiceJwt | undefined
+const getClassifyJwt = (): ScopedServiceJwt =>
+ (classifyJwt ??= new ScopedServiceJwt(
+ PosthogJwtAudience.WORKFLOW_CLASSIFY,
+ defaultConfig.WORKFLOW_CLASSIFY_JWT_SECRET
+ ))
+
+// Django gives the gateway 5 seconds (TIMEOUT_SECONDS in workflow_classifications.py) and returns a 503
+// on a gateway timeout, which this worker retries. The worker budget must be longer than that plus Django's
+// own work. That 5 seconds limits each network operation, not the whole call, so Django can still overrun
+// this budget. The worker does not retry its own timeout, because the gateway may still be answering the
+// first request and a retry would pay for the same classification again.
+const CLASSIFY_TIMEOUT_MS = 7000
+
+// Match the limits of the classification endpoint (the request serializer in workflow_classifications.py),
+// so a mocked test run fails on the same inputs as a live run.
+const MAX_QUESTION_LENGTH = 2000
+const MAX_CATEGORIES = 16
+const MAX_CATEGORY_NAME_LENGTH = 100
+const MAX_DESCRIPTION_LENGTH = 500
+// Counted on the JSON text, like MAX_CONTEXT_CHARS in workflow_classifications.py.
+const MAX_CONTEXT_CHARS = 65_536
+const MAX_CONTEXT_DEPTH = 100
+
+const nestingExceeds = (value: unknown, limit: number): boolean => {
+ const pending: [unknown, number][] = [[value, 1]]
+ while (pending.length > 0) {
+ const [item, depth] = pending.pop()!
+ if (item === null || typeof item !== 'object') {
+ continue
+ }
+ if (depth > limit) {
+ return true
+ }
+ for (const child of Object.values(item)) {
+ pending.push([child, depth + 1])
+ }
+ }
+ return false
+}
+
+// The step test panel mocks async functions by default, so `mock` runs these checks too.
+const parseClassifyPayload = (args: any[]): Record<string, unknown> => {
+ const [payload] = args as [Record<string, unknown> | undefined]
+ if (typeof payload?.question !== 'string' || !payload.question.trim()) {
+ throw new Error('Enter a question')
+ }
+ if ([...payload.question.trim()].length > MAX_QUESTION_LENGTH) {
+ throw new Error(`Keep the question to ${MAX_QUESTION_LENGTH} characters or fewer`)
+ }
+ const categories = payload.categories
+ if (!categories || typeof categories !== 'object' || Object.keys(categories).length < 2) {
+ throw new Error('Enter at least two categories')
+ }
+ if (Object.keys(categories).length > MAX_CATEGORIES) {
+ throw new Error(`Enter at most ${MAX_CATEGORIES} categories`)
+ }
+ if (Object.keys(categories).some((name) => !name.trim())) {
+ throw new Error('Give every category a name')
+ }
+ if (Object.keys(categories).some((name) => [...name].length > MAX_CATEGORY_NAME_LENGTH)) {
+ throw new Error(`Keep category names to ${MAX_CATEGORY_NAME_LENGTH} characters or fewer`)
+ }
+ if (
+ Object.values(categories).some(
+ (description) => typeof description === 'string' && [...description.trim()].length > MAX_DESCRIPTION_LENGTH
+ )
+ ) {
+ throw new Error(`Keep each category description to ${MAX_DESCRIPTION_LENGTH} characters or fewer`)
+ }
+ if (nestingExceeds(payload.context, MAX_CONTEXT_DEPTH)) {
+ throw new Error(`Keep the context to ${MAX_CONTEXT_DEPTH} levels of nesting or fewer`)
+ }
+ if ([...(JSON.stringify(payload.context) ?? '')].length > MAX_CONTEXT_CHARS) {
+ throw new Error(`Keep the context to ${MAX_CONTEXT_CHARS} characters of JSON or fewer`)
+ }
+ return payload
+}
+
+registerAsyncFunction('postHogClassify', {
+ execute: async (args, context, result) => {
+ const payload = parseClassifyPayload(args)
+
+ const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow
+ if (!hogFlow?.id) {
+ throw new Error('Classify with AI only runs inside a workflow')
+ }
+
+ const jwt = getClassifyJwt()
+ if (!jwt.enabled) {
+ throw new Error(
+ 'Classify with AI is not configured. Set WORKFLOW_CLASSIFY_JWT_SECRET on the worker and Django to matching keys.'
+ )
+ }
+ await callInternalApi(context, result, {
+ jwt,
+ path: `/api/projects/${context.invocation.teamId}/workflow_classifications/`,
+ method: 'POST',
+ entityClaims: { hog_flow_id: hogFlow.id },
+ body: JSON.stringify(payload),
+ timeoutMs: CLASSIFY_TIMEOUT_MS,
+ retryOnTimeout: false,
+ })
+ },
+ mock: (args, logs) => {
+ const payload = parseClassifyPayload(args)
+ const categories = Object.keys(payload.categories as Record<string, unknown>)
+ logs.push({
+ level: 'info',
+ timestamp: DateTime.now(),
+ message: 'Classify with AI was mocked. The first category was returned without asking the model.',
+ })
+ return {
+ status: 200,
+ body: {
+ category: categories[0],
+ confidence: 1,
+ probabilities: Object.fromEntries(categories.map((name, i) => [name, i === 0 ? 1 : 0])),
+ },
+ }
+ },
+})
diff --git a/nodejs/src/cdp/async-functions/index.ts b/nodejs/src/cdp/async-functions/index.ts
index 97df8292265f..9511a04143b5 100644
--- a/nodejs/src/cdp/async-functions/index.ts
+++ b/nodejs/src/cdp/async-functions/index.ts
@@ -1,3 +1,4 @@
+import './classify'
import './conversations'
import './create-customer-task'
import './create-task'
diff --git a/nodejs/src/cdp/async-functions/internal-api-call.ts b/nodejs/src/cdp/async-functions/internal-api-call.ts
index eb6f99ac055c..26c90012f6e6 100644
--- a/nodejs/src/cdp/async-functions/internal-api-call.ts
+++ b/nodejs/src/cdp/async-functions/internal-api-call.ts
@@ -5,7 +5,7 @@ import { internalFetch } from '~/common/utils/request'
import { AsyncFunctionContext } from '../async-function-registry'
import { CyclotronJobInvocationHogFunction, CyclotronJobInvocationResult } from '../types'
-import { RETRIABLE_STATUS_CODES, fetchErrorDetail } from '../utils/cdp-fetch'
+import { RETRIABLE_STATUS_CODES, fetchErrorDetail, isTimeoutError } from '../utils/cdp-fetch'
import { ScopedServiceJwt } from '../utils/scoped-service-jwt'
export const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
@@ -43,9 +43,23 @@ export async function callInternalApi(
body?: string
extraHeaders?: Record<string, string>
retriableStatuses?: number[]
+ /** Per-attempt budget. Defaults to internalFetch's inter-service timeout. */
+ timeoutMs?: number
+ /** Retry an attempt that hit timeoutMs. Turn it off when the server may still be doing costly work for that attempt. */
+ retryOnTimeout?: boolean
}
): Promise<void> {
- const { jwt, path, method, entityClaims, body, extraHeaders, retriableStatuses = [] } = options
+ const {
+ jwt,
+ path,
+ method,
+ entityClaims,
+ body,
+ extraHeaders,
+ retriableStatuses = [],
+ timeoutMs,
+ retryOnTimeout = true,
+ } = options
const startedAt = performance.now()
// Counts once per handler call, not per retry attempt below: the retries are all one
@@ -81,6 +95,7 @@ export async function callInternalApi(
Authorization: `Bearer ${token}`,
},
...(body !== undefined ? { body } : {}),
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
})
status = fetchResponse.status
text = await fetchResponse.text()
@@ -107,7 +122,8 @@ export async function callInternalApi(
break
}
- const willRetry = attempt < MAX_ATTEMPTS
+ const willRetry =
+ attempt < MAX_ATTEMPTS && (retryOnTimeout || fetchError === null || !isTimeoutError(fetchError))
result.logs.push({
level: willRetry ? 'info' : 'error',
timestamp: DateTime.now(),
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index db7c1adcd63d..da93b3552029 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -227,6 +227,8 @@ export type CdpConfig = ClickhouseConfig & {
// TASKS_CREATE_JWT_SECRET — see products/workflows/backend/service_jwt.py. Same
// comma-separated rotation and fail-closed-when-empty semantics.
WORKFLOW_SCOUT_RUN_JWT_SECRET: string
+ // Scoped JWT keys signing the workflow engine's classify calls to Django. Its own key, for the same reason.
+ WORKFLOW_CLASSIFY_JWT_SECRET: string
CYCLOTRON_NODE_RESCHEDULE_FLOOR_SECONDS: number
CYCLOTRON_NODE_RESCHEDULE_WAKE_RATE_PER_SECOND: number
CYCLOTRON_NODE_RESCHEDULE_MIN_WINDOW_SECONDS: number
@@ -433,6 +435,8 @@ export function getDefaultCdpConfig(): CdpConfig {
TASKS_CREATE_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-tasks-create-jwt' : '',
// Dev/test default must match Django's (posthog/settings/data_stores.py).
WORKFLOW_SCOUT_RUN_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-workflow-scout-run-jwt' : '',
+ // Dev/test default must match Django's (posthog/settings/data_stores.py).
+ WORKFLOW_CLASSIFY_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-workflow-classify-jwt' : '',
CYCLOTRON_NODE_RESCHEDULE_FLOOR_SECONDS: 600,
CYCLOTRON_NODE_RESCHEDULE_WAKE_RATE_PER_SECOND: 200,
CYCLOTRON_NODE_RESCHEDULE_MIN_WINDOW_SECONDS: 300,
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts
index 1159071d1d26..2a0ceaa45541 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts
@@ -6,6 +6,7 @@ import { logger, serializeError } from '~/common/utils/logger'
import { Team } from '~/types'
import { HogFunctionFilters } from '../../types'
+import { isTimeoutError } from '../../utils/cdp-fetch'
export interface BlastRadiusResponse {
users_affected: number
@@ -62,16 +63,6 @@ export class AudienceFetchTimeoutError extends Error {
}
}
-// AbortSignal.timeout rejects with a TimeoutError. undici reports some aborts as an
-// AbortError, and can wrap either one in `cause`.
-const TIMEOUT_ERROR_NAMES = ['TimeoutError', 'AbortError']
-
-const isTimeoutError = (error: unknown): boolean => {
- const name = (error as { name?: string } | null)?.name
- const causeName = (error as { cause?: { name?: string } } | null)?.cause?.name
- return TIMEOUT_ERROR_NAMES.includes(name ?? '') || TIMEOUT_ERROR_NAMES.includes(causeName ?? '')
-}
-
/**
* Service for querying persons via Django internal API for batch HogFlow processing.
* Calls internal endpoints authenticated with INTERNAL_API_SECRET.
diff --git a/nodejs/src/cdp/templates/_destinations/posthog_workflows/posthog-classify.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_workflows/posthog-classify.template.ts
new file mode 100644
index 000000000000..830c1bf060ea
--- /dev/null
+++ b/nodejs/src/cdp/templates/_destinations/posthog_workflows/posthog-classify.template.ts
@@ -0,0 +1,72 @@
+import { HogFunctionTemplate } from '~/cdp/types'
+
+import { hogApiErrorMessageFn } from '../../hog-helpers'
+
+export const template: HogFunctionTemplate = {
+ free: true,
+ status: 'hidden',
+ type: 'destination',
+ id: 'template-posthog-classify',
+ name: 'Classify with AI',
+ description: 'Ask an AI model to pick one category for the context. Returns the category and its confidence.',
+ icon_url: '/static/posthog-icon.svg',
+ category: ['Custom'],
+ code_language: 'hog',
+ code: `
+${hogApiErrorMessageFn}
+
+let response := postHogClassify({
+ 'question': inputs.question,
+ 'context': inputs.context,
+ 'categories': inputs.categories,
+ 'model': inputs.model
+})
+
+if (response.status >= 400) {
+ throw Error(f'Could not classify ({response.status}): {apiErrorMessage(response)}')
+}
+
+return response.body
+`,
+ inputs_schema: [
+ {
+ key: 'model',
+ type: 'choice',
+ label: 'Model',
+ required: false,
+ default: 'jev',
+ choices: [
+ { label: 'Jev', value: 'jev' },
+ // Hidden until OpenAI's processing of workflow context is signed off. Enable it with the backend model.
+ // { label: 'GPT-6 Luna', value: 'gpt-6-luna' },
+ ],
+ description: 'The model that picks the category.',
+ },
+ {
+ key: 'question',
+ type: 'string',
+ label: 'Question',
+ required: true,
+ // Event data goes in the context, so it can never become part of the instructions.
+ templating: false,
+ description: 'What the model should decide, for example "Which team should handle this ticket?"',
+ },
+ {
+ key: 'context',
+ type: 'json',
+ label: 'Context',
+ required: true,
+ default: { subject: '{event.properties.subject}', message: '{event.properties.message}' },
+ description: 'The data the model reads to decide. Use event properties or variables from earlier steps.',
+ },
+ {
+ key: 'categories',
+ type: 'dictionary',
+ label: 'Categories',
+ required: true,
+ templating: false,
+ default: { spam: 'Cold outreach, marketing or automated mail', support: 'A customer asking for help' },
+ description: 'Each category and when it applies. Enter 2 to 16 categories.',
+ },
+ ],
+}
diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.ts
index cee24f97c760..dad822a2bea1 100644
--- a/nodejs/src/cdp/templates/index.ts
+++ b/nodejs/src/cdp/templates/index.ts
@@ -38,6 +38,7 @@ import { template as posthogUpdateAccountRelationshipsTemplate } from './_destin
import { template as posthogUpdateAccountTemplate } from './_destinations/posthog_customer_analytics/posthog-update-account.template'
import { template as posthogRunScoutTemplate } from './_destinations/posthog_signals/posthog-run-scout.template'
import { template as posthogCreateTaskTemplate } from './_destinations/posthog_tasks/posthog-create-task.template'
+import { template as posthogClassifyTemplate } from './_destinations/posthog_workflows/posthog-classify.template'
import { template as posthogSetHogflowVariableTemplate } from './_destinations/posthog_workflows/posthog-set-variable.template'
import { template as pushTemplate } from './_destinations/push/push.template'
import { template as redditAdsTemplate } from './_destinations/reddit_ads/reddit.template'
@@ -111,6 +112,7 @@ export const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [
posthogUpdateTicketTemplate,
posthogCreateTaskTemplate,
posthogRunScoutTemplate,
+ posthogClassifyTemplate,
posthogCreateAccountTemplate,
posthogCreateCustomerTaskTemplate,
posthogGetAccountTemplate,
diff --git a/nodejs/src/cdp/utils/cdp-fetch.ts b/nodejs/src/cdp/utils/cdp-fetch.ts
index 591af1a5386f..2464864cc8be 100644
--- a/nodejs/src/cdp/utils/cdp-fetch.ts
+++ b/nodejs/src/cdp/utils/cdp-fetch.ts
@@ -84,6 +84,16 @@ export function isConnectionLevelError(error: any): boolean {
// attempt to a host fails, and the per-address reasons (ECONNREFUSED, ETIMEDOUT, ...) live in
// `errors`. Without unpacking them, the customer-facing log reads "AggregateError: " with no way
// to tell a DNS failure from a refused connection.
+// AbortSignal.timeout rejects with a TimeoutError. undici reports some aborts as an
+// AbortError, and can wrap either one in `cause`.
+const TIMEOUT_ERROR_NAMES = ['TimeoutError', 'AbortError']
+
+export const isTimeoutError = (error: unknown): boolean => {
+ const name = (error as { name?: string } | null)?.name
+ const causeName = (error as { cause?: { name?: string } } | null)?.cause?.name
+ return TIMEOUT_ERROR_NAMES.includes(name ?? '') || TIMEOUT_ERROR_NAMES.includes(causeName ?? '')
+}
+
export function fetchErrorDetail(error: Error): string {
const causes =
error instanceof AggregateError && error.errors.length > 0
diff --git a/nodejs/src/cdp/utils/jwt-utils.ts b/nodejs/src/cdp/utils/jwt-utils.ts
index 3ed1dde60b2f..b916d9acd5e4 100644
--- a/nodejs/src/cdp/utils/jwt-utils.ts
+++ b/nodejs/src/cdp/utils/jwt-utils.ts
@@ -10,6 +10,7 @@ export enum PosthogJwtAudience {
CUSTOMER_TASKS_CREATE = 'posthog:customer-tasks:create',
TASKS_CREATE = 'posthog:tasks:create',
WORKFLOW_SCOUT_RUN = 'posthog:workflows:scout_run',
+ WORKFLOW_CLASSIFY = 'posthog:workflows:classify',
// Must match PosthogJwtAudience.CONVERSATIONS_TICKETS in posthog/jwt.py exactly.
CONVERSATIONS_TICKETS = 'posthog:conversations:tickets',
// Must match PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS in posthog/jwt.py exactly.
diff --git a/nodejs/tests/fixtures/hog-bytecode/f8625b8fbbf89b0563ab15d8ae427ec2800cb197cfeb4d08fb931b7871424802.json b/nodejs/tests/fixtures/hog-bytecode/f8625b8fbbf89b0563ab15d8ae427ec2800cb197cfeb4d08fb931b7871424802.json
new file mode 100644
index 000000000000..36ba442dd43b
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/f8625b8fbbf89b0563ab15d8ae427ec2800cb197cfeb4d08fb931b7871424802.json
@@ -0,0 +1 @@
+["_H",1,52,"apiErrorMessage",1,0,28,36,0,32,"body",45,32,"error",45,47,9,35,36,0,32,"body",45,32,"detail",45,47,6,35,36,0,32,"body",45,38,53,0,32,"question",32,"question",32,"inputs",1,2,32,"context",32,"context",32,"inputs",1,2,32,"categories",32,"categories",32,"inputs",1,2,32,"model",32,"model",32,"inputs",1,2,42,4,2,"postHogClassify",1,33,400,36,1,32,"status",45,14,40,22,32,"Could not classify (",36,1,32,"status",45,32,"): ",36,1,36,0,54,1,2,"concat",4,2,"Error",1,49,36,1,32,"body",45,38,35,35]
diff --git a/posthog/cdp/flag_gated_templates.py b/posthog/cdp/flag_gated_templates.py
index b8390cabd28a..4ce1665b85cd 100644
--- a/posthog/cdp/flag_gated_templates.py
+++ b/posthog/cdp/flag_gated_templates.py
@@ -15,6 +15,7 @@ logger = structlog.get_logger(__name__)
FLAG_GATED_TEMPLATE_IDS = {
"template-posthog-create-task": "workflow-ai-task-action",
"template-posthog-run-scout": "workflow-run-scout-action",
+ "template-posthog-classify": "workflow-classify-action",
}
@@ -28,7 +29,9 @@ def gated_template_enabled(flag_key: str, team: "Team") -> bool:
groups={"organization": str(team.organization_id), "project": str(team.id)},
group_properties={
"organization": {"id": str(team.organization_id)},
- "project": {"id": str(team.id)},
+ # A team id repeats across PostHog instances (self-hosted, local dev), so a flag that
+ # must reach one project matches on the uuid.
+ "project": {"id": str(team.id), "uuid": str(team.uuid)},
},
)
)
diff --git a/posthog/jwt.py b/posthog/jwt.py
index 2e8ad5e5716e..8f1b34a2dcff 100644
--- a/posthog/jwt.py
+++ b/posthog/jwt.py
@@ -35,6 +35,7 @@ class PosthogJwtAudience(Enum):
TASKS_CREATE = "posthog:tasks:create"
CUSTOMER_TASKS_CREATE = "posthog:customer-tasks:create"
WORKFLOW_SCOUT_RUN = "posthog:workflows:scout_run"
+ WORKFLOW_CLASSIFY = "posthog:workflows:classify"
CONVERSATIONS_TICKETS = "posthog:conversations:tickets"
CUSTOMER_ANALYTICS_ACCOUNTS = "posthog:customer_analytics:accounts"
SECURITY_HUB_RULES = "posthog:security_hub:rules"
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index 227270546629..cd4909aba5c8 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -614,6 +614,12 @@ WORKFLOW_SCOUT_RUN_JWT_SECRETS = get_list(
get_from_env("WORKFLOW_SCOUT_RUN_JWT_SECRET", "local-dev-workflow-scout-run-jwt" if DEBUG or TEST else "")
)
+# Signs the tokens a workflow's "Classify with AI" action calls back with. The dev/test value
+# must match the plugin server's minting default.
+WORKFLOW_CLASSIFY_JWT_SECRETS = get_list(
+ get_from_env("WORKFLOW_CLASSIFY_JWT_SECRET", "local-dev-workflow-classify-jwt" if DEBUG or TEST else "")
+)
+
# Verifies the scoped JWTs the CDP worker's conversations ticket actions send to the internal
# ticket route (the worker mints, Django verifies; products/conversations/backend/api/internal.py).
# Comma-separated, newest first. Empty outside dev/test, so the internal route rejects every
diff --git a/products/workflows/backend/facade/service_jwt.py b/products/workflows/backend/facade/service_jwt.py
index b544eafa4bf5..d5713d58e2be 100644
--- a/products/workflows/backend/facade/service_jwt.py
+++ b/products/workflows/backend/facade/service_jwt.py
@@ -1,8 +1,13 @@
"""The scoped service JWT purposes that the workflow callback endpoints verify.
-The plugin server mints these tokens for the "Create AI task" and "Run scout" workflow steps.
+The plugin server mints these tokens for the "Create AI task", "Run scout", and "Classify with AI"
+workflow steps.
"""
-from products.workflows.backend.service_jwt import TASKS_CREATE_PURPOSE, WORKFLOW_SCOUT_RUN_PURPOSE
+from products.workflows.backend.service_jwt import (
+ TASKS_CREATE_PURPOSE,
+ WORKFLOW_CLASSIFY_PURPOSE,
+ WORKFLOW_SCOUT_RUN_PURPOSE,
+)
-__all__ = ["TASKS_CREATE_PURPOSE", "WORKFLOW_SCOUT_RUN_PURPOSE"]
+__all__ = ["TASKS_CREATE_PURPOSE", "WORKFLOW_CLASSIFY_PURPOSE", "WORKFLOW_SCOUT_RUN_PURPOSE"]
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 40df8cbb4ab4..77db59b3f93f 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -291,6 +291,9 @@ from products.workflows.backend.presentation.views.message_assets import (
MessageAssetSerializer,
MessageAssetsRequestSerializer,
)
+from products.workflows.backend.presentation.views.workflow_classifications import (
+ WorkflowClassificationRequestSerializer,
+)
logger = structlog.get_logger(__name__)
@@ -493,6 +496,10 @@ _CREATE_TASK_TEMPLATE_ID = "template-posthog-create-task"
# workflow built through the API or MCP.
_RUN_SCOUT_TEMPLATE_ID = "template-posthog-run-scout"
+# The "Classify with AI" step. The classification endpoint refuses categories outside its limits with a
+# 400, which fails the step on every run, so a strict save applies the same limits.
+_CLASSIFY_TEMPLATE_ID = "template-posthog-classify"
+
_REPOSITORY_SHAPE = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+")
MIN_WORKFLOW_TASK_MAX_PARALLEL_TASKS = 1
@@ -1412,6 +1419,15 @@ class HogFlowActionSerializer(serializers.Serializer):
{"template_id": "Run scout is only available in the project's main environment."}
)
+ def _validate_classify_action(self, inputs: dict) -> None:
+ data = {key: (inputs.get(key) or {}).get("value") for key in ("question", "categories", "model")}
+ if data["model"] is None:
+ del data["model"]
+ # Reuses the endpoint's serializer so the save-time and runtime limits cannot drift apart.
+ serializer = WorkflowClassificationRequestSerializer(data=data, partial=True)
+ if not serializer.is_valid():
+ raise serializers.ValidationError({"inputs": serializer.errors})
+
def validate(self, data):
is_draft = self.context.get("is_draft")
# Drafts from the web builder stay lenient (incomplete graphs save fine); programmatic callers
@@ -1678,6 +1694,8 @@ class HogFlowActionSerializer(serializers.Serializer):
self._validate_create_task_action(data["config"]["inputs"])
if strict and template_id == _RUN_SCOUT_TEMPLATE_ID:
self._validate_run_scout_action()
+ if strict and template_id == _CLASSIFY_TEMPLATE_ID:
+ self._validate_classify_action(data["config"]["inputs"])
# Branch types fan out via 'branch' edges indexed into these arrays; a node stored without
# its array crashes the editor panel and assigns nothing at runtime. Presence is only
@@ -5593,8 +5611,7 @@ class HogFlowViewSet(
serializer = HogFlowInvocationSerializer(
data=request.data, context={**self.get_serializer_context(), "instance": hog_flow}
)
- if not serializer.is_valid():
- return Response(serializer.errors, status=400)
+ serializer.is_valid(raise_exception=True)
payload = dict(serializer.validated_data)
if payload.pop("use_draft", False):
diff --git a/products/workflows/backend/presentation/views/workflow_classifications.py b/products/workflows/backend/presentation/views/workflow_classifications.py
new file mode 100644
index 000000000000..793adf2ccd41
--- /dev/null
+++ b/products/workflows/backend/presentation/views/workflow_classifications.py
@@ -0,0 +1,255 @@
+import json
+import math
+from typing import Any, cast
+
+from django.db import models
+
+import structlog
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import serializers, status, viewsets
+from rest_framework.exceptions import AuthenticationFailed
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.auth import InternalAPIUser, ScopedServiceJWTAuthentication
+from posthog.cdp.flag_gated_templates import gated_template_enabled
+from posthog.models import Team
+
+from products.ml_inference.backend.facade.contracts import (
+ DEFAULT_DECISION_MODEL,
+ MAX_OPTIONS_PER_QUESTION,
+ ChoiceAnswer,
+ DecisionGatewayError,
+ DecisionGatewayUnreachableError,
+ DecisionQuestion,
+ DecisionRequest,
+ DecisionsDisabledError,
+)
+from products.ml_inference.backend.facade.enums import DecisionQuestionType
+from products.workflows.backend.facade.service_jwt import WORKFLOW_CLASSIFY_PURPOSE
+
+logger = structlog.get_logger(__name__)
+
+# The CDP worker waits inline for the answer, so a slow gateway must not hold its consumer loop for long.
+# Keep it below CLASSIFY_TIMEOUT_MS in nodejs/src/cdp/async-functions/classify.ts so the worker receives the 503.
+TIMEOUT_SECONDS = 5.0
+_QUESTION_ID = "category"
+MAX_CATEGORIES = MAX_OPTIONS_PER_QUESTION
+MAX_CATEGORY_NAME_LENGTH = 100
+# Same state limit as the ml_inference decide API, which asks the same model.
+# Keep it equal to MAX_CONTEXT_CHARS in nodejs/src/cdp/async-functions/classify.ts.
+MAX_CONTEXT_CHARS = 65_536
+# DecisionRequest validation fails on JSON nested about 255 levels deep, and its error text repeats the
+# whole context into logs and exception reporting. A small payload can reach that depth, so cap it first.
+# Keep it equal to MAX_CONTEXT_DEPTH in nodejs/src/cdp/async-functions/classify.ts.
+MAX_CONTEXT_DEPTH = 100
+
+
+# The models an author can pick for the step, keyed by the value the step stores. A new entry needs the AI gateway
+# to route the model on /v1/systemone, and the vendor's data processing must be covered for customer context.
+class ClassificationModel(models.TextChoices):
+ JEV = "jev", "Jev"
+ # Hidden until OpenAI's processing of workflow context is signed off. Enable it with the template choice.
+ # GPT_6_LUNA = "gpt-6-luna", "GPT-6 Luna"
+
+
+CLASSIFICATION_MODELS: dict[str, str] = {
+ ClassificationModel.JEV: DEFAULT_DECISION_MODEL,
+ # ClassificationModel.GPT_6_LUNA: "openai/gpt-6-luna",
+}
+
+
+def _nesting_exceeds(value: Any, limit: int) -> bool:
+ pending: list[tuple[Any, int]] = [(value, 1)]
+ while pending:
+ item, depth = pending.pop()
+ if isinstance(item, dict):
+ children = list(item.values())
+ elif isinstance(item, list):
+ children = item
+ else:
+ continue
+ if depth > limit:
+ return True
+ pending.extend((child, depth + 1) for child in children)
+ return False
+
+
+class WorkflowClassifyJWTAuthentication(ScopedServiceJWTAuthentication):
+ purpose = WORKFLOW_CLASSIFY_PURPOSE
+
+ def _authenticate_claims(self, request: Request, claims: dict[str, Any]) -> tuple[Any, dict[str, Any]]:
+ if not claims.get("hog_flow_id"):
+ raise AuthenticationFailed("Service token is missing its workflow claim.")
+ return super()._authenticate_claims(request, claims)
+
+
+class WorkflowClassificationRequestSerializer(serializers.Serializer):
+ question = serializers.CharField(
+ max_length=2000,
+ help_text="What to decide about the context, for example 'Which team should handle this ticket?'",
+ )
+ context = serializers.JSONField( # type: ignore[assignment] # The field name shadows DRF Field.context.
+ help_text=f"The data to classify, such as ticket fields or event properties. The model reads it as data, never as instructions. At most {MAX_CONTEXT_CHARS} characters of JSON and {MAX_CONTEXT_DEPTH} levels of nesting."
+ )
+ model = serializers.ChoiceField(
+ choices=ClassificationModel.choices,
+ default=ClassificationModel.JEV,
+ allow_null=True,
+ help_text="The model that picks the category. Defaults to Jev.",
+ )
+ categories = serializers.DictField(
+ child=serializers.CharField(max_length=500, allow_blank=True),
+ help_text=f"Category names of at most {MAX_CATEGORY_NAME_LENGTH} characters mapped to a short description of when each applies. 2 to {MAX_CATEGORIES} categories.",
+ )
+
+ def validate_context(self, value: Any) -> Any:
+ if _nesting_exceeds(value, MAX_CONTEXT_DEPTH):
+ raise serializers.ValidationError(f"Keep the context to {MAX_CONTEXT_DEPTH} levels of nesting or fewer.")
+ if len(json.dumps(value, ensure_ascii=False, separators=(",", ":"))) > MAX_CONTEXT_CHARS:
+ raise serializers.ValidationError(f"Keep the context to {MAX_CONTEXT_CHARS} characters of JSON or fewer.")
+ return value
+
+ def validate_categories(self, value: dict[str, str]) -> dict[str, str]:
+ if not 2 <= len(value) <= MAX_CATEGORIES:
+ raise serializers.ValidationError(f"Enter between 2 and {MAX_CATEGORIES} categories.")
+ if any(not name.strip() for name in value):
+ raise serializers.ValidationError("Give every category a name.")
+ if any(len(name) > MAX_CATEGORY_NAME_LENGTH for name in value):
+ raise serializers.ValidationError(f"Keep category names to {MAX_CATEGORY_NAME_LENGTH} characters or fewer.")
+ return value
+
+
+class WorkflowClassificationResponseSerializer(serializers.Serializer):
+ category = serializers.CharField(help_text="The category the model chose.")
+ confidence = serializers.FloatField(help_text="The model's probability for the chosen category, from 0 to 1.")
+ probabilities = serializers.DictField(
+ child=serializers.FloatField(), help_text="The probability of every category, from 0 to 1."
+ )
+
+
+class WorkflowClassificationErrorSerializer(serializers.Serializer):
+ detail = serializers.CharField(help_text="Why the context was not classified.")
+
+
+class WorkflowClassificationViewSet(viewsets.GenericViewSet):
+ """Classify a workflow's context with an AI model for the "Classify with AI" action. Authenticated by a
+ scoped service JWT minted by the plugin server, never by a user credential."""
+
+ authentication_classes = [WorkflowClassifyJWTAuthentication]
+ permission_classes = [IsAuthenticated]
+ serializer_class = WorkflowClassificationRequestSerializer
+
+ @extend_schema(
+ request=WorkflowClassificationRequestSerializer,
+ responses={
+ 200: WorkflowClassificationResponseSerializer,
+ 403: OpenApiResponse(
+ response=WorkflowClassificationErrorSerializer,
+ description="The feature is disabled or the organization has not approved AI data processing",
+ ),
+ 501: OpenApiResponse(
+ response=WorkflowClassificationErrorSerializer,
+ description="This deployment has no AI gateway configured",
+ ),
+ 422: OpenApiResponse(
+ response=WorkflowClassificationErrorSerializer,
+ description="The model rejected the request or returned an unusable answer",
+ ),
+ 503: OpenApiResponse(
+ response=WorkflowClassificationErrorSerializer,
+ description="The model is busy or unreachable. Retry later",
+ ),
+ },
+ summary="Classify workflow context with an AI model",
+ )
+ def create(self, request: Request, **kwargs: Any) -> Response:
+ user = cast(InternalAPIUser, request.user)
+ team = Team.objects.select_related("organization").get(id=cast(int, user.current_team_id))
+
+ if not gated_template_enabled("workflow-classify-action", team):
+ return _error("Classify with AI is not enabled for this project.", status.HTTP_403_FORBIDDEN)
+
+ serializer = WorkflowClassificationRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+
+ if not team.organization.is_ai_data_processing_approved:
+ return _error(
+ "Your organization has not approved AI data processing. Approve it in organization settings.",
+ status.HTTP_403_FORBIDDEN,
+ )
+
+ # The facade pulls the LLM SDKs through the gateway client, which must stay out of Django startup.
+ from posthog.llm.gateway_client import GatewayNotConfiguredError # noqa: PLC0415
+
+ from products.ml_inference.backend.facade import api as decisions_api # noqa: PLC0415
+
+ categories: dict[str, str] = data["categories"]
+ try:
+ result = decisions_api.decide_when_available(
+ DecisionRequest(
+ team_id=team.id,
+ state=data["context"],
+ questions={
+ _QUESTION_ID: DecisionQuestion(
+ type=DecisionQuestionType.CHOICE, instructions=data["question"], criteria=categories
+ )
+ },
+ model=CLASSIFICATION_MODELS[data["model"] or ClassificationModel.JEV],
+ ai_product="workflows",
+ properties={"hog_flow_id": str(cast(dict[str, Any], request.auth)["hog_flow_id"])},
+ # The context carries person and event data, which must stay out of the internal AI observability project.
+ privacy_mode=True,
+ ),
+ timeout_seconds=TIMEOUT_SECONDS,
+ )
+ except (DecisionsDisabledError, GatewayNotConfiguredError):
+ return _error("The model is not available on this PostHog deployment.", status.HTTP_501_NOT_IMPLEMENTED)
+ except DecisionGatewayUnreachableError:
+ logger.warning("workflow_classification_unreachable", team_id=team.id)
+ return _error("The model is busy or unreachable. Retry later.", status.HTTP_503_SERVICE_UNAVAILABLE)
+ except DecisionGatewayError as error:
+ # Only the status is logged: the gateway's body can echo the context.
+ logger.warning("workflow_classification_failed", team_id=team.id, status_code=error.status_code)
+ if error.status_code == 429 or error.status_code >= 500:
+ return _error("The model is busy or unreachable. Retry later.", status.HTTP_503_SERVICE_UNAVAILABLE)
+ if error.status_code == 200:
+ return _error(
+ "The model returned an answer the step cannot read.", status.HTTP_422_UNPROCESSABLE_ENTITY
+ )
+ return _error(
+ f"The model refused the request (gateway status {error.status_code}).",
+ status.HTTP_422_UNPROCESSABLE_ENTITY,
+ )
+
+ answer = result.answers.get(_QUESTION_ID)
+ if not _is_usable(answer, categories):
+ logger.warning("workflow_classification_unusable_answer", team_id=team.id)
+ return _error("The model returned an answer the step cannot read.", status.HTTP_422_UNPROCESSABLE_ENTITY)
+ answer = cast(ChoiceAnswer, answer)
+ return Response(
+ WorkflowClassificationResponseSerializer(
+ {
+ "category": answer.choice,
+ "confidence": answer.confidence,
+ "probabilities": {name: answer.probabilities[name] for name in categories},
+ }
+ ).data
+ )
+
+
+def _is_usable(answer: object, categories: dict[str, str]) -> bool:
+ """The facade checks the answer's shape but not its values. A choice outside the categories
+ would send the person down no branch."""
+ if not isinstance(answer, ChoiceAnswer) or answer.choice not in categories:
+ return False
+ if not all(name in answer.probabilities for name in categories):
+ return False
+ values = [answer.confidence, *(answer.probabilities[name] for name in categories)]
+ return all(math.isfinite(value) and 0 <= value <= 1 for value in values)
+
+
+def _error(detail: str, http_status: int) -> Response:
+ return Response(WorkflowClassificationErrorSerializer({"detail": detail}).data, status=http_status)
diff --git a/products/workflows/backend/routes.py b/products/workflows/backend/routes.py
index 02fbfce3ac61..efffd88aca4c 100644
--- a/products/workflows/backend/routes.py
+++ b/products/workflows/backend/routes.py
@@ -9,6 +9,7 @@ from products.workflows.backend.presentation.views import (
email_drafts,
hog_flow,
hog_flow_template,
+ workflow_classifications,
workflow_scout_runs,
workflow_tasks,
)
@@ -40,6 +41,12 @@ def register_routes(routers: RouterRegistry) -> None:
"project_workflow_email_drafts",
["team_id"],
)
+ routers.projects.register(
+ r"workflow_classifications",
+ workflow_classifications.WorkflowClassificationViewSet,
+ "project_workflow_classifications",
+ ["team_id"],
+ )
routers.projects.register(
r"hog_flow_templates",
hog_flow_template.HogFlowTemplateViewSet,
diff --git a/products/workflows/backend/service_jwt.py b/products/workflows/backend/service_jwt.py
index 5c3cced4a267..8bcbbef93d97 100644
--- a/products/workflows/backend/service_jwt.py
+++ b/products/workflows/backend/service_jwt.py
@@ -16,3 +16,9 @@ WORKFLOW_SCOUT_RUN_PURPOSE = ScopedServiceJwtPurpose(
audience=PosthogJwtAudience.WORKFLOW_SCOUT_RUN,
settings_name="WORKFLOW_SCOUT_RUN_JWT_SECRETS",
)
+
+# Its own key for the same narrowest-scope reason as WORKFLOW_SCOUT_RUN_PURPOSE.
+WORKFLOW_CLASSIFY_PURPOSE = ScopedServiceJwtPurpose(
+ audience=PosthogJwtAudience.WORKFLOW_CLASSIFY,
+ settings_name="WORKFLOW_CLASSIFY_JWT_SECRETS",
+)
diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.py
index 721208b455eb..ab145bcc5122 100644
--- a/products/workflows/backend/tests/api/test_hog_flow.py
+++ b/products/workflows/backend/tests/api/test_hog_flow.py
@@ -6510,6 +6510,23 @@ class TestFlagGatedTemplates(APIBaseTest):
if expected_status == status.HTTP_400_BAD_REQUEST:
assert "Template not found" in response.json()["detail"]
+ def test_invocation_rejects_an_inline_gated_step_when_the_flag_is_off(self):
+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=True):
+ created = self._post_flow_with_create_task_action_as_web()
+ assert created.status_code == status.HTTP_201_CREATED
+ flow = created.json()
+
+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=False):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/new/invocations/",
+ {"configuration": {"name": flow["name"], "actions": flow["actions"], "edges": flow["edges"]}},
+ format="json",
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert "Template not found" in str(response.json())
+
def test_flag_eval_failure_hides_the_gated_template(self):
# A flag-service blip must hide the pre-release step, not expose it.
with patch(
@@ -6875,3 +6892,65 @@ class TestRunScoutActionValidation(APIBaseTest):
response = self._post_flow(self.team)
assert response.status_code == status.HTTP_201_CREATED, response.json()
+
+
+class TestClassifyActionValidation(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ template = deepcopy(webhook_template)
+ template["id"] = "template-posthog-classify"
+ template["name"] = "Classify with AI"
+ template["inputs_schema"] = [
+ {"key": "question", "type": "string", "label": "Question", "secret": False, "required": True},
+ {"key": "categories", "type": "dictionary", "label": "Categories", "secret": False, "required": True},
+ {"key": "model", "type": "choice", "label": "Model", "secret": False, "required": False},
+ ]
+ sync_template_to_db(template)
+
+ def _post_flow(self, categories: dict, question: str = "Which team?", model: str | None = None):
+ trigger_action = {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {
+ "type": "event",
+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},
+ },
+ }
+ inputs: dict[str, Any] = {"question": {"value": question}, "categories": {"value": categories}}
+ if model is not None:
+ inputs["model"] = {"value": model}
+ action = {
+ "id": "action_1",
+ "name": "action_1",
+ "type": "function",
+ "config": {"template_id": "template-posthog-classify", "inputs": inputs},
+ }
+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=True):
+ return self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows",
+ {"name": "Test Flow", "actions": [trigger_action, action], "edges": []},
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+
+ @parameterized.expand(
+ [
+ ("sixteen_categories", {f"c{i}": "x" for i in range(16)}, status.HTTP_201_CREATED),
+ ("seventeen_categories", {f"c{i}": "x" for i in range(17)}, status.HTTP_400_BAD_REQUEST),
+ ("long_description", {"spam": "x" * 501, "support": "help"}, status.HTTP_400_BAD_REQUEST),
+ ("long_question", {"spam": "x", "support": "help"}, status.HTTP_400_BAD_REQUEST, "x" * 2001),
+ (
+ "unlisted_model",
+ {"spam": "x", "support": "help"},
+ status.HTTP_400_BAD_REQUEST,
+ "Which team?",
+ "gpt-unlisted",
+ ),
+ ]
+ )
+ def test_applies_the_classification_endpoint_limits_at_save(
+ self, _name, categories, expected, question="Which team?", model=None
+ ):
+ response = self._post_flow(categories, question, model)
+
+ assert response.status_code == expected, response.json()
diff --git a/products/workflows/backend/tests/api/test_workflow_classifications_api.py b/products/workflows/backend/tests/api/test_workflow_classifications_api.py
new file mode 100644
index 000000000000..33a60f660c2f
--- /dev/null
+++ b/products/workflows/backend/tests/api/test_workflow_classifications_api.py
@@ -0,0 +1,192 @@
+from datetime import timedelta
+from functools import reduce
+from typing import Any, cast
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.test import override_settings
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.jwt import PosthogJwtAudience, encode_jwt
+from posthog.llm.gateway_client import GatewayNotConfiguredError
+
+from products.ml_inference.backend.facade.contracts import (
+ DEFAULT_DECISION_MODEL,
+ ChoiceAnswer,
+ DecisionGatewayError,
+ DecisionGatewayUnreachableError,
+ DecisionQuestion,
+ DecisionResult,
+ DecisionsDisabledError,
+ NoulAnswer,
+)
+from products.ml_inference.backend.facade.enums import DecisionQuestionType
+
+SECRET = "test-workflow-classify-jwt"
+_DECIDE = "products.ml_inference.backend.facade.api.decide_when_available"
+CATEGORIES = {"spam": "Cold outreach or marketing", "support": "A customer asking for help"}
+
+
+def _token(team_id: int, audience: PosthogJwtAudience = PosthogJwtAudience.WORKFLOW_CLASSIFY) -> str:
+ return encode_jwt(
+ {"team_id": team_id, "hog_flow_id": str(uuid4())}, timedelta(minutes=5), audience, signing_key=SECRET
+ )
+
+
+def _result(answer: Any) -> DecisionResult:
+ return DecisionResult(model="jevk5", answers={"category": answer}, input_tokens=20)
+
+
+@override_settings(WORKFLOW_CLASSIFY_JWT_SECRETS=[SECRET], TASKS_CREATE_JWT_SECRETS=[SECRET])
+class TestWorkflowClassificationsAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.client.logout()
+ self.url = f"/api/projects/{self.team.id}/workflow_classifications/"
+ flag_patch = patch("posthoganalytics.feature_enabled", return_value=True)
+ self.feature_flag = flag_patch.start()
+ self.addCleanup(flag_patch.stop)
+
+ def _post(self, body: dict | None = None, token: str | None = None) -> Any:
+ return self.client.post(
+ self.url,
+ {
+ "question": "Is this ticket spam?",
+ "context": {"subject": "Buy SEO"},
+ "categories": CATEGORIES,
+ **(body or {}),
+ },
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {token or _token(self.team.id)}",
+ )
+
+ @parameterized.expand(
+ [
+ ("disabled", False, None),
+ ("unavailable", None, RuntimeError("Flag evaluation is unavailable")),
+ ]
+ )
+ def test_refuses_classification_without_the_feature_flag(
+ self, _name: str, enabled: bool | None, error: Exception | None
+ ) -> None:
+ self.feature_flag.return_value = enabled
+ self.feature_flag.side_effect = error
+ with patch(_DECIDE) as decide:
+ response = self._post()
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ decide.assert_not_called()
+
+ # The step sends a null model when the author never opened the picker.
+ @parameterized.expand(
+ [
+ ("model_omitted", {}, DEFAULT_DECISION_MODEL),
+ ("model_null", {"model": None}, DEFAULT_DECISION_MODEL),
+ ("jev", {"model": "jev"}, DEFAULT_DECISION_MODEL),
+ ]
+ )
+ def test_returns_the_chosen_category(self, _name: str, body: dict, expected_model: str) -> None:
+ answer = ChoiceAnswer(choice="spam", confidence=0.9, probabilities={"spam": 0.9, "support": 0.1})
+ with patch(_DECIDE, return_value=_result(answer)) as decide:
+ response = self._post(body)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {
+ "category": "spam",
+ "confidence": 0.9,
+ "probabilities": {"spam": 0.9, "support": 0.1},
+ }
+ sent = decide.call_args.args[0]
+ assert sent.team_id == self.team.id
+ assert sent.privacy_mode is True
+ assert sent.model == expected_model
+ # User text stays in the state, never in the instructions.
+ assert sent.state == {"subject": "Buy SEO"}
+ assert sent.questions == {
+ "category": DecisionQuestion(
+ type=DecisionQuestionType.CHOICE, instructions="Is this ticket spam?", criteria=CATEGORIES
+ )
+ }
+
+ @parameterized.expand(
+ [
+ ("unavailable_in_region", DecisionsDisabledError(1), status.HTTP_501_NOT_IMPLEMENTED),
+ ("not_configured", GatewayNotConfiguredError("no gateway"), status.HTTP_501_NOT_IMPLEMENTED),
+ ("rate_limited", DecisionGatewayError(429, "slow down"), status.HTTP_503_SERVICE_UNAVAILABLE),
+ ("unreachable", DecisionGatewayUnreachableError("timeout"), status.HTTP_503_SERVICE_UNAVAILABLE),
+ ("gateway_error", DecisionGatewayError(503, "down"), status.HTTP_503_SERVICE_UNAVAILABLE),
+ ("malformed_answer", DecisionGatewayError(200, "unreadable"), status.HTTP_422_UNPROCESSABLE_ENTITY),
+ ("bad_request", DecisionGatewayError(400, "bad"), status.HTTP_422_UNPROCESSABLE_ENTITY),
+ ]
+ )
+ def test_a_model_failure_maps_onto_a_status_the_step_can_retry_or_fail_on(
+ self, _name: str, error: Exception, expected: int
+ ) -> None:
+ with patch(_DECIDE, side_effect=error):
+ response = self._post()
+
+ assert response.status_code == expected
+
+ @parameterized.expand(
+ [
+ (
+ "unknown_category",
+ ChoiceAnswer(choice="sales", confidence=0.9, probabilities={"spam": 0.1, "support": 0.0}),
+ ),
+ ("missing_probability", ChoiceAnswer(choice="spam", confidence=0.9, probabilities={"spam": 0.9})),
+ ("out_of_range", ChoiceAnswer(choice="spam", confidence=1.5, probabilities={"spam": 0.9, "support": 0.1})),
+ ("wrong_answer_type", NoulAnswer(probability=0.9)),
+ ]
+ )
+ def test_fails_the_step_on_an_answer_it_cannot_branch_on(self, _name: str, answer: Any) -> None:
+ with patch(_DECIDE, return_value=_result(answer)):
+ response = self._post()
+
+ assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
+
+ def test_refuses_an_organization_without_ai_data_processing_approval(self) -> None:
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save()
+ with patch(_DECIDE) as decide:
+ response = self._post()
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ decide.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("one_category", {"categories": {"spam": "Spam"}}),
+ ("blank_category_name", {"categories": {" ": "Spam", "support": "Help"}}),
+ ("long_category_name", {"categories": {"x" * 101: "Spam", "support": "Help"}}),
+ ("too_many_categories", {"categories": {f"c{i}": "x" for i in range(17)}}),
+ ("oversized_context", {"context": {"message": "x" * 65_536}}),
+ ("unlisted_model", {"model": "openai/gpt-6-luna"}),
+ ("hidden_model", {"model": "gpt-6-luna"}),
+ ("deeply_nested_context", {"context": reduce(lambda inner, _: {"a": inner}, range(255), cast(Any, "x"))}),
+ ]
+ )
+ def test_rejects_inputs_the_model_cannot_answer(self, _name: str, body: dict) -> None:
+ with patch(_DECIDE) as decide:
+ response = self._post(body)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ decide.assert_not_called()
+
+ def test_rejects_a_token_minted_for_another_workflow_action(self) -> None:
+ response = self._post(token=_token(self.team.id, audience=PosthogJwtAudience.TASKS_CREATE))
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+
+ def test_rejects_a_token_without_a_workflow_claim(self) -> None:
+ token = encode_jwt(
+ {"team_id": self.team.id}, timedelta(minutes=5), PosthogJwtAudience.WORKFLOW_CLASSIFY, signing_key=SECRET
+ )
+ with patch(_DECIDE) as decide:
+ response = self._post(token=token)
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ decide.assert_not_called()
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx
index f9234b50930d..e39a2857de38 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx
@@ -93,6 +93,17 @@ const RUN_SCOUT_ACTION_NODE: CreateActionType = {
output_variable: { key: 'scout_run', result_path: null, label: 'Scout run' },
}
+const CLASSIFY_ACTION_NODE: CreateActionType = {
+ type: 'function',
+ name: 'Classify with AI',
+ description: 'Ask an AI model to pick one category for the context. Branch on the result with a condition step.',
+ config: { template_id: 'template-posthog-classify', inputs: {} },
+ output_variable: [
+ { key: 'category', result_path: 'category', label: 'Category' },
+ { key: 'confidence', result_path: 'confidence', label: 'Confidence' },
+ ],
+}
+
export const DELAY_NODES_TO_SHOW: CreateActionType[] = [
{
type: 'delay',
@@ -396,6 +407,13 @@ export function HogFlowEditorPanelBuild({
onActionSelect={onActionSelect}
/>
)}
+ {featureFlags[FEATURE_FLAGS.WORKFLOW_CLASSIFY_ACTION] && (
+ <HogFlowEditorToolbarNode
+ key="classify"
+ action={CLASSIFY_ACTION_NODE}
+ onActionSelect={onActionSelect}
+ />
+ )}
<HogFunctionTemplatesChooser onActionSelect={onActionSelect} />
</HogFlowEditorToolbarSection>
diff --git a/tach.toml b/tach.toml
index b101880f8bdd..9cbd7d41f133 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1083,6 +1083,9 @@ depends_on = [
# Facade-only: the AI task action's endpoint creates tasks through
# products.tasks.backend.facade.workflow_tasks.
"products.tasks", "products.access_control",
+ # Facade-only: the Classify with AI action's endpoint asks the model through
+ # products.ml_inference.backend.facade.api.
+ "products.ml_inference",
]
layer = "modules"