: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(hogql): add preview Jev sql decisions (#108610)
Jovan Sakovic506366b9da9f
diff --git a/posthog/hogql/database/test/test_warehouse_usage.py b/posthog/hogql/database/test/test_warehouse_usage.pyindex 8205696a72fa..696ce294c5bd 100644--- a/posthog/hogql/database/test/test_warehouse_usage.py+++ b/posthog/hogql/database/test/test_warehouse_usage.py@@ -1,4 +1,5 @@from posthog.test.base import BaseTest+from unittest.mock import patchfrom django.contrib.auth.models import AnonymousUser@@ -8,7 +9,7 @@ from posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.database.warehouse_usage import WarehouseSourceUsage, extract_warehouse_sourcesfrom posthog.hogql.parser import parse_select-from posthog.hogql.query import HogQLQueryExecutor+from posthog.hogql.query import HogQLQueryExecutor, execute_hogql_queryfrom posthog.hogql.resolver import resolve_typesfrom posthog.hogql.visitor import clone_expr@@ -105,6 +106,21 @@ class TestWarehouseUsage(BaseTest):assert sources == []+ def test_prompt_jev_source_reads_are_attributed(self):+ source = self._create_stripe_table()++ with (+ patch("posthog.hogql.transforms.prompt_jev.feature_enabled_or_false", return_value=True),+ patch("posthog.hogql.query.sync_execute", return_value=([], [("label", "Nullable(String)")])),+ ):+ response = execute_hogql_query(+ "SELECT label FROM (SELECT __preview_promptJev(id, 'Refund?') AS label FROM stripe_table_1 LIMIT 10)",+ self.team,+ user=self.user,+ )++ assert [s.id for s in response.used_data_warehouse_sources or []] == [str(source.id)]+def test_deduplicates_by_source(self):source = self._create_stripe_table()diff --git a/posthog/hogql/functions/posthog.py b/posthog/hogql/functions/posthog.pyindex c0cac74507ed..ac1e713a99fb 100644--- a/posthog/hogql/functions/posthog.py+++ b/posthog/hogql/functions/posthog.py@@ -26,6 +26,7 @@ HOGQL_POSTHOG_FUNCTIONS: dict[str, HogQLFunctionMeta] = {signatures=[((StringType(),), ArrayType(item_type=IntegerType()))],),"embedText": HogQLFunctionMeta("embedText", 1, 2),+ "__preview_promptJev": HogQLFunctionMeta("__preview_promptJev", 2, 4, case_sensitive=False),# posthog/models/channel_type/sql.py and posthog/hogql/database/schema/channel_type.py"lookupDomainType": HogQLFunctionMeta("lookupDomainType", 1, 1),"lookupPaidSourceType": HogQLFunctionMeta("lookupPaidSourceType", 1, 1),diff --git a/posthog/hogql/functions/prompt_jev.py b/posthog/hogql/functions/prompt_jev.pynew file mode 100644index 000000000000..2f3eea244c46--- /dev/null+++ b/posthog/hogql/functions/prompt_jev.py@@ -0,0 +1,88 @@+from posthog.hogql import ast+from posthog.hogql.errors import QueryError+from posthog.hogql.visitor import TraversingVisitor++from posthog.dataclasses import frozen+from posthog.llm.system_one import ChoiceQuestion, NoulQuestion, Question++MAX_CHOICES = 16+CHOICE_TYPE = "Tuple(choice Nullable(String), probabilities Array(Tuple(value String, probability Float64)), confidence Nullable(Float64))"+++class PromptJevFinder(TraversingVisitor):+ def __init__(self) -> None:+ self.calls: list[ast.Call] = []++ def visit_call(self, node: ast.Call) -> None:+ if node.name.lower() == "__preview_promptjev":+ self.calls.append(node)+ super().visit_call(node)++ @classmethod+ def contains(cls, node: ast.AST) -> bool:+ finder = cls()+ finder.visit(node)+ return bool(finder.calls)+++@frozen+class PromptJevCall:+ input: ast.Expr+ question: Question+ batch_size: int++ @property+ def clickhouse_type(self) -> str:+ return CHOICE_TYPE if isinstance(self.question, ChoiceQuestion) else "Nullable(Float64)"++ @classmethod+ def parse(cls, node: ast.Call) -> "PromptJevCall":+ if node.params or node.distinct or node.filter_expr or node.order_by or node.within_group:+ raise QueryError("__preview_promptJev does not accept aggregate modifiers.")+ if len(node.args) < 2 or isinstance(node.args[0], ast.NamedArgument):+ raise QueryError("Use __preview_promptJev(input, instructions, choice := ['label', 'other']).")+ instructions = node.args[1]+ if (+ not isinstance(instructions, ast.Constant)+ or not isinstance(instructions.value, str)+ or not instructions.value.strip()+ ):+ raise QueryError("__preview_promptJev instructions must be a non-empty string literal.")+ if len(instructions.value.encode()) > 8192:+ raise QueryError("__preview_promptJev instructions exceed 8 KiB. Shorten the instructions.")+ options: dict[str, ast.Expr] = {}+ for arg in node.args[2:]:+ if not isinstance(arg, ast.NamedArgument) or arg.name not in {"choice", "noul", "batch_size"}:+ raise QueryError("__preview_promptJev supports the named arguments choice, noul, and batch_size.")+ if arg.name in options:+ raise QueryError(f"__preview_promptJev received {arg.name} more than once.")+ options[arg.name] = arg.value+ if "choice" in options and "noul" in options:+ raise QueryError("Use either choice or noul with __preview_promptJev.")+ batch = options.get("batch_size", ast.Constant(value=16))+ if not isinstance(batch, ast.Constant) or type(batch.value) is not int or not 1 <= batch.value <= 32:+ raise QueryError("__preview_promptJev batch_size must be an integer literal between 1 and 32.")+ criteria: dict[str, str | None] = {}+ option = options.get("choice", options.get("noul"))+ if option is not None:+ if not isinstance(option, ast.Array):+ raise QueryError("__preview_promptJev criteria must be an array of string literals.")+ for item in option.exprs:+ if not isinstance(item, ast.Constant) or not isinstance(item.value, str) or not item.value.strip():+ raise QueryError("__preview_promptJev criteria must contain non-empty string literals.")+ if item.value in criteria:+ raise QueryError("__preview_promptJev criteria must be unique.")+ if len(item.value.encode()) > 1024:+ raise QueryError("__preview_promptJev labels exceed 1 KiB. Shorten the labels.")+ criteria[item.value] = None+ if "choice" in options:+ if not 2 <= len(criteria) <= MAX_CHOICES:+ raise QueryError(f"__preview_promptJev choice needs between 2 and {MAX_CHOICES} labels.")+ question: Question = ChoiceQuestion(instructions=instructions.value, criteria=criteria)+ else:+ if "noul" in options and set(criteria) != {"true", "false"}:+ raise QueryError("__preview_promptJev noul needs exactly the labels 'true' and 'false'.")+ question = NoulQuestion(instructions=instructions.value)+ if PromptJevFinder.contains(node.args[0]):+ raise QueryError("Put each __preview_promptJev evaluation in a separate subquery.")+ return cls(input=node.args[0], question=question, batch_size=batch.value)diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.pyindex 3c05f9b0070b..fe7ebafff40e 100644--- a/posthog/hogql/printer/clickhouse.py+++ b/posthog/hogql/printer/clickhouse.py@@ -955,6 +955,10 @@ class ClickHousePrinter(BasePrinter):return isinstance(left_type, ast.DecimalType) and isinstance(right_type, ast.DecimalType)def visit_call(self, node: ast.Call):+ if node.name.lower() == "__preview_promptjev":+ raise QueryError(+ "__preview_promptJev must run through the HogQL query executor. It cannot be embedded in SQL."+ )serialized = self._serialize_to_json_string_call(node)if serialized is not None:return serializeddiff --git a/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambrindex 2951f56cee01..6456bd55e361 100644--- a/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr+++ b/posthog/hogql/printer/test/__snapshots__/test_trino_printer.ambr@@ -304,6 +304,7 @@'__preview_getTrafficCategory','__preview_getTrafficType','__preview_isBot',+ '__preview_promptJev','_defaultChannelType','_domainType','embedText',diff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex 1a3b96846621..8e0e2d1e30d1 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -49,9 +49,10 @@ from posthog.hogql.direct_sql import (get_adapter,get_raw_adapter_for_source,)-from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError, QueryError, ResolutionError+from posthog.hogql.errors import BaseHogQLError, ExposedHogQLError, InternalHogQLError, QueryError, ResolutionErrorfrom posthog.hogql.feature_extractor import extract_hogql_featuresfrom posthog.hogql.filters import replace_filters+from posthog.hogql.functions.prompt_jev import PromptJevFinderfrom posthog.hogql.hogql import HogQLContextfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_select, sanitize_client_parser_mode@@ -80,6 +81,8 @@ from products.access_control.backend.facade.user_access_control import UserAccesfrom products.warehouse_sources.backend.facade.types import ManagedWarehouseSQLModeif TYPE_CHECKING:+ from posthog.hogql.transforms.prompt_jev import PromptJevTable+from products.warehouse_sources.backend.facade.models import ExternalDataSourcetracer = trace.get_tracer(__name__)@@ -169,6 +172,9 @@ class HogQLQueryExecutor:self.used_data_warehouse_sources: list[WarehouseSourceUsage] = []self._direct_source: Optional[ExternalDataSource] = Noneself._direct_source_resolved = False+ self._prompt_jev_tables: list[PromptJevTable] = []+ self._prompt_jev_warehouse_sources: list[WarehouseSourceUsage] = []+ self._executing = False@tracer.start_as_current_span("HogQLQueryExecutor._parse_query")def _parse_query(self):@@ -309,6 +315,8 @@ class HogQLQueryExecutor:limit_context=self.limit_context,database=database,)+ for table in self._prompt_jev_tables:+ table.register(self.hogql_context)self._apply_optimizers()@@ -567,6 +575,25 @@ class HogQLQueryExecutor:return None+ def _resolved_column_types(self) -> dict[str, ast.ConstantType]:+ """HogQL types of the executed query's columns, for a caller that has to keep a column's+ logical type after materializing its rows. A column whose type cannot be resolved is left out,+ because the caller has the ClickHouse type to fall back on."""+ context = self.hogql_context or self.context+ types: dict[str, ast.ConstantType] = {}+ try:+ query_type = self._get_select_query_type()+ if query_type is None:+ return types+ for name, column in query_type.columns.items():+ try:+ types[name] = column.resolve_constant_type(context)+ except BaseHogQLError:+ continue+ except BaseHogQLError:+ return {}+ return types+def _detect_warehouse_sources(self) -> list[WarehouseSourceUsage]:"""Detect connector-synced data warehouse sources referenced by the (resolved) query andstore them for the query response. Never raises — telemetry must not break query execution."""@@ -574,6 +601,8 @@ class HogQLQueryExecutor:sources = extract_warehouse_sources(self._get_select_query_type())except Exception:sources = []+ # __preview_promptJev source queries read their tables in separate executions.+ sources = list({source.id: source for source in [*sources, *self._prompt_jev_warehouse_sources]}.values())self.used_data_warehouse_sources = sourcesreturn sources@@ -705,6 +734,69 @@ class HogQLQueryExecutor:else:raise+ def _evaluate_prompt_jev(self) -> None:+ from posthog.hogql.transforms.prompt_jev import ( # noqa: PLC0415 -- keep the optional model clients off ordinary query imports+ PromptJevBudget,+ PromptJevPlanner,+ PromptJevRunner,+ PromptJevSource,+ validate_prompt_jev_access,+ )++ validate_prompt_jev_access(self.team)+ PromptJevBudget().visit(self.select_query)+ # The resolver types __preview_promptJev calls without model output, so an invalid query fails before any model call.+ Resolver(+ context=dataclasses.replace(+ self.context,+ team_id=self.team.pk,+ team=self.team,+ user=self.user,+ enable_select_queries=True,+ modifiers=self.query_modifiers,+ database=self.context.database+ or Database.create_for(+ team=self.team,+ user=self.user,+ user_access_control=self.context.user_access_control,+ modifiers=self.query_modifiers,+ timings=self.timings,+ bypass_warehouse_access_control=self.context.bypass_warehouse_access_control,+ trigger="executor",+ ),+ warnings=[],+ notices=[],+ errors=[],+ ),+ dialect="clickhouse",+ ).visit(clone_expr(self.select_query, True))+ self._prompt_jev_tables = []+ runner = PromptJevRunner(team_id=self.team.pk, distinct_id=self.user.distinct_id if self.user else None)++ def execute_source(query: ast.SelectQuery) -> PromptJevSource:+ settings = get_default_hogql_global_settings(self.team.pk, self.settings)+ timeout = runner.source_timeout()+ settings.max_execution_time = min(settings.max_execution_time or timeout, timeout)+ executor = dataclasses.replace(+ self,+ query=query,+ settings=settings,+ context=dataclasses.replace(self.context, limit_top_select=False),+ limit_context=LimitContext.QUERY,+ )+ executor._prompt_jev_tables = self._prompt_jev_tables+ response = executor.execute()+ self._prompt_jev_warehouse_sources.extend(executor.used_data_warehouse_sources)+ return PromptJevSource(response=response, column_types=executor._resolved_column_types())++ planner = PromptJevPlanner(execute=execute_source, runner=runner, tables=self._prompt_jev_tables)+ with self.timings.measure("__preview_promptJev"):+ self.select_query = planner.visit(self.select_query)+ if PromptJevFinder.contains(self.select_query):+ raise QueryError(+ "Use __preview_promptJev in a named SELECT column and filter its results in an outer query."+ )+def _prepare_execution(self, *, embedded_select: bool = False) -> _PreparedExecution:self.context.referenced_saved_query_ids.clear()self._parse_query()@@ -720,6 +812,12 @@ class HogQLQueryExecutor:self._process_variables()self._process_placeholders()+ if PromptJevFinder.contains(self.select_query):+ if embedded_select or not self._executing or self.connection_id is not None:+ raise QueryError(+ "__preview_promptJev requires a ClickHouse-backed query execution and cannot be embedded."+ )+ self._evaluate_prompt_jev()if embedded_select:_EmbeddedSelectSettingsValidator().visit(self.select_query)if not embedded_select:@@ -898,6 +996,7 @@ class HogQLQueryExecutor:@tracer.start_as_current_span("HogQLQueryExecutor.execute")def execute(self) -> HogQLQueryResponse:+ self._executing = Truetrace.get_current_span().set_attribute("team_id", self.team.pk)try:if self.send_raw_query and self.connection_id is not None:diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex e56561a25fcb..bb2bbe48acde 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -33,6 +33,7 @@ from posthog.hogql.functions.cohort import cohort_query_nodefrom posthog.hogql.functions.core import validate_function_argsfrom posthog.hogql.functions.explain_csp_report import explain_csp_reportfrom posthog.hogql.functions.mapping import HOGQL_CLICKHOUSE_FUNCTIONS+from posthog.hogql.functions.prompt_jev import PromptJevCallfrom posthog.hogql.functions.recording_button import recording_buttonfrom posthog.hogql.functions.sparkline import sparklinefrom posthog.hogql.functions.survey import get_survey_response, unique_survey_submissions_filter@@ -61,6 +62,7 @@ from posthog.hogql.transforms.trino.persons import ()from posthog.hogql.transforms.trino.pivot import TrinoPivotLowererfrom posthog.hogql.type_system import (+ constant_type_from_runtime_type,infer_array_access_constant_type,infer_array_constant_type,infer_array_slice_constant_type,@@ -69,6 +71,7 @@ from posthog.hogql.type_system import (infer_try_cast_constant_type,infer_tuple_access_constant_type,least_common_supertype,+ parse_clickhouse_type,)from posthog.hogql.utils import map_virtual_propertiesfrom posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr@@ -1984,6 +1987,17 @@ class Resolver(CloningVisitor):def visit_call(self, node: ast.Call):"""Visit function calls."""+ if node.name.lower() == "__preview_promptjev":+ spec = PromptJevCall.parse(node)+ node = clone_expr(node, clear_types=True)+ node.args[0] = self.visit(spec.input)+ node.type = ast.CallType(+ name="__preview_promptJev",+ arg_types=[],+ return_type=constant_type_from_runtime_type(parse_clickhouse_type(spec.clickhouse_type)),+ )+ return node+if self.dialect == "trino" and node.name.lower() == "date":node = clone_expr(node, clear_types=False)node.name = "toDate"@@ -2506,6 +2520,13 @@ class Resolver(CloningVisitor):if len(chain_to_parse) == 0:breaknext_chain = chain_to_parse.pop(0)+ if isinstance(loop_type, (ast.FieldType, ast.FieldAliasType)) and self.dialect in {"hogql", "clickhouse"}:+ tuple_type = loop_type.resolve_constant_type(self.context)+ if isinstance(tuple_type, ast.TupleType) and str(next_chain) in tuple_type.field_names:+ expression: ast.Expr = ast.Field(chain=list(resolved_chain))+ for member in [next_chain, *chain_to_parse]:+ expression = ast.Call(name="tupleElement", args=[expression, ast.Constant(value=member)])+ return self.visit(expression)if next_chain == "..": # only support one level of ".."previous_types.pop()previous_types.pop()diff --git a/posthog/hogql/test/test_prompt_jev.py b/posthog/hogql/test/test_prompt_jev.pynew file mode 100644index 000000000000..1d3a3e9f4721--- /dev/null+++ b/posthog/hogql/test/test_prompt_jev.py@@ -0,0 +1,373 @@+import re+import json+import time+import asyncio++from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events+from unittest.mock import patch++from django.test import SimpleTestCase, override_settings++import httpx+from parameterized import parameterized++from posthog.hogql import ast+from posthog.hogql.errors import QueryError+from posthog.hogql.functions.prompt_jev import PromptJevCall+from posthog.hogql.parser import parse_expr, parse_select+from posthog.hogql.query import execute_hogql_query+from posthog.hogql.transforms.prompt_jev import PromptJevBudget, PromptJevRunner++from posthog.clickhouse.client import sync_execute+from posthog.models.team import Team+++def gateway_response(_url: str, *, json: dict, headers: dict) -> httpx.Response:+ answers = {}+ for name, question in json["questions"].items():+ text = json["state"][name]+ if question["type"] == "noul":+ answers[name] = {"type": "noul", "noul": 0.9 if "refund" in text else 0.1}+ else:+ choice = "billing" if "refund" in text else "other"+ answers[name] = {+ "type": "choice",+ "choice": choice,+ "confidence": 0.9,+ "probabilities": {label: 0.9 if label == choice else 0.1 for label in question["criteria"]},+ }+ return httpx.Response(200, json={"model": "jevk5-0.2", "answers": answers, "usage": {"input_tokens": 10}})+++@override_settings(AI_GATEWAY_URL="https://gateway.example.com/v1", AI_GATEWAY_API_KEY="test-key")+class TestPromptJev(SimpleTestCase):+ @parameterized.expand(+ [+ ("SELECT __preview_promptJev('a', 'q') AS p", 1000),+ ("SELECT __preview_promptJev('a', 'q') AS p, __preview_promptJev('b', 'q') AS q LIMIT 500", 1000),+ ("SELECT __preview_promptJev('a', 'q') AS p, __preview_promptJev('b', 'q') AS q LIMIT 0", 0),+ (+ "WITH c AS (SELECT __preview_promptJev('a', 'q') AS p LIMIT 1000) SELECT a.p, b.p FROM c a CROSS JOIN c b",+ 1000,+ ),+ (+ "WITH c AS (SELECT __preview_promptJev('a', 'q') AS p LIMIT 600) "+ "SELECT 0.0 AS p UNION ALL SELECT p FROM c",+ 600,+ ),+ (+ "WITH c AS (SELECT __preview_promptJev('a', 'q') AS p LIMIT 600) "+ "SELECT p FROM c UNION ALL SELECT p FROM c",+ 600,+ ),+ ]+ )+ def test_query_budget_reservations(self, query: str, expected: int) -> None:+ budget = PromptJevBudget()+ budget.visit(parse_select(query))+ self.assertEqual(budget.decisions, expected)++ def test_unused_ctes_do_not_reserve_budget(self) -> None:+ budget = PromptJevBudget()+ budget.visit(+ parse_select(+ "WITH a AS (SELECT __preview_promptJev('a', 'q') AS p), "+ "b AS (SELECT __preview_promptJev('b', 'q') AS p) SELECT 1"+ )+ )+ self.assertEqual(budget.decisions, 0)++ @parameterized.expand(+ [+ ("__preview_promptJev('a', '')", "non-empty"),+ ("__preview_promptJev('a', instructions)", "literal"),+ ("__preview_promptJev('a', 'q', choice := ['a', 'a'])", "unique"),+ ("__preview_promptJev('a', 'q', choice := ['a'])", "between 2"),+ ("__preview_promptJev('a', 'q', batch_size := 0)", "between 1"),+ ("__preview_promptJev('a', 'q', noul := ['yes', 'no'])", "exactly"),+ ("__preview_promptJev('a', 'q', choice := ['a','b'], noul := ['true','false'])", "either"),+ ("__preview_promptJev('a', 'q', score := ['a','b'])", "supports"),+ ]+ )+ def test_invalid_arguments(self, query: str, message: str) -> None:+ node = parse_expr(query)+ assert isinstance(node, ast.Call)+ with self.assertRaisesRegex(QueryError, message):+ PromptJevCall.parse(node)++ def test_batches_deduplicates_and_skips_nulls(self) -> None:+ node = parse_expr("__preview_promptJev(body, 'Refund?', batch_size := 2)")+ assert isinstance(node, ast.Call)+ spec = PromptJevCall.parse(node)+ runner = PromptJevRunner(team_id=123, distinct_id="test-user")+ with patch("httpx.AsyncClient.post", side_effect=gateway_response) as post:+ self.assertEqual(runner.evaluate(spec, [None, "refund", "hello", "refund"]), [None, 0.9, 0.1, 0.9])+ self.assertEqual(runner.evaluate(spec, ["refund"]), [0.9])+ self.assertEqual(post.call_count, 1)+ request = post.call_args.kwargs+ self.assertEqual(len(request["json"]["questions"]), 2)+ properties = json.loads(request["headers"]["X-PostHog-Properties"])+ self.assertEqual(properties["team_id"], "123")++ @parameterized.expand([(42, "must be text"), ("x" * 8193, "8 KiB")])+ def test_rejects_invalid_input_before_network(self, value: object, message: str) -> None:+ node = parse_expr("__preview_promptJev(body, 'Refund?')")+ assert isinstance(node, ast.Call)+ with patch("httpx.AsyncClient.post") as post, self.assertRaisesRegex(QueryError, message):+ PromptJevRunner(team_id=1, distinct_id=None).evaluate(PromptJevCall.parse(node), [value])+ post.assert_not_called()++ def test_gateway_failure_does_not_return_a_decision(self) -> None:+ node = parse_expr("__preview_promptJev('refund', 'Refund?')")+ assert isinstance(node, ast.Call)+ with (+ patch("httpx.AsyncClient.post", return_value=httpx.Response(429)),+ self.assertRaisesRegex(QueryError, "could not evaluate"),+ ):+ PromptJevRunner(team_id=1, distinct_id=None).evaluate(PromptJevCall.parse(node), ["refund"])++ def test_deadline_cancels_inflight_requests_and_pending_batches(self) -> None:+ node = parse_expr("__preview_promptJev(body, 'Refund?', batch_size := 1)")+ assert isinstance(node, ast.Call)+ runner = PromptJevRunner(team_id=1, distinct_id=None)+ cancelled = 0+ started = 0+ timeout = asyncio.timeout+ deadline: asyncio.Timeout | None = None++ def controlled_timeout(seconds: float) -> asyncio.Timeout:+ nonlocal deadline+ deadline = timeout(None)+ return deadline++ async def stalled_response(*args: object, **kwargs: object) -> httpx.Response:+ nonlocal cancelled, started+ started += 1+ if started == 4:+ assert deadline is not None+ deadline.reschedule(asyncio.get_running_loop().time())+ try:+ await asyncio.Event().wait()+ finally:+ cancelled += 1+ raise AssertionError("The stalled response must be cancelled")++ with (+ patch("httpx.AsyncClient.post", side_effect=stalled_response) as post,+ patch("posthog.hogql.transforms.prompt_jev.asyncio.timeout", side_effect=controlled_timeout),+ self.assertRaisesRegex(QueryError, "time limit"),+ ):+ runner.evaluate(PromptJevCall.parse(node), [str(i) for i in range(8)])+ self.assertEqual(post.call_count, 4)+ self.assertEqual(cancelled, 4)++ def test_expired_deadline_sends_no_requests(self) -> None:+ node = parse_expr("__preview_promptJev(body, 'Refund?')")+ assert isinstance(node, ast.Call)+ runner = PromptJevRunner(team_id=1, distinct_id=None)+ runner.deadline = time.monotonic() - 1+ self.assertEqual(runner.source_timeout(), 1)+ with patch("httpx.AsyncClient.post") as post, self.assertRaisesRegex(QueryError, "time limit"):+ runner.evaluate(PromptJevCall.parse(node), ["refund"])+ post.assert_not_called()+++@override_settings(AI_GATEWAY_URL="https://gateway.example.com/v1", AI_GATEWAY_API_KEY="test-key")+class TestPromptJevQuery(ClickhouseTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ flag = patch("posthog.hogql.transforms.prompt_jev.feature_enabled_or_false", return_value=True)+ self.feature_enabled = flag.start()+ self.addCleanup(flag.stop)++ @parameterized.expand(+ [+ ("SELECT " + ", ".join(f"__preview_promptJev('a', 'q{i}') AS p{i}" for i in range(10)) + " LIMIT 101",),+ ("SELECT __preview_promptJev('a', 'q') AS p, __preview_promptJev('b', 'q') AS q",),+ (+ "SELECT __preview_promptJev('a', 'q') AS p LIMIT 501 UNION ALL SELECT __preview_promptJev('b', 'q') AS p LIMIT 500",+ ),+ (+ "SELECT __preview_promptJev(toString(p), 'q') AS q FROM (SELECT __preview_promptJev('a', 'q') AS p LIMIT 501) LIMIT 500",+ ),+ (+ "WITH c AS (SELECT __preview_promptJev(toString(number), 'first') AS p FROM numbers(1000) LIMIT 1000) "+ "SELECT 0.0 AS p UNION ALL SELECT __preview_promptJev('refund', 'second') AS p FROM c LIMIT 1",+ ),+ ]+ )+ def test_combined_budget_rejects_before_source_queries_or_inference(self, query: str) -> None:+ with (+ patch("posthog.hogql.query.sync_execute") as execute,+ patch("httpx.AsyncClient.post") as post,+ self.assertRaisesRegex(QueryError, "across all columns and SELECTs"),+ ):+ execute_hogql_query(query, self.team, user=self.user)+ execute.assert_not_called()+ post.assert_not_called()++ @parameterized.expand([(False,), (None,)])+ def test_unapproved_project_cannot_start_inference(self, enabled: bool | None) -> None:+ self.feature_enabled.return_value = enabled+ with (+ patch("posthog.hogql.query.sync_execute") as execute,+ patch("httpx.AsyncClient.post") as post,+ self.assertRaisesRegex(QueryError, "not enabled for this project"),+ ):+ execute_hogql_query("SELECT __preview_promptJev('refund', 'Refund?') AS p", self.team, user=self.user)+ execute.assert_not_called()+ post.assert_not_called()+ self.assertEqual(self.feature_enabled.call_args.kwargs["groups"]["project"], str(self.team.pk))++ @parameterized.expand([("global",), ("team",)])+ def test_http_route_is_rejected_before_query_or_inference(self, mode: str) -> None:+ with (+ override_settings(+ CLICKHOUSE_USE_HTTP=mode == "global",+ CLICKHOUSE_USE_HTTP_PER_TEAM=[self.team.pk] if mode == "team" else [],+ ),+ patch("posthog.hogql.query.sync_execute") as execute,+ patch("httpx.AsyncClient.post") as post,+ self.assertRaisesRegex(QueryError, "native ClickHouse connection"),+ ):+ execute_hogql_query("SELECT __preview_promptJev('refund', 'Refund?') AS p", self.team, user=self.user)+ execute.assert_not_called()+ post.assert_not_called()++ def test_query_api_only_classifies_the_requesting_teams_events(self) -> None:+ other_team = Team.objects.create(organization=self.organization)+ for team, message in [(self.team, "refund please"), (other_team, "different project message")]:+ _create_event(+ team=team, event="jev_test_message", distinct_id="synthetic-user", properties={"message": message}+ )+ flush_persons_and_events()+ with patch("httpx.AsyncClient.post", side_effect=gateway_response) as post:+ response = self.client.post(+ f"/api/environments/{self.team.id}/query/",+ {+ "query": {+ "kind": "HogQLQuery",+ "query": "SELECT __preview_promptJev(properties.message, 'Refund?') AS probability FROM events WHERE event = 'jev_test_message' LIMIT 10",+ }+ },+ )+ self.assertEqual(response.status_code, 200, response.content)+ self.assertEqual(response.json()["results"], [[0.9]])+ self.assertEqual(list(post.call_args.kwargs["json"]["state"].values()), ["refund please"])++ @parameterized.expand(+ [+ (+ "SELECT probability FROM (SELECT __preview_promptJev('refund please', 'Refund?') AS probability) WHERE probability > 0.5",+ [(0.9,)],+ ),+ (+ "SELECT result.choice, count() FROM (SELECT __preview_promptJev(body, 'Route?', choice := ['billing', 'other']) AS result FROM (SELECT arrayJoin(['refund', 'hello', 'refund']) AS body)) GROUP BY result.choice ORDER BY result.choice",+ [("billing", 2), ("other", 1)],+ ),+ (+ "WITH classified AS (SELECT __preview_promptJev('refund', 'Refund?') AS p) SELECT a.p, b.p FROM classified a CROSS JOIN classified b",+ [(0.9, 0.9)],+ ),+ (+ "WITH a AS (SELECT __preview_promptJev('refund', 'Refund?') AS p), b AS (SELECT p FROM a) SELECT p FROM b",+ [(0.9,)],+ ),+ (+ "SELECT label FROM (SELECT __preview_promptJev(body, 'Refund?') AS label FROM (SELECT label AS body FROM (SELECT 'refund' AS label)))",+ [(0.9,)],+ ),+ ("SELECT __preview_promptJev(NULL, 'Refund?') AS p", [(None,)]),+ ("SELECT __preview_promptJev('hello', 'Refund?') AS p LIMIT 0", []),+ (+ "SELECT "+ + ", ".join(f"__preview_promptJev('refund', 'Refund?') AS p{i}" for i in range(10))+ + " LIMIT 100",+ [(0.9,) * 10],+ ),+ (+ "WITH messages AS (SELECT 'refund' AS body) SELECT 0.0 AS p UNION ALL SELECT __preview_promptJev(body, 'Refund?') AS p FROM messages LIMIT 10",+ [(0.0,), (0.9,)],+ ),+ ]+ )+ def test_sql_decisions(self, query: str, expected: list) -> None:+ with patch("httpx.AsyncClient.post", side_effect=gateway_response) as post:+ response = execute_hogql_query(query, self.team, user=self.user)+ self.assertEqual(response.results, expected)+ self.assertLessEqual(post.call_count, 1)++ @parameterized.expand(+ [+ ("WITH unused AS (SELECT __preview_promptJev('refund', 'Refund?') AS p) SELECT 1",),+ ("WITH a AS (SELECT __preview_promptJev('refund', 'Refund?') AS p), b AS (SELECT p FROM a) SELECT 1",),+ ]+ )+ def test_unused_ctes_send_no_requests(self, query: str) -> None:+ with patch("httpx.AsyncClient.post") as post:+ response = execute_hogql_query(query, self.team, user=self.user)+ self.assertEqual(response.results, [(1,)])+ post.assert_not_called()++ def test_explicit_limit_above_the_default_keeps_every_row(self) -> None:+ with patch("httpx.AsyncClient.post", side_effect=gateway_response):+ response = execute_hogql_query(+ "SELECT __preview_promptJev(toString(number), 'Refund?') AS p FROM numbers(150) LIMIT 150",+ self.team,+ user=self.user,+ )+ self.assertEqual(len(response.results or []), 150)++ def test_outer_query_reads_properties_off_a_passthrough_column(self) -> None:+ _create_event(+ team=self.team,+ event="jev_test_message",+ distinct_id="synthetic-user",+ properties={"message": "refund please", "category": "billing"},+ )+ flush_persons_and_events()+ with patch("httpx.AsyncClient.post", side_effect=gateway_response):+ response = execute_hogql_query(+ "SELECT props.category, p FROM (SELECT properties AS props, __preview_promptJev(properties.message, 'Refund?') AS p FROM events WHERE event = 'jev_test_message' LIMIT 1)",+ self.team,+ user=self.user,+ )+ self.assertEqual(response.results, [("billing", 0.9)])++ def test_source_scan_stays_within_the_inference_deadline(self) -> None:+ with (+ patch("httpx.AsyncClient.post", side_effect=gateway_response),+ patch("posthog.hogql.query.sync_execute", wraps=sync_execute) as execute,+ ):+ execute_hogql_query("SELECT __preview_promptJev('refund', 'Refund?') AS p", self.team, user=self.user)+ timeouts = [+ int(seconds)+ for call in execute.call_args_list+ for seconds in re.findall(r"max_execution_time=(\d+)", call.args[0])+ ]+ self.assertEqual(len(timeouts), 2)+ self.assertLessEqual(max(timeouts), 60)++ @parameterized.expand(+ [+ ("SELECT __preview_promptJev('a', 'q')", "named SELECT"),+ ("SELECT __preview_promptJev('a', 'q') AS p ORDER BY p", "outside"),+ ("SELECT __preview_promptJev('a', 'q') AS p WHERE p > 0.5", "outer query"),+ ("SELECT labl FROM (SELECT __preview_promptJev('refund', 'Refund?') AS label)", "labl"),+ ("SELECT __preview_promptJev(toString(number), 'q') AS p FROM numbers(1001)", "at most 1000"),+ (+ "SELECT __preview_promptJev(toString(number), 'Topic?') AS a, __preview_promptJev(toString(number), 'Tone?') AS b FROM numbers(600)",+ "query budget",+ ),+ ]+ )+ def test_rejects_unsafe_query_shapes_before_inference(self, query: str, message: str) -> None:+ with patch("httpx.AsyncClient.post") as post, self.assertRaisesRegex(QueryError, message):+ execute_hogql_query(query, self.team, user=self.user)+ post.assert_not_called()++ @override_settings(AI_GATEWAY_URL="", AI_GATEWAY_API_KEY="")+ def test_missing_gateway_configuration(self) -> None:+ with patch("httpx.AsyncClient.post") as post, self.assertRaisesRegex(QueryError, "not configured"):+ execute_hogql_query("SELECT __preview_promptJev('a', 'q') AS p", self.team, user=self.user)+ post.assert_not_called()diff --git a/posthog/hogql/transforms/prompt_jev.py b/posthog/hogql/transforms/prompt_jev.pynew file mode 100644index 000000000000..afbc38c46325--- /dev/null+++ b/posthog/hogql/transforms/prompt_jev.py@@ -0,0 +1,495 @@+import json+import math+import time+import uuid+import asyncio+from collections.abc import Callable+from dataclasses import replace+from typing import TYPE_CHECKING, cast++from django.conf import settings++import structlog+from asgiref.sync import async_to_sync++from posthog.schema import HogQLQueryResponse++from posthog.hogql import ast+from posthog.hogql.database.models import DANGEROUS_NoTeamIdCheckTable, DatabaseField, TableNode+from posthog.hogql.errors import QueryError+from posthog.hogql.escape_sql import escape_clickhouse_identifier+from posthog.hogql.functions.prompt_jev import PromptJevCall, PromptJevFinder+from posthog.hogql.type_system import constant_type_from_runtime_type, parse_clickhouse_type+from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr++from posthog.dataclasses import frozen+from posthog.llm.system_one import (+ ChoiceAnswer,+ ChoiceQuestion,+ NoulAnswer,+ Question,+ SystemOneNotConfigured,+ SystemOneRequestFailed,+)+from posthog.llm.system_one_client import GatewaySystemOneClient, build_system_one_client+from posthog.ph_client import feature_enabled_or_false++if TYPE_CHECKING:+ from posthog.hogql.context import HogQLContext++ from posthog.models.team import Team++logger = structlog.get_logger(__name__)++MAX_ROWS = 1000+MAX_DECISIONS = 1000+MAX_INPUT_BYTES = 8192+MAX_TOTAL_BYTES = 2 * 1024 * 1024+MAX_BATCH_BYTES = 32768+++class _ResultField(DatabaseField):+ clickhouse_type: str+ hogql_type: ast.ConstantType | None = None++ def get_constant_type(self) -> ast.ConstantType:+ if self.hogql_type is not None:+ return self.hogql_type+ return constant_type_from_runtime_type(parse_clickhouse_type(self.clickhouse_type))+++class _ResultTable(DANGEROUS_NoTeamIdCheckTable):+ # These rows have already passed the source query's tenant and resource access checks.+ def to_printed_clickhouse(self, context: "HogQLContext") -> str:+ return escape_clickhouse_identifier(self.name or "")++ def to_printed_hogql(self) -> str:+ return self.name or ""+++@frozen+class PromptJevColumn:+ name: str+ clickhouse_type: str+ # A ClickHouse type does not say whether the source column was a JSON blob or an array, so a+ # passthrough column keeps its HogQL type here and an outer query can still read properties off it.+ hogql_type: ast.ConstantType | None = None+++@frozen+class PromptJevSource:+ response: HogQLQueryResponse+ column_types: dict[str, ast.ConstantType]+++@frozen+class PromptJevTable:+ name: str+ columns: list[PromptJevColumn]+ rows: list[list[object]]++ def register(self, context: "HogQLContext") -> None:+ assert context.database is not None+ names = [column.name for column in self.columns]+ context.external_tables[self.name] = {+ "name": self.name,+ "structure": [(column.name, column.clickhouse_type) for column in self.columns],+ "data": [dict(zip(names, row)) for row in self.rows],+ }+ context.database.tables.add_child(+ TableNode(+ name=self.name,+ table=_ResultTable(+ name=self.name,+ fields={+ column.name: _ResultField(+ name=column.name,+ clickhouse_type=column.clickhouse_type,+ hogql_type=column.hogql_type,+ )+ for column in self.columns+ },+ ),+ hidden=True,+ ),+ table_conflict_mode="override",+ children_conflict_mode="override",+ )+++@frozen+class _DecisionKey:+ question: str+ text: str+++class PromptJevRunner:+ def __init__(self, *, team_id: int, distinct_id: str | None) -> None:+ self.team_id = team_id+ self.distinct_id = distinct_id+ self.cache: dict[_DecisionKey, object] = {}+ self.input_bytes = 0+ self.deadline = time.monotonic() + 60+ self.client: GatewaySystemOneClient | None = None++ def source_timeout(self) -> int:+ # Source scans share the inference deadline. ClickHouse takes max_execution_time in whole seconds, and 0 disables it.+ return max(1, math.ceil(self.deadline - time.monotonic()))++ async def _batch(self, spec: PromptJevCall, texts: list[str]) -> dict[str, object]:+ assert self.client is not None+ remaining = self.deadline - time.monotonic()+ if remaining <= 0:+ raise QueryError("__preview_promptJev exceeded its time limit. Select fewer rows and try again.")+ questions: dict[str, Question] = {}+ state: dict[str, str] = {}+ for i, text in enumerate(texts):+ key = f"row_{i}"+ state[key] = text+ questions[key] = replace(+ spec.question,+ instructions={+ "input": f"Evaluate only the text in state.{key}.",+ "question": spec.question.instructions,+ },+ )+ try:+ result = await replace(self.client, timeout=min(remaining, 30)).adecide(state=state, questions=questions)+ except SystemOneRequestFailed as error:+ # Log only the status, because the inputs and the gateway response body can hold customer data.+ logger.warning(+ "prompt_jev_gateway_failed",+ team_id=self.team_id,+ status_code=error.status_code,+ reason=type(error).__name__,+ )+ raise QueryError("Jev could not evaluate this query. Try again or select fewer rows.") from error+ decisions: dict[str, object] = {}+ for key, text in state.items():+ answer = result.answers[key]+ if isinstance(answer, NoulAnswer):+ decisions[text] = answer.probability+ elif isinstance(answer, ChoiceAnswer):+ decisions[text] = (answer.choice, list(answer.probabilities.items()), answer.confidence)+ return decisions++ async def _batches(self, spec: PromptJevCall, batches: list[list[str]]) -> list[dict[str, object]]:+ semaphore = asyncio.Semaphore(4)++ async def evaluate_batch(batch: list[str]) -> dict[str, object]:+ async with semaphore:+ return await self._batch(spec, batch)++ tasks: list[asyncio.Task[dict[str, object]]] = []+ try:+ async with asyncio.timeout(max(0, self.deadline - time.monotonic())):+ tasks = [asyncio.create_task(evaluate_batch(batch)) for batch in batches]+ return await asyncio.gather(*tasks)+ except TimeoutError as error:+ raise QueryError("__preview_promptJev exceeded its time limit. Select fewer rows and try again.") from error+ finally:+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)++ def check_budget(self, columns: list[tuple[PromptJevCall, list[object]]]) -> dict[_DecisionKey, None]:+ missing: dict[_DecisionKey, None] = {}+ for spec, values in columns:+ question_key = json.dumps(spec.question.to_json(), sort_keys=True)+ for value in values:+ if value is None:+ continue+ if not isinstance(value, str):+ raise QueryError("__preview_promptJev input must be text. Use toString(input) to convert it.")+ if len(value.encode()) > MAX_INPUT_BYTES:+ raise QueryError(+ "__preview_promptJev input exceeds 8 KiB. Shorten each input before classifying it."+ )+ key = _DecisionKey(question=question_key, text=value)+ if key not in self.cache:+ missing[key] = None+ input_bytes = self.input_bytes + sum(len(key.text.encode()) for key in missing)+ if len(self.cache) + len(missing) > MAX_DECISIONS or input_bytes > MAX_TOTAL_BYTES:+ raise QueryError("__preview_promptJev exceeds the query budget. Select fewer or shorter inputs.")+ return missing++ def evaluate(self, spec: PromptJevCall, values: list[object]) -> list[object]:+ question_key = json.dumps(spec.question.to_json(), sort_keys=True)+ missing = [key.text for key in self.check_budget([(spec, values)])]+ self.input_bytes += sum(len(text.encode()) for text in missing)+ if missing and self.client is None:+ try:+ client = build_system_one_client(+ model=settings.HOGQL_PROMPT_JEV_MODEL,+ ai_product="hogql_prompt_jev",+ distinct_id=self.distinct_id,+ properties={"team_id": str(self.team_id)},+ )+ assert isinstance(client, GatewaySystemOneClient)+ self.client = client+ except SystemOneNotConfigured as error:+ raise QueryError(+ "Jev is not configured. Set AI_GATEWAY_URL and AI_GATEWAY_API_KEY on the server."+ ) from error+ batches: list[list[str]] = []+ batch_bytes = 0+ for text in missing:+ size = len(text.encode())+ if not batches or len(batches[-1]) >= spec.batch_size or batch_bytes + size > MAX_BATCH_BYTES:+ batches.append([])+ batch_bytes = 0+ batches[-1].append(text)+ batch_bytes += size+ if batches:+ for decisions in async_to_sync(self._batches)(spec, batches):+ for text, decision in decisions.items():+ self.cache[_DecisionKey(question=question_key, text=text)] = decision+ null: object = (None, [], None) if isinstance(spec.question, ChoiceQuestion) else None+ return [+ null if value is None else self.cache[_DecisionKey(question=question_key, text=cast(str, value))]+ for value in values+ ]+++class _LocalFinder(PromptJevFinder):+ def visit_select_query(self, node: ast.SelectQuery) -> None:+ pass+++class PromptJevBudget(TraversingVisitor):+ def __init__(self) -> None:+ self.decisions = 0++ def visit_select_set_query(self, node: ast.SelectSetQuery) -> None:+ initial = node.initial_select_query+ # A WITH clause on the first branch stays in scope for every later branch, so its CTEs are+ # counted once across the whole set. Counting them per branch reserves nothing for a CTE+ # that only a later branch reads, and the query then spends inference the budget never+ # approved.+ if not isinstance(initial, ast.SelectQuery) or not initial.ctes:+ super().visit_select_set_query(node)+ return+ without_ctes = clone_expr(node)+ cast(ast.SelectQuery, without_ctes.initial_select_query).ctes = None+ for cte in _CTEReferences.used(without_ctes, initial.ctes).values():+ self.visit(cte)+ super().visit_select_set_query(without_ctes)++ def visit_select_query(self, node: ast.SelectQuery) -> None:+ node = clone_expr(node)+ ctes = node.ctes or {}+ node.ctes = None+ node.ctes = _CTEReferences.used(node, ctes) or None+ finder = _LocalFinder()+ for column in node.select:+ finder.visit(column)+ if finder.calls:+ rows = MAX_ROWS+ if node.limit is not None:+ if (+ not isinstance(node.limit, ast.Constant)+ or type(node.limit.value) is not int+ or not 0 <= node.limit.value <= MAX_ROWS+ ):+ raise QueryError(f"__preview_promptJev LIMIT must be an integer literal between 0 and {MAX_ROWS}.")+ rows = node.limit.value+ # Reserve the worst case before any stage runs, including stages that depend on earlier decisions.+ self.decisions += rows * len(finder.calls)+ if self.decisions > MAX_DECISIONS:+ raise QueryError(+ f"__preview_promptJev exceeds the query budget of {MAX_DECISIONS} row evaluations across all columns and SELECTs. "+ f"This query reserves {self.decisions}. Add smaller LIMITs to the SELECTs containing Jev calls, "+ "or use fewer Jev columns. A SELECT without LIMIT reserves 1000 rows per Jev column."+ )+ super().visit_select_query(node)+++class _AliasReferences(TraversingVisitor):+ def __init__(self, aliases: set[str]) -> None:+ self.aliases = aliases+ self.in_scope = False++ def visit_field(self, node: ast.Field) -> None:+ if node.chain and node.chain[0] in self.aliases:+ raise QueryError("Read __preview_promptJev result aliases from an outer query.")++ def visit_select_query(self, node: ast.SelectQuery) -> None:+ # HogQL resolves a field only against its own SELECT, so fields in nested SELECTs cannot read these aliases.+ if not self.in_scope:+ self.in_scope = True+ super().visit_select_query(node)+++class _CTEReferences(TraversingVisitor):+ def __init__(self) -> None:+ self.names: set[str | int] = set()++ def visit_field(self, node: ast.Field) -> None:+ self.names.update(node.chain[:1])++ @classmethod+ def used(cls, query: ast.Expr, ctes: dict[str, ast.CTE]) -> dict[str, ast.CTE]:+ # ClickHouse does not run a CTE that nothing reads, so inference must not run for it either.+ references = cls()+ references.visit(query)+ used: set[str] = set()+ while pending := [name for name in ctes if name in references.names and name not in used]:+ for name in pending:+ used.add(name)+ references.visit(ctes[name])+ return {name: cte for name, cte in ctes.items() if name in used}+++class PromptJevPlanner(CloningVisitor):+ def __init__(+ self,+ *,+ execute: Callable[[ast.SelectQuery], PromptJevSource],+ runner: PromptJevRunner,+ tables: list[PromptJevTable],+ ) -> None:+ super().__init__(clear_types=True)+ self.execute = execute+ self.runner = runner+ self.tables = tables+ self.ctes: dict[str, ast.CTE] = {}++ def visit_select_set_query(self, node: ast.SelectSetQuery) -> ast.SelectSetQuery:+ initial = node.initial_select_query+ # A WITH clause on the first branch stays in scope for every later branch, so its CTEs are+ # planned once across the whole set. Planning them per branch drops a CTE that only a later+ # branch reads, and that branch then cannot find its table.+ if not isinstance(initial, ast.SelectQuery) or not initial.ctes:+ return cast(ast.SelectSetQuery, super().visit_select_set_query(node))+ previous = self.ctes+ self.ctes = dict(previous)+ try:+ without_ctes = clone_expr(node)+ cast(ast.SelectQuery, without_ctes.initial_select_query).ctes = None+ for name, cte in _CTEReferences.used(without_ctes, initial.ctes).items():+ self.ctes[name] = self.visit(cte)+ return cast(ast.SelectSetQuery, super().visit_select_set_query(without_ctes))+ finally:+ self.ctes = previous++ def visit_select_query(self, node: ast.SelectQuery) -> ast.SelectQuery:+ previous = self.ctes+ self.ctes = dict(previous)+ try:+ without_ctes = clone_expr(node)+ without_ctes.ctes = None+ for name, cte in _CTEReferences.used(without_ctes, node.ctes or {}).items():+ self.ctes[name] = self.visit(cte)+ query = cast(ast.SelectQuery, super().visit_select_query(without_ctes))+ query.ctes = dict(self.ctes) or None+ local = _LocalFinder()+ for column in query.select:+ local.visit(column)+ if not local.calls:+ return query+ if (+ query.distinct+ or query.group_by+ or query.group_by_mode+ or query.having+ or query.qualify+ or query.order_by+ or query.limit_by+ or query.limit_percent+ or query.limit_with_ties+ ):+ raise QueryError(+ "Apply grouping, sorting, and DISTINCT in a query outside the __preview_promptJev SELECT."+ )+ specs: dict[int, PromptJevCall] = {}+ aliases: set[str] = set()+ for i, column in enumerate(query.select):+ if (+ isinstance(column, ast.Alias)+ and isinstance(column.expr, ast.Call)+ and column.expr.name.lower() == "__preview_promptjev"+ ):+ specs[i] = PromptJevCall.parse(column.expr)+ aliases.add(column.alias)+ elif isinstance(column, ast.Field) and "*" in column.chain:+ raise QueryError("List columns explicitly in a __preview_promptJev SELECT instead of using '*'.")+ if len(specs) != len(local.calls):+ raise QueryError("Use __preview_promptJev as a named SELECT column, then read it from an outer query.")+ source = clone_expr(query)+ for i, spec in specs.items():+ source.select[i] = ast.Alias(alias=cast(ast.Alias, query.select[i]).alias, expr=clone_expr(spec.input))+ if PromptJevFinder.contains(source):+ raise QueryError(+ "Use __preview_promptJev only in SELECT columns. Filter its results in an outer query."+ )+ _AliasReferences(aliases).visit(source)+ if source.limit is None:+ source.limit = ast.Constant(value=MAX_ROWS + 1)+ elif (+ not isinstance(source.limit, ast.Constant)+ or type(source.limit.value) is not int+ or not 0 <= source.limit.value <= MAX_ROWS+ ):+ raise QueryError(f"__preview_promptJev LIMIT must be an integer literal between 0 and {MAX_ROWS}.")+ result = self.execute(source)+ response = result.response+ if response.error:+ raise QueryError(response.error)+ rows: list[list[object]] = [list(row) for row in response.results or []]+ if len(rows) > MAX_ROWS:+ raise QueryError(f"__preview_promptJev reads at most {MAX_ROWS} rows. Add a LIMIT to its SELECT.")+ names = response.columns or []+ if len(names) != len(query.select) or len(set(names)) != len(names):+ raise QueryError("Give each column in the __preview_promptJev SELECT a unique name.")+ kinds = [str(kind) for _, kind in response.types or []]+ inputs = {i: [row[i] for row in rows] for i in specs}+ self.runner.check_budget([(spec, inputs[i]) for i, spec in specs.items()])+ for i, spec in specs.items():+ values = self.runner.evaluate(spec, inputs[i])+ for row, value in zip(rows, values):+ row[i] = value+ kinds[i] = spec.clickhouse_type+ columns = [+ PromptJevColumn(+ name=name,+ clickhouse_type=kinds[i],+ hogql_type=None if i in specs else result.column_types.get(name),+ )+ for i, name in enumerate(names)+ ]+ table = PromptJevTable(name=f"__prompt_jev_{uuid.uuid4().hex}", columns=columns, rows=rows)+ self.tables.append(table)+ return ast.SelectQuery(+ select=[ast.Field(chain=[name]) for name in names],+ select_from=ast.JoinExpr(table=ast.Field(chain=[table.name])),+ # The source query consumed the LIMIT and the OFFSET. Keeping the limit stops the+ # default row limit from replacing it; re-applying the offset would skip rows twice.+ limit=clone_expr(query.limit) if query.limit is not None else None,+ )+ finally:+ self.ctes = previous++ def visit_call(self, node: ast.Call) -> ast.Call:+ # Binding validates every call, including ones whose SELECT has no rows.+ if node.name.lower() == "__preview_promptjev":+ PromptJevCall.parse(node)+ return cast(ast.Call, super().visit_call(node))+++def validate_prompt_jev_access(team: "Team") -> None:+ if settings.CLICKHOUSE_USE_HTTP or team.pk in settings.CLICKHOUSE_USE_HTTP_PER_TEAM:+ raise QueryError(+ "__preview_promptJev requires the native ClickHouse connection. Ask your administrator to configure it."+ )+ if not feature_enabled_or_false(+ "hogql-prompt-jev",+ str(team.uuid),+ groups={"organization": str(team.organization_id), "project": str(team.pk)},+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team.pk)},+ },+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ ):+ raise QueryError("__preview_promptJev is not enabled for this project. Contact support to request access.")diff --git a/posthog/llm/system_one_client.py b/posthog/llm/system_one_client.pyindex 3f560a9c09fd..4060f9134a06 100644--- a/posthog/llm/system_one_client.py+++ b/posthog/llm/system_one_client.py@@ -59,12 +59,15 @@ class GatewaySystemOneClient:model: strtimeout: float- def decide(self, *, state: JsonValue, questions: Mapping[str, Question]) -> SystemOneResult:+ def _validate_questions(self, questions: Mapping[str, Question]) -> None:if not 1 <= len(questions) <= GATEWAY_MAX_QUESTIONS:raise ValueError(f"A System One request needs between 1 and {GATEWAY_MAX_QUESTIONS} questions")for question_id, question in questions.items():if isinstance(question, ChoiceQuestion) and len(question.criteria) > GATEWAY_MAX_CHOICE_OPTIONS:raise ValueError(f"{question_id!r} has more than {GATEWAY_MAX_CHOICE_OPTIONS} options")++ def decide(self, *, state: JsonValue, questions: Mapping[str, Question]) -> SystemOneResult:+ self._validate_questions(questions)try:with httpx.Client(trust_env=False, timeout=self.timeout) as client:response = client.post(@@ -74,6 +77,22 @@ class GatewaySystemOneClient:)except httpx.HTTPError as exc:raise SystemOneRequestFailed(f"The ai-gateway was not reached: {exc.__class__.__name__}") from exc+ return self._parse_response(response, questions)++ async def adecide(self, *, state: JsonValue, questions: Mapping[str, Question]) -> SystemOneResult:+ self._validate_questions(questions)+ try:+ async with httpx.AsyncClient(trust_env=False, timeout=self.timeout) as client:+ response = await client.post(+ self.url,+ json=build_system_one_body(state=state, questions=questions, model=self.model),+ headers={**self.headers, "Authorization": f"Bearer {self.api_key}"},+ )+ except httpx.HTTPError as exc:+ raise SystemOneRequestFailed(f"The ai-gateway was not reached: {exc.__class__.__name__}") from exc+ return self._parse_response(response, questions)++ def _parse_response(self, response: httpx.Response, questions: Mapping[str, Question]) -> SystemOneResult:if response.status_code != 200:# The error body can echo the state, so it stays out of the exception that gets logged.raise SystemOneRequestFailed(diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 5ba6bc6593a1..9833e052b849 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1305,6 +1305,10 @@ AI_GATEWAY_INTERNAL_TOKEN = get_from_env("AI_GATEWAY_INTERNAL_TOKEN", "")AI_GATEWAY_URL = get_from_env("AI_GATEWAY_URL", "")AI_GATEWAY_API_KEY = get_from_env("AI_GATEWAY_API_KEY", "")+# Decision model behind the preview HogQL `__preview_promptJev` function. Per environment, so a+# different model can be measured without a code change.+HOGQL_PROMPT_JEV_MODEL = get_from_env("HOGQL_PROMPT_JEV_MODEL", "posthog/hogference/jevk5-fp8-0.2")+# Projected into gateway_credential.json: a JSON team_id -> tier map# ("free"/"pro"/"enterprise") for the gateway's rate-limit bucket.# Parsed defensively rather than with type_cast=json.loads: that runs at settings