: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
fix(aio): make Hog eval templates target-independent (#72353)
Radu Raicea0227a270a0ad
diff --git a/posthog/hogql_queries/ai/utils.py b/posthog/hogql_queries/ai/utils.pyindex 5c0f20e9004f..ca85c6131047 100644--- a/posthog/hogql_queries/ai/utils.py+++ b/posthog/hogql_queries/ai/utils.py@@ -12,7 +12,7 @@ from posthog.caching.utils import ThresholdMode, is_stalefrom posthog.hogql_queries.ai.ai_property_rewriter import AI_PROPERTY_TO_COLUMNfrom posthog.models.team.team import Team-_HEAVY_PROPERTIES: frozenset[str] = frozenset(+HEAVY_PROPERTY_NAMES: frozenset[str] = frozenset({"$ai_input","$ai_output",@@ -22,7 +22,11 @@ _HEAVY_PROPERTIES: frozenset[str] = frozenset("$ai_tools",})-HEAVY_COLUMN_TO_PROPERTY: dict[str, str] = {v: k for k, v in AI_PROPERTY_TO_COLUMN.items() if k in _HEAVY_PROPERTIES}+HEAVY_COLUMN_TO_PROPERTY: dict[str, str] = {+ column_name: property_name+ for property_name, column_name in AI_PROPERTY_TO_COLUMN.items()+ if property_name in HEAVY_PROPERTY_NAMES+}# Ordered tuple of heavy column names. Used for unpacking event tuples from ClickHouse.# Keep in sync with the SQL tuple in trace_query_runner.py _build_query().diff --git a/posthog/temporal/ai_observability/evaluation_hog.py b/posthog/temporal/ai_observability/evaluation_hog.pyindex 2cd9d23159ed..c3943979cd30 100644--- a/posthog/temporal/ai_observability/evaluation_hog.py+++ b/posthog/temporal/ai_observability/evaluation_hog.py@@ -6,6 +6,7 @@ import structlogimport temporaliofrom temporalio.exceptions import ApplicationError+from posthog.hogql_queries.ai.utils import HEAVY_PROPERTY_NAMESfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.evaluation_errors import (require_user_error_spec,@@ -13,8 +14,10 @@ from posthog.temporal.ai_observability.evaluation_errors import ()from posthog.temporal.ai_observability.evaluation_event_io import extract_event_iofrom posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult+from posthog.temporal.ai_observability.message_utils import extract_text_from_messagesfrom common.hogvm.python.execute import execute_bytecode+from common.hogvm.python.operation import Operationfrom common.hogvm.python.utils import HogVMException, HogVMMemoryExceededException, HogVMRuntimeExceededExceptionlogger = structlog.get_logger(__name__)@@ -31,6 +34,90 @@ def coerce_hog_io_value(value: Any) -> str:return "" if value is None or value == "" else str(value)+def _extract_hog_message_text(messages: Any) -> str:+ if messages is None or isinstance(messages, str | list | dict):+ return extract_text_from_messages(messages)+ return str(messages)+++def _get_hog_output_choice_content(choice: dict[str, Any]) -> Any:+ for key in ("content", "refusal", "text"):+ value = choice.get(key)+ if value is None or (isinstance(value, str | list | dict) and not value):+ continue+ return value+ return None+++def _normalize_hog_output_choice(choice: dict[str, Any]) -> dict[str, Any] | None:+ message = choice.get("message")+ if isinstance(message, dict):+ choice = message++ if not any(key in choice for key in ("content", "refusal", "text", "tool_calls")):+ return choice++ content = _get_hog_output_choice_content(choice)+ if content is None and not choice.get("tool_calls"):+ return None+ if content is not None and not isinstance(content, str | list | dict):+ content = coerce_hog_io_value(content)+ return {"content": content, "tool_calls": choice.get("tool_calls")}+++def _extract_hog_output_text(output: Any) -> str:+ if isinstance(output, dict) and isinstance(output.get("choices"), list):+ output = output["choices"]++ messages: list[Any] = []+ for choice in output if isinstance(output, list) else [output]:+ if isinstance(choice, dict):+ choice = _normalize_hog_output_choice(choice)+ if choice is None:+ continue+ elif not isinstance(choice, str):+ choice = coerce_hog_io_value(choice)+ messages.append(choice)+ return _extract_hog_message_text(messages)+++def hog_bytecode_references_global(bytecode: list[Any], global_name: str) -> bool:+ """Return whether compiled Hog bytecode reads a specific global."""+ return any(+ operation == Operation.GET_GLOBAL and index > 0 and bytecode[index - 1] == global_name+ for index, operation in enumerate(bytecode)+ )+++def build_hog_event_global(+ event_type: str,+ properties: dict[str, Any],+ *,+ event_uuid: Any,+ timestamp: Any,+ include_text: bool = True,+) -> dict[str, Any]:+ """Build the per-event global shared by generation and trace evaluations.++ With text projections enabled, this is the target-independent event shape exposed through+ `evaluation_events`. The trace-only `events` compatibility global disables them so saved+ source keeps its original shape and memory cost.+ """+ input_raw, output_raw = extract_event_io(event_type, properties)+ event_global: dict[str, Any] = {+ "uuid": event_uuid,+ "event": event_type,+ "timestamp": timestamp,+ "input": coerce_hog_io_value(input_raw),+ "output": coerce_hog_io_value(output_raw),+ "properties": {key: value for key, value in properties.items() if key not in HEAVY_PROPERTY_NAMES},+ }+ if include_text:+ event_global["input_text"] = _extract_hog_message_text(input_raw)+ event_global["output_text"] = _extract_hog_output_text(output_raw)+ return event_global++def execute_hog_eval_bytecode(bytecode: list, globals_dict: dict[str, Any], allows_na: bool) -> dict[str, Any]:"""Run compiled Hog eval bytecode against pre-built globals and shape the verdict.@@ -97,6 +184,7 @@ def run_hog_eval(bytecode: list, event_data: dict[str, Any], allows_na: bool = Finput_raw, output_raw = extract_event_io(event_type, properties)globals_dict: dict[str, Any] = {+ # Generation-only compatibility globals kept for saved Hog source."input": coerce_hog_io_value(input_raw),"output": coerce_hog_io_value(output_raw),"properties": properties,@@ -106,6 +194,22 @@ def run_hog_eval(bytecode: list, event_data: dict[str, Any], allows_na: bool = F"distinct_id": event_data.get("distinct_id", ""),},}+ if hog_bytecode_references_global(bytecode, "target"):+ globals_dict["target"] = {+ "type": "generation",+ "id": event_data.get("uuid", ""),+ "total_cost_usd": properties.get("$ai_total_cost_usd"),+ "total_latency_seconds": properties.get("$ai_latency"),+ }+ if hog_bytecode_references_global(bytecode, "evaluation_events"):+ globals_dict["evaluation_events"] = [+ build_hog_event_global(+ event_type,+ properties,+ event_uuid=event_data.get("uuid", ""),+ timestamp=event_data.get("timestamp"),+ )+ ]return execute_hog_eval_bytecode(bytecode, globals_dict, allows_na=allows_na)diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.pyindex 037a95c600ee..8daf2f857832 100644--- a/posthog/temporal/ai_observability/run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py@@ -39,8 +39,11 @@ from posthog.temporal.ai_observability.evaluation_errors import (require_user_error_spec,status_reason_detail_for_terminal_user_error,)-from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io-from posthog.temporal.ai_observability.evaluation_hog import coerce_hog_io_value, execute_hog_eval_bytecode+from posthog.temporal.ai_observability.evaluation_hog import (+ build_hog_event_global,+ execute_hog_eval_bytecode,+ hog_bytecode_references_global,+)from posthog.temporal.ai_observability.evaluation_llm_judge import (LLM_JUDGE_RETRY_POLICY,call_llm_judge,@@ -90,18 +93,6 @@ MAX_TRACE_EVAL_EVENTS = 500# much, so we cap lower to bound cost. Over budget, the formatter uniformly samples lines.JUDGE_TRACE_MAX_CHARS = 150_000-# Heavy payload keys are dropped from per-event `properties` in Hog globals — their content-# is already exposed via the per-event `input`/`output` strings, and duplicating them doubles-# HogVM memory pressure on large traces.-HEAVY_TRACE_PROPERTY_KEYS = (- "$ai_input",- "$ai_output",- "$ai_output_choices",- "$ai_input_state",- "$ai_output_state",- "$ai_tools",-)-# Written against ai_events; query_ai_events rewrites it for the events table when ai_events# returns nothing. HAVING makes a zero count return no rows, which both triggers the events-table# fallback and keeps "no events" distinguishable without a second query.@@ -258,32 +249,54 @@ def format_trace_for_judge(trace: LLMTrace) -> str:return text-def build_trace_hog_globals(trace: LLMTrace, trace_id: str) -> dict[str, Any]:+def build_trace_hog_globals(trace: LLMTrace, trace_id: str, *, bytecode: list[Any] | None = None) -> dict[str, Any]:"""Build Hog globals for a trace-level eval.- `events` carries every trace event in chronological order with stringified input/output.- Sources read per-event io off `events`; there is no trace-level `input`/`output` because- a single synthesized pair isn't meaningful across a whole trace and wouldn't match what- the trace view shows.+ `events` and `trace` keep their original shapes for saved trace Hog source. New target-independent+ source uses `evaluation_events`, which adds readable text projections, and `target`.++ Existing bytecode receives the original globals. Bytecode that uses a new shared global only+ builds the event collections it references, avoiding duplicate HogVM and worker memory cost."""- events_globals: list[dict[str, Any]] = []- for event in trace.events or []:- props = event.properties- input_raw, output_raw = extract_event_io(event.event, props)- events_globals.append(- {- "uuid": event.id,- "event": event.event,- "timestamp": event.createdAt,- "input": coerce_hog_io_value(input_raw),- "output": coerce_hog_io_value(output_raw),- "properties": {k: v for k, v in props.items() if k not in HEAVY_TRACE_PROPERTY_KEYS},- }- )- return {- "events": events_globals,- "trace": {"id": trace_id, "event_count": len(events_globals)},+ trace_events = trace.events or []+ references_target = bytecode is not None and hog_bytecode_references_global(bytecode, "target")+ references_events = bytecode is not None and hog_bytecode_references_global(bytecode, "events")+ references_evaluation_events = bytecode is not None and hog_bytecode_references_global(+ bytecode, "evaluation_events"+ )+ can_skip_compatibility_events = (references_target or references_evaluation_events) and not references_events+ globals_dict: dict[str, Any] = {+ "trace": {"id": trace_id, "event_count": len(trace_events)},}+ if bytecode is None or references_target:+ globals_dict["target"] = {+ "type": "trace",+ "id": trace_id,+ "total_cost_usd": trace.totalCost,+ "total_latency_seconds": trace.totalLatency,+ }+ if bytecode is None or not can_skip_compatibility_events:+ globals_dict["events"] = [+ build_hog_event_global(+ event.event,+ event.properties,+ event_uuid=event.id,+ timestamp=event.createdAt,+ include_text=False,+ )+ for event in trace_events+ ]+ if bytecode is None or references_evaluation_events:+ globals_dict["evaluation_events"] = [+ build_hog_event_global(+ event.event,+ event.properties,+ event_uuid=event.id,+ timestamp=event.createdAt,+ )+ for event in trace_events+ ]+ return globals_dict@temporalio.activity.defn@@ -350,7 +363,7 @@ async def execute_trace_hog_eval_activity(inputs: ExecuteTraceEvaluationInputs))if outcome.skip_reason or outcome.trace is None:return None, outcome.skip_reason or "trace_not_found"- globals_dict = build_trace_hog_globals(outcome.trace, inputs.trace_id)+ globals_dict = build_trace_hog_globals(outcome.trace, inputs.trace_id, bytecode=bytecode)return execute_hog_eval_bytecode(bytecode, globals_dict, allows_na=allows_na), Noneresult, skip_reason = await database_sync_to_async(_execute, thread_sensitive=False)()diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex d8902a172998..ea6571c26e97 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -1451,7 +1451,12 @@ class TestExecuteHogEvalActivity:from posthog.cdp.validation import compile_hog- source = "let out := output; if (out == 'test output') { return true } return false"+ source = """+ return output == 'test output'+ and length(evaluation_events) == 1+ and evaluation_events.1.output == output+ and target.type == 'generation'+ """bytecode = compile_hog(source, "destination")evaluation = {@@ -1783,6 +1788,19 @@ class TestRunHogEvalAllowsNA:def _event_data(self) -> dict[str, Any]:return create_mock_event_data(team_id=1)+ @patch("posthog.temporal.ai_observability.evaluation_hog.execute_hog_eval_bytecode")+ def test_saved_generation_source_only_builds_compatibility_globals(self, mock_execute):+ mock_execute.return_value = {"verdict": True, "reasoning": "", "error": None}+ bytecode = self.compile_hog(+ "return output == 'evaluation_events' or output == 'target'",+ "destination",+ )++ run_hog_eval(bytecode, self._event_data())++ globals_dict = mock_execute.call_args.args[1]+ assert set(globals_dict) == {"input", "output", "properties", "event"}+@parameterized.expand([("true_result", "return true", True, True),diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.pyindex e23eedfc590f..cd1e22b6f8fb 100644--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py@@ -15,6 +15,7 @@ from products.ai_observability.backend.models.evaluation_config import Evaluatiofrom products.ai_observability.backend.models.evaluations import Evaluationfrom products.ai_observability.backend.models.provider_keys import LLMProviderKey+from .evaluation_hog import execute_hog_eval_bytecodefrom .evaluation_llm_judge import BooleanEvalResultfrom .evaluation_types import EvaluationActivityResultfrom .run_trace_evaluation import (@@ -180,17 +181,40 @@ class TestBuildTraceHogGlobals:create_trace_event("$ai_generation", **{"$ai_input": "first question", "$ai_output": "first answer"}),create_trace_event("$ai_generation", **{"$ai_input": "second question", "$ai_output": "final answer"}),]- trace = create_trace(events)+ trace = create_trace(events, totalCost=0.03, totalLatency=2.5)globals_dict = build_trace_hog_globals(trace, "trace-123")assert "input" not in globals_dictassert "output" not in globals_dictassert globals_dict["trace"] == {"id": "trace-123", "event_count": 3}+ assert globals_dict["target"] == {+ "type": "trace",+ "id": "trace-123",+ "total_cost_usd": 0.03,+ "total_latency_seconds": 2.5,+ }assert len(globals_dict["events"]) == 3assert globals_dict["events"][1]["event"] == "$ai_generation"assert globals_dict["events"][1]["input"] == "first question"assert globals_dict["events"][2]["output"] == "final answer"+ assert "input_text" not in globals_dict["events"][1]+ assert "output_text" not in globals_dict["events"][2]+ assert globals_dict["evaluation_events"][1]["input_text"] == "first question"+ assert globals_dict["evaluation_events"][2]["output_text"] == "final answer"++ def test_saved_events_source_only_builds_compatibility_events(self):+ bytecode = compile_hog("return length(events) == 1 and events.1.output == 'answer'", "destination")+ trace = create_trace(+ [create_trace_event("$ai_generation", **{"$ai_input": "question", "$ai_output": "answer"})]+ )++ globals_dict = build_trace_hog_globals(trace, "trace-123", bytecode=bytecode)+ result = execute_hog_eval_bytecode(bytecode, globals_dict, allows_na=False)++ assert set(globals_dict) == {"events", "trace"}+ assert set(globals_dict["events"][0]) == {"uuid", "event", "timestamp", "input", "output", "properties"}+ assert result == {"verdict": True, "reasoning": "", "error": None}def test_strips_heavy_keys_from_event_properties(self):events = [diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.pyindex dfeb8f0172b7..afd9eda4945c 100644--- a/products/ai_observability/backend/api/evaluations.py+++ b/products/ai_observability/backend/api/evaluations.py@@ -1,4 +1,3 @@-import jsonfrom typing import Anyfrom django.db import transaction@@ -14,11 +13,18 @@ from rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response+from posthog.hogql import ast+from posthog.hogql.property import property_to_expr+from posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.monitoring import monitorfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer+from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.event_usage import report_user_action+from posthog.hogql_queries.ai.ai_table_resolver import AIEventsUnavailableError, query_ai_events+from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, merge_heavy_properties+from posthog.models.team import Teamfrom posthog.permissions import AccessControlPermissionfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.temporal.ai_observability.message_utils import extract_text_from_messages@@ -850,13 +856,6 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbiallows_na = serializer.validated_data["allows_na"]conditions = serializer.validated_data.get("conditions", [])- from posthog.hogql import ast- from posthog.hogql.property import property_to_expr- from posthog.hogql.query import execute_hogql_query-- from posthog.clickhouse.query_tagging import Feature, Product, tag_queries- from posthog.models.team import Team-try:bytecode = compile_ai_observability_hog(source, "destination")except serializers.ValidationError as e:@@ -905,17 +904,30 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbiast.Field(chain=["event"]),ast.Field(chain=["properties"]),ast.Field(chain=["distinct_id"]),+ ast.Field(chain=["timestamp"]),+ *[ast.Field(chain=[column_name]) for column_name in HEAVY_COLUMN_NAMES],],- select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),- where=ast.And(exprs=where_exprs),+ select_from=ast.JoinExpr(table=ast.Field(chain=["posthog", "ai_events"]), alias="ai_events"),+ where=ast.Placeholder(expr=ast.Field(chain=["where_clause"])),order_by=[ast.OrderExpr(expr=ast.Field(chain=["timestamp"]), order="DESC")],limit=ast.Constant(value=sample_count),)tag_queries(product=Product.LLM_ANALYTICS, feature=Feature.QUERY)- response = execute_hogql_query(query=query, team=team, limit_context=None)+ try:+ response = query_ai_events(+ query=query,+ placeholders={"where_clause": ast.And(exprs=where_exprs)},+ team=team,+ query_type="EvaluationTestHog",+ fall_back_to_events=False,+ limit_context=None,+ )+ query_results = response.results or []+ except AIEventsUnavailableError:+ query_results = []- if not response.results:+ if not query_results:report_user_action(request.user,"llma evaluation hog code tested",@@ -936,20 +948,21 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbireturn Response({"results": [], "message": "No recent AI events found in the last 7 days"})results = []- for row in response.results:+ for row in query_results:event_uuid = str(row[0])event_type = row[1]- properties = row[2]+ timestamp = row[4]+ heavy_values = row[5 : 5 + len(HEAVY_COLUMN_NAMES)]+ heavy_columns = dict(zip(HEAVY_COLUMN_NAMES, heavy_values, strict=True))+ properties = merge_heavy_properties(row[2], heavy_columns)distinct_id = row[3]- if isinstance(properties, str):- properties = json.loads(properties)-event_data = {"uuid": event_uuid,"event": event_type,"properties": properties,"distinct_id": distinct_id or "",+ "timestamp": timestamp,}result = run_hog_eval(bytecode, event_data, allows_na=allows_na)diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.pyindex 3f6ffc5834c7..5d327e3f6392 100644--- a/products/ai_observability/backend/api/test/test_evaluations.py+++ b/products/ai_observability/backend/api/test/test_evaluations.py@@ -1,3 +1,4 @@+import jsonfrom uuid import uuid4from posthog.test.base import APIBaseTest@@ -9,6 +10,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom rest_framework import status+from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, HEAVY_COLUMN_TO_PROPERTYfrom posthog.models import Organization, Project, Team, Userfrom products.ai_observability.backend.api.evaluations import ModelConfigurationSerializer@@ -950,27 +952,47 @@ class TestEvaluationConfigsApi(APIBaseTest):class TestTestHogEndpoint(APIBaseTest):+ EVENT_TIMESTAMP = "2026-07-20T12:34:56Z"+def _mock_hogql_response(self, count=1):from posthog.hogql.query import HogQLQueryResponse+ heavy_property_values = {+ "$ai_input": json.dumps("What is 2+2?"),+ "$ai_output": json.dumps("4"),+ }+ heavy_values = tuple(+ heavy_property_values.get(HEAVY_COLUMN_TO_PROPERTY[column_name], "") for column_name in HEAVY_COLUMN_NAMES+ )rows = [(str(uuid4()),"$ai_generation",- {"$ai_input": "What is 2+2?", "$ai_output": "4"},+ {"$ai_model": "gpt-5-mini"},"user-1",+ self.EVENT_TIMESTAMP,+ *heavy_values,)for _ in range(count)]- return HogQLQueryResponse(results=rows, columns=["uuid", "event", "properties", "distinct_id"])+ return HogQLQueryResponse(+ results=rows,+ columns=["uuid", "event", "properties", "distinct_id", "timestamp", *HEAVY_COLUMN_NAMES],+ )- @patch("posthog.hogql.query.execute_hogql_query")- def test_test_hog_compiles_and_executes(self, mock_query):+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")+ def test_test_hog_loads_ai_input_and_output(self, mock_query):mock_query.return_value = self._mock_hogql_response(2)response = self.client.post(f"/api/environments/{self.team.id}/evaluations/test_hog/",- {"source": "return length(output) > 0", "sample_count": 2},+ {+ "source": (+ "return evaluation_events.1.output_text == '4' "+ f"and evaluation_events.1.timestamp == '{self.EVENT_TIMESTAMP}'"+ ),+ "sample_count": 2,+ },)self.assertEqual(response.status_code, status.HTTP_200_OK)results = response.json()["results"]@@ -982,6 +1004,13 @@ class TestTestHogEndpoint(APIBaseTest):self.assertIn("error", r)self.assertTrue(r["result"])self.assertIsNone(r["error"])+ self.assertEqual(r["input_preview"], "What is 2+2?")+ self.assertEqual(r["output_preview"], "4")++ query = mock_query.call_args.kwargs["query"]+ self.assertEqual(query.select_from.table.chain, ["posthog", "ai_events"])+ self.assertEqual(query.select[4].chain, ["timestamp"])+ self.assertEqual([field.chain for field in query.select[5:]], [[name] for name in HEAVY_COLUMN_NAMES])def test_test_hog_compilation_error(self):response = self.client.post(@@ -998,7 +1027,7 @@ class TestTestHogEndpoint(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- @patch("posthog.hogql.query.execute_hogql_query")+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")def test_test_hog_no_events(self, mock_query):mock_query.return_value = self._mock_hogql_response(0)@@ -1010,7 +1039,7 @@ class TestTestHogEndpoint(APIBaseTest):self.assertEqual(response.json()["results"], [])self.assertIn("message", response.json())- @patch("posthog.hogql.query.execute_hogql_query")+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")def test_test_hog_handles_runtime_error(self, mock_query):mock_query.return_value = self._mock_hogql_response(1)@@ -1024,7 +1053,7 @@ class TestTestHogEndpoint(APIBaseTest):self.assertIsNone(results[0]["result"])self.assertIn("Must return boolean", results[0]["error"])- @patch("posthog.hogql.query.execute_hogql_query")+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")def test_test_hog_uses_null_safe_comparisons(self, mock_query):mock_query.return_value = self._mock_hogql_response(1)diff --git a/products/ai_observability/backend/test_hog_eval_examples.py b/products/ai_observability/backend/test_hog_eval_examples.pyindex a817e328eb75..f1cffa1ed38d 100644--- a/products/ai_observability/backend/test_hog_eval_examples.py+++ b/products/ai_observability/backend/test_hog_eval_examples.py@@ -7,11 +7,16 @@ import jsonimport uuidfrom datetime import datetimefrom pathlib import Path+from typing import Anyfrom parameterized import parameterized+from posthog.schema import LLMTrace, LLMTraceEvent+from posthog.cdp.validation import compile_hog+from posthog.temporal.ai_observability.evaluation_hog import execute_hog_eval_bytecodefrom posthog.temporal.ai_observability.run_evaluation import run_hog_eval+from posthog.temporal.ai_observability.run_trace_evaluation import build_trace_hog_globalsEXAMPLES_PATH = Path(__file__).resolve().parents[1] / "frontend" / "evaluations" / "hogEvalExamples.json"EXAMPLES: list[dict] = json.loads(EXAMPLES_PATH.read_text())@@ -76,6 +81,32 @@ CLEAN_EVENT = _make_event(},],)+CLEAN_EVENT["properties"]["$ai_tools_called"] = "get_weather,get_news"+++def _make_clean_trace_globals(bytecode: list[Any]) -> dict[str, Any]:+ trace = LLMTrace(+ id="trace-123",+ createdAt=CLEAN_EVENT["timestamp"],+ distinctId="test-user",+ totalCost=0.01,+ totalLatency=1.5,+ events=[+ LLMTraceEvent(+ id="span-1",+ event="$ai_span",+ createdAt=CLEAN_EVENT["timestamp"],+ properties={"$ai_span_name": "agent"},+ ),+ LLMTraceEvent(+ id=CLEAN_EVENT["uuid"],+ event=CLEAN_EVENT["event"],+ createdAt=CLEAN_EVENT["timestamp"],+ properties=CLEAN_EVENT["properties"],+ ),+ ],+ )+ return build_trace_hog_globals(trace, "trace-123", bytecode=bytecode)class TestHogEvalExamplesCompile:@@ -96,6 +127,14 @@ class TestHogEvalExamplesRun:assert result["error"] is None, f"'{label}' errored: {result['error']}"assert isinstance(result["verdict"], bool), f"'{label}' returned non-bool: {result['verdict']}"+ @parameterized.expand(EXAMPLE_LABELS)+ def test_returns_bool_without_error_for_trace(self, label):+ bytecode = compile_hog(_get_source(label), "destination")+ result = execute_hog_eval_bytecode(bytecode, _make_clean_trace_globals(bytecode), allows_na=False)++ assert result["error"] is None, f"'{label}' errored for a trace: {result['error']}"+ assert isinstance(result["verdict"], bool), f"'{label}' returned non-bool for a trace: {result['verdict']}"+class TestHogEvalExamplesBehavior:@parameterized.expand(@@ -141,6 +180,93 @@ class TestHogEvalExamplesBehavior:assert result["verdict"] is Falseassert "exceeds budget" in result["reasoning"]+ def test_output_not_empty_fails_on_empty_choice_content(self):+ bytecode = compile_hog(_get_source("Output not empty"), "destination")+ event = _make_event(ai_output_choices=[{"message": {"role": "assistant", "content": ""}}])++ result = run_hog_eval(bytecode, event)++ assert result["verdict"] is False++ @parameterized.expand([("Output not empty",), ("Min output length",), ("Output quality",)])+ def test_generation_quality_checks_fail_without_generation_events(self, label: str) -> None:+ bytecode = compile_hog(_get_source(label), "destination")+ trace = LLMTrace(+ id="trace-123",+ createdAt=CLEAN_EVENT["timestamp"],+ distinctId="test-user",+ events=[+ LLMTraceEvent(+ id="span-1",+ event="$ai_span",+ createdAt=CLEAN_EVENT["timestamp"],+ properties={"$ai_span_name": "agent"},+ )+ ],+ )++ result = execute_hog_eval_bytecode(+ bytecode, build_trace_hog_globals(trace, trace.id, bytecode=bytecode), allows_na=False+ )++ assert result["verdict"] is False+ assert "No generation events found" in result["reasoning"]++ @parameterized.expand([([{"type": "text", "text": ""}],), ({"choices": [{"text": ""}]},)])+ def test_output_not_empty_fails_on_empty_text_choice(self, output_choices):+ bytecode = compile_hog(_get_source("Output not empty"), "destination")+ event = _make_event(ai_output_choices=output_choices)++ result = run_hog_eval(bytecode, event)++ assert result["verdict"] is False++ @parameterized.expand(+ [+ ("scalar", 42),+ ("boolean_choice", [False]),+ ("zero_content", [{"message": {"role": "assistant", "content": 0}}]),+ ]+ )+ def test_output_not_empty_passes_on_non_string_output(self, _name: str, output_choices: Any) -> None:+ bytecode = compile_hog(_get_source("Output not empty"), "destination")+ event = _make_event(ai_output_choices=output_choices)++ result = run_hog_eval(bytecode, event)++ assert result["verdict"] is True++ def test_refusal_detection_handles_openai_refusal_field(self):+ bytecode = compile_hog(_get_source("Refusal detection"), "destination")+ event = _make_event(+ ai_output_choices=[+ {"message": {"role": "assistant", "content": None, "refusal": "I cannot help with that request."}}+ ]+ )++ result = run_hog_eval(bytecode, event)++ assert result["verdict"] is False++ def test_error_detection_handles_string_error_flag(self):+ bytecode = compile_hog(_get_source("Error detection"), "destination")+ event = _make_event()+ event["properties"]["$ai_is_error"] = "true"++ result = run_hog_eval(bytecode, event)++ assert result["verdict"] is False++ def test_tools_called_does_not_match_names_only_mentioned_in_output(self):+ bytecode = compile_hog(_get_source("Tools called"), "destination")+ event = _make_event(+ ai_output_choices=[{"message": {"role": "assistant", "content": "I could call get_weather and get_news."}}]+ )++ result = run_hog_eval(bytecode, event)++ assert result["verdict"] is False+def test_conversation_length_fails_on_long(self):bytecode = compile_hog(_get_source("Conversation length"), "destination")long_conversation = [{"role": "user", "content": f"Message {i}"} for i in range(15)]@@ -149,6 +275,16 @@ class TestHogEvalExamplesBehavior:assert result["verdict"] is Falseassert "Exceeds limit" in result["reasoning"]+ def test_conversation_length_skips_truncated_json(self):+ bytecode = compile_hog(_get_source("Conversation length"), "destination")+ event = _make_event(ai_input='[{"role":"user","content":"truncated... [truncated]')++ result = run_hog_eval(bytecode, event)++ assert result["error"] is None+ assert result["verdict"] is True+ assert "Could not parse input" in result["reasoning"]+def test_regex_safety_fails_on_email(self):bytecode = compile_hog(_get_source("Regex safety checks"), "destination")event = _make_event(@@ -163,9 +299,9 @@ class TestHogEvalExamplesBehavior:bytecode = compile_hog(_get_source("Quickstart"), "destination")result = run_hog_eval(bytecode, CLEAN_EVENT)assert result["verdict"] is True- assert "[system] You are a helpful assistant." in result["reasoning"]- assert "[user] What is PostHog?" in result["reasoning"]- assert "Choice 0:" in result["reasoning"]+ assert "Event 0: $ai_generation" in result["reasoning"]+ assert "Input:" in result["reasoning"]+ assert "Output:" in result["reasoning"]assert "Model: gpt-4" in result["reasoning"]def test_na_guard_returns_null_when_model_missing(self):@@ -202,3 +338,29 @@ class TestHogEvalExamplesBehavior:assert result["verdict"] is Trueassert "Input: What is PostHog?" in result["reasoning"]assert "Output: PostHog is a product analytics platform." in result["reasoning"]++ @parameterized.expand([("Quickstart",), ("Print messages",)])+ def test_diagnostic_output_fits_temporal_payload_for_max_unicode_trace(self, label):+ bytecode = compile_hog(_get_source(label), "destination")+ unicode_text = "😀" * 101+ trace = LLMTrace(+ id="trace-123",+ createdAt=CLEAN_EVENT["timestamp"],+ distinctId="test-user",+ events=[+ LLMTraceEvent(+ id=f"generation-{index}",+ event="$ai_generation",+ createdAt=CLEAN_EVENT["timestamp"],+ properties={"$ai_input": unicode_text, "$ai_output": unicode_text},+ )+ for index in range(500)+ ],+ )++ result = execute_hog_eval_bytecode(+ bytecode, build_trace_hog_globals(trace, trace.id, bytecode=bytecode), allows_na=False+ )++ assert result["error"] is None+ assert len(json.dumps(result["reasoning"]).encode()) < 2 * 1024 * 1024diff --git a/products/ai_observability/backend/tools/run_hog_eval.py b/products/ai_observability/backend/tools/run_hog_eval.pyindex 50b4d49ab95a..56a59908df78 100644--- a/products/ai_observability/backend/tools/run_hog_eval.py+++ b/products/ai_observability/backend/tools/run_hog_eval.py@@ -18,11 +18,15 @@ TOOL_DESCRIPTION = """Test Hog evaluation code against sample events from the laReturns compilation errors if the code is invalid, or pass/fail/error results for each sample event.-The Hog code receives these globals:-- `input` (string): the LLM input (prompt/messages)-- `output` (string): the LLM output (completion/response)-- `properties` (object): all event properties-- `event` (object): event metadata with `uuid`, `event`, `distinct_id`+Write new evaluations using these globals:+- `evaluation_events` (array): the sampled event. Each item has `uuid`, `event`, `timestamp`,+ serialized `input` and `output`, readable `input_text` and `output_text`, and `properties`+ without large input, output, and tool payloads.+- `target` (object): the sampled generation's `type`, `id`, `total_cost_usd`, and+ `total_latency_seconds`.++Saved evaluations can still use the generation-only compatibility globals `input`, `output`,+`properties`, and `event`, but do not use them in new source that should also work for traces.The code must return a boolean: `true` for pass, `false` for fail.Use `print()` statements to output reasoning.@@ -67,6 +71,7 @@ class RunHogEvalTestTool(MaxTool):ast.Field(chain=["event"]),ast.Field(chain=["properties"]),ast.Field(chain=["distinct_id"]),+ ast.Field(chain=["timestamp"]),*[ast.Field(chain=[col]) for col in HEAVY_COLUMN_NAMES],],select_from=ast.JoinExpr(table=ast.Field(chain=["posthog", "ai_events"]), alias="ai_events"),@@ -106,7 +111,7 @@ class RunHogEvalTestTool(MaxTool):)# Parse all events first to collect property keys and build event data.- # Heavy columns trail the four base columns in row order — re-merge them+ # Heavy columns trail the five base columns in row order — re-merge them# into `properties` so the Hog body can read `properties.$ai_input` etc.# `merge_heavy_properties` skips NULL heavy slots, so on the events# fallback (heavy columns absent) it re-merges nothing, and on ai_events@@ -114,7 +119,7 @@ class RunHogEvalTestTool(MaxTool):parsed_events: list[dict[str, Any]] = []all_property_keys: set[str] = set()for row in response.results:- heavy_values = row[4 : 4 + len(HEAVY_COLUMN_NAMES)]+ heavy_values = row[5 : 5 + len(HEAVY_COLUMN_NAMES)]heavy_columns = dict(zip(HEAVY_COLUMN_NAMES, heavy_values))properties = merge_heavy_properties(row[2], heavy_columns)all_property_keys.update(properties.keys())@@ -124,6 +129,7 @@ class RunHogEvalTestTool(MaxTool):"event": row[1],"properties": properties,"distinct_id": row[3] or "",+ "timestamp": row[4],})diff --git a/products/ai_observability/backend/tools/test_run_hog_eval.py b/products/ai_observability/backend/tools/test_run_hog_eval.pyindex 7933e0d5d411..9f427d14098d 100644--- a/products/ai_observability/backend/tools/test_run_hog_eval.py+++ b/products/ai_observability/backend/tools/test_run_hog_eval.py@@ -11,6 +11,8 @@ from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMESfrom products.ai_observability.backend.tools.run_hog_eval import RunHogEvalTestTool+EVENT_TIMESTAMP = "2026-07-20T12:34:56Z"+def _make_event(ai_input=None,@@ -32,6 +34,7 @@ def _make_event(}),"test-user",+ EVENT_TIMESTAMP,*(None,) * len(HEAVY_COLUMN_NAMES),]@@ -50,6 +53,11 @@ class TestRunHogEvalTestTool(BaseTest):("valid_return_false", "return false;", False),("with_print", "print('checking'); return true;", True),("length_check", "return length(output) > 0;", True),+ (+ "shared_timestamp",+ f"return evaluation_events.1.timestamp == '{EVENT_TIMESTAMP}';",+ True,+ ),])@patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")@@ -150,6 +158,7 @@ class TestRunHogEvalTestTool(BaseTest):"$ai_metric",json.dumps({"$ai_input_state": "some input", "$ai_output_state": "some output"}),"test-user",+ EVENT_TIMESTAMP,]mock_response.results = [event_row]mock_query.return_value = mock_response@@ -170,7 +179,7 @@ class TestRunHogEvalTestTool(BaseTest):from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES# row[2]: stripped properties (no $ai_input).- # row[4..9]: native heavy column values, in HEAVY_COLUMN_NAMES order+ # row[5..10]: native heavy column values, in HEAVY_COLUMN_NAMES order# ("input", "output", "output_choices", "input_state", "output_state", "tools").stripped_props = json.dumps({"$ai_model": "gpt-4o"})heavy_input = '[{"role":"user","content":"recovered from native column"}]'@@ -179,6 +188,7 @@ class TestRunHogEvalTestTool(BaseTest):"$ai_generation",stripped_props,"test-user",+ EVENT_TIMESTAMP,heavy_input, # inputNone, # outputNone, # output_choices@@ -187,7 +197,7 @@ class TestRunHogEvalTestTool(BaseTest):None, # tools]# Sanity: row layout matches what the source expects.- assert len(row) == 4 + len(HEAVY_COLUMN_NAMES)+ assert len(row) == 5 + len(HEAVY_COLUMN_NAMES)mock_query.return_value = MagicMock(results=[row])tool = self._make_tool()diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsxindex 5c8f991878b4..1708a0022f57 100644--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx@@ -458,10 +458,18 @@ export function AIObservabilityEvaluation(): JSX.Element {<Link to="https://posthog.com/docs/hog" target="_blank">Hog code</Link>{' '}- against each generation. No LLM cost, instant results.+ against{' '}+ {evaluation.target === 'trace'+ ? 'the whole trace'+ : 'each generation'}+ . No LLM cost.</>) : (- 'Use an LLM to evaluate each generation against a natural-language prompt.'+ `Use an LLM to evaluate ${+ evaluation.target === 'trace'+ ? 'the whole trace'+ : 'each generation'+ } against a natural-language prompt.`)}</p>diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsxindex abe5c1f673f4..f4a25177c44f 100644--- a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx+++ b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx@@ -1,4 +1,5 @@import { useActions, useValues } from 'kea'+import { Fragment } from 'react'import { IconCheck, IconExternal, IconMinus, IconSparkles, IconWarning, IconX } from '@posthog/icons'import { LemonButton, LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'@@ -10,25 +11,166 @@ import { urls } from '~/scenes/urls'import { HOG_EVAL_EXAMPLES } from '../hogEvalExamples'import { llmEvaluationLogic } from '../llmEvaluationLogic'-import { HogTestResult } from '../types'+import type { EvaluationTarget, HogTestResult } from '../types'-const HOG_EVAL_GLOBALS = {- input: {- type: 'string',- description: 'The input to the LLM (prompt / messages)',+const GLOBAL_NAME_CODE_CLASS = 'font-medium text-sm text-primary bg-fill-highlight-100 px-1.5 py-0.5 rounded'+const PROPERTY_NAME_CODE_CLASS = 'font-medium text-xs text-primary bg-fill-highlight-100 px-1 py-0.5 rounded'++type HogGlobalFieldType = 'string' | 'number' | 'object'+type HogGlobalDescription = string | Record<EvaluationTarget, string>++interface HogGlobalFieldDefinition {+ name: string+ type: HogGlobalFieldType+ description: HogGlobalDescription+}++interface HogGlobalDefinition {+ name: string+ collection: 'array' | 'object'+ description: HogGlobalDescription+ fields: readonly HogGlobalFieldDefinition[]+}++interface MonacoHogGlobalField {+ type: HogGlobalFieldType+ description: string+}++type MonacoHogGlobal = Record<string, MonacoHogGlobalField> | Record<string, MonacoHogGlobalField>[]++const HOG_EVAL_COMMON_GLOBAL_DEFINITIONS: readonly HogGlobalDefinition[] = [+ {+ name: 'evaluation_events',+ collection: 'array',+ description: {+ generation: 'The event for the generation being evaluated.',+ trace: 'Every event in the trace being evaluated.',+ },+ fields: [+ { name: 'uuid', type: 'string', description: 'The event UUID.' },+ { name: 'event', type: 'string', description: 'The PostHog event name.' },+ { name: 'timestamp', type: 'string', description: 'When the event was captured.' },+ { name: 'input', type: 'string', description: 'The raw input serialized as a string.' },+ { name: 'output', type: 'string', description: 'The raw output serialized as a string.' },+ {+ name: 'input_text',+ type: 'string',+ description: 'Best-effort readable text extracted from the input.',+ },+ {+ name: 'output_text',+ type: 'string',+ description: 'Best-effort readable text extracted from the output.',+ },+ {+ name: 'properties',+ type: 'object',+ description: 'Event properties without large input, output, and tool payloads.',+ },+ ],},- output: {- type: 'string',- description: 'The output from the LLM (response / choices)',+ {+ name: 'target',+ collection: 'object',+ description: {+ generation: 'Details about the generation being evaluated.',+ trace: 'Details about the trace being evaluated.',+ },+ fields: [+ {+ name: 'type',+ type: 'string',+ description: {+ generation: 'The target type: generation.',+ trace: 'The target type: trace.',+ },+ },+ {+ name: 'id',+ type: 'string',+ description: {+ generation: 'The generation event UUID.',+ trace: 'The trace ID.',+ },+ },+ {+ name: 'total_cost_usd',+ type: 'number',+ description: {+ generation: 'The total cost for the generation in USD, when available.',+ trace: 'The total cost for the trace in USD, when available.',+ },+ },+ {+ name: 'total_latency_seconds',+ type: 'number',+ description: {+ generation: 'The total latency for the generation in seconds, when available.',+ trace: 'The total latency for the trace in seconds, when available.',+ },+ },+ ],},- properties: {- type: 'object',- description: 'All event properties',+]++function resolveHogGlobalDescription(description: HogGlobalDescription, target: EvaluationTarget): string {+ return typeof description === 'string' ? description : description[target]+}++function buildMonacoHogGlobals(target: EvaluationTarget): Record<string, MonacoHogGlobal> {+ return Object.fromEntries(+ HOG_EVAL_COMMON_GLOBAL_DEFINITIONS.map((globalDefinition) => {+ const fields = Object.fromEntries(+ globalDefinition.fields.map((field) => [+ field.name,+ {+ type: field.type,+ description: resolveHogGlobalDescription(field.description, target),+ },+ ])+ ) as Record<string, MonacoHogGlobalField>++ return [globalDefinition.name, globalDefinition.collection === 'array' ? [fields] : fields]+ })+ ) as Record<string, MonacoHogGlobal>+}++const HOG_EVAL_COMMON_GLOBALS_BY_TARGET = {+ generation: buildMonacoHogGlobals('generation'),+ trace: buildMonacoHogGlobals('trace'),+}++const HOG_EVAL_GLOBALS_BY_TARGET = {+ generation: {+ ...HOG_EVAL_COMMON_GLOBALS_BY_TARGET.generation,+ // Compatibility globals kept for saved generation Hog source.+ input: { type: 'string', description: 'The input to the LLM' },+ output: { type: 'string', description: 'The output from the LLM' },+ properties: { type: 'object', description: 'All event properties' },+ event: {+ uuid: { type: 'string' },+ event: { type: 'string' },+ distinct_id: { type: 'string' },+ },},- event: {- uuid: { type: 'string' },- event: { type: 'string' },- distinct_id: { type: 'string' },+ trace: {+ ...HOG_EVAL_COMMON_GLOBALS_BY_TARGET.trace,+ // Compatibility globals kept for saved trace Hog source.+ events: [+ {+ uuid: { type: 'string' },+ event: { type: 'string' },+ timestamp: { type: 'string' },+ input: { type: 'string' },+ output: { type: 'string' },+ properties: { type: 'object' },+ },+ ],+ trace: {+ id: { type: 'string' },+ event_count: { type: 'number' },+ },},}@@ -174,7 +316,7 @@ export function EvaluationCodeEditor(): JSX.Element {language="hog"value={source}onChange={(v) => setHogSource(v ?? '')}- globals={HOG_EVAL_GLOBALS}+ globals={HOG_EVAL_GLOBALS_BY_TARGET[evaluation.target]}minHeight="12rem"maxHeight="60vh"options={{@@ -189,7 +331,13 @@ export function EvaluationCodeEditor(): JSX.Element {/><div className="flex justify-between items-center text-sm text-muted"><div className="flex items-center gap-2">- <Tooltip title="Compile and run your code against up to 5 recent generations matching your trigger filters">+ <Tooltip+ title={+ evaluation.target === 'trace'+ ? 'Preview this code against up to 5 recent generations. Online runs evaluate the whole trace.'+ : 'Compile and run your code against up to 5 recent generations matching your trigger filters'+ }+ ><LemonButtontype="secondary"size="xsmall"@@ -257,21 +405,32 @@ export function EvaluationCodeEditor(): JSX.Element {))}</div><h4 className="text-sm font-semibold mb-2">Available globals</h4>- <div className="text-sm text-muted space-y-1">- <div>- <code>input</code> — the input to the LLM (prompt / messages)- </div>- <div>- <code>output</code> — the output from the LLM (response / choices)- </div>- <div>- <code>properties</code> — all event properties (e.g. <code>properties.$ai_model</code>,{' '}- <code>properties.$ai_total_cost_usd</code> etc)- </div>- <div>- <code>event.uuid</code>, <code>event.event</code>, <code>event.distinct_id</code>- </div>- </div>+ <dl className="grid grid-cols-[max-content_minmax(0,1fr)] items-start gap-x-3 gap-y-2 text-sm text-muted">+ {HOG_EVAL_COMMON_GLOBAL_DEFINITIONS.map((globalDefinition) => (+ <Fragment key={globalDefinition.name}>+ <dt>+ <code className={GLOBAL_NAME_CODE_CLASS}>{globalDefinition.name}</code>+ </dt>+ <dd className="m-0">+ <p className="m-0">+ {resolveHogGlobalDescription(globalDefinition.description, evaluation.target)}+ </p>+ <dl className="grid grid-cols-[max-content_minmax(0,1fr)] items-baseline gap-x-2 gap-y-1 mt-1.5">+ {globalDefinition.fields.map((field) => (+ <Fragment key={field.name}>+ <dt>+ <code className={PROPERTY_NAME_CODE_CLASS}>{field.name}</code>+ </dt>+ <dd className="m-0">+ {resolveHogGlobalDescription(field.description, evaluation.target)}+ </dd>+ </Fragment>+ ))}+ </dl>+ </dd>+ </Fragment>+ ))}+ </dl><h4 className="text-sm font-semibold mt-3 mb-2">Tips</h4><ul className="text-sm text-muted space-y-1 list-disc list-inside"><li>diff --git a/products/ai_observability/frontend/evaluations/hogEvalExamples.json b/products/ai_observability/frontend/evaluations/hogEvalExamples.jsonindex 464b03d4d902..7c95ac776c57 100644--- a/products/ai_observability/frontend/evaluations/hogEvalExamples.json+++ b/products/ai_observability/frontend/evaluations/hogEvalExamples.json@@ -1,58 +1,72 @@[{+ "key": "quickstart","label": "Quickstart",- "source": "// Globals: input, output, properties, event\n// input and output are strings — use jsonParse() when they contain JSON\n\n// Loop over input messages\nif (startsWith(trim(input), '[')) {\n let messages := jsonParse(input)\n for (let i, msg in messages) {\n print(concat('[', msg.role, '] ', msg.content))\n }\n} else {\n print(concat('Input: ', input))\n}\n\n// Loop over output choices\nif (startsWith(trim(output), '[')) {\n let choices := jsonParse(output)\n for (let i, choice in choices) {\n print(concat('Choice ', toString(i), ': ', choice.message.content))\n }\n} else {\n print(concat('Output: ', output))\n}\n\nprint(concat('Model: ', properties.$ai_model))\n\n// Return true (pass) or false (fail)\nreturn true"+ "source": "// Globals: evaluation_events (one generation event, or every event in a trace) and target\nprint(concat('Evaluating ', target.type, ' ', target.id))\n\nfor (let i, item in evaluation_events) {\n print(concat('Event ', toString(i), ': ', item.event))\n if (length(item.input_text) > 0) {\n print(concat('Input: ', substring(item.input_text, 1, 100)))\n }\n if (length(item.output_text) > 0) {\n print(concat('Output: ', substring(item.output_text, 1, 100)))\n }\n if (item.properties.$ai_model != null) {\n print(concat('Model: ', item.properties.$ai_model))\n }\n}\n\n// Return true (pass) or false (fail)\nreturn true"},{+ "key": "output_not_empty","label": "Output not empty",- "source": "// Check that the output is not empty\nlet result := length(output) > 0\nif (not result) {\n print('Output is empty')\n}\nreturn result"+ "source": "// Require every generation to have a non-empty output\nlet generation_count := 0\nfor (let i, item in evaluation_events) {\n if (item.event == '$ai_generation') {\n generation_count := generation_count + 1\n if (length(trim(item.output_text)) == 0) {\n print(concat('Generation ', item.uuid, ' has empty output'))\n return false\n }\n }\n}\nif (generation_count == 0) {\n print('No generation events found')\n return false\n}\nreturn true"},{+ "key": "min_output_length","label": "Min output length",- "source": "// Check that the output is at least 100 characters\nlet result := length(output) >= 100\nif (not result) {\n print('Output too short:', length(output), 'chars')\n}\nreturn result"+ "source": "// Require every generation output to be at least 100 characters\nlet generation_count := 0\nfor (let i, item in evaluation_events) {\n if (item.event == '$ai_generation') {\n generation_count := generation_count + 1\n if (length(item.output_text) < 100) {\n print('Output too short:', length(item.output_text), 'chars')\n return false\n }\n }\n}\nif (generation_count == 0) {\n print('No generation events found')\n return false\n}\nreturn true"},{+ "key": "contains_keywords","label": "Contains keywords",- "source": "// Check that the output contains all expected keywords\nlet keywords := ['hello', 'world']\nlet missing := []\nfor (let i, kw in keywords) {\n if (not (output ilike concat('%', kw, '%'))) {\n missing := arrayPushBack(missing, kw)\n }\n}\nif (length(missing) > 0) {\n print('Missing keywords:', missing)\n return false\n}\nreturn true"+ "source": "// Require each keyword to appear in at least one generation output\nlet keywords := ['hello', 'world']\nlet missing := []\nfor (let i, keyword in keywords) {\n let found := false\n for (let j, item in evaluation_events) {\n if (item.event == '$ai_generation' and item.output_text ilike concat('%', keyword, '%')) {\n found := true\n }\n }\n if (not found) {\n missing := arrayPushBack(missing, keyword)\n }\n}\nif (length(missing) > 0) {\n print('Missing keywords:', missing)\n return false\n}\nreturn true"},{+ "key": "print_messages","label": "Print messages",- "source": "// Print each message and always pass\nlet messages := input\nif (typeof(messages) == 'string' and startsWith(trim(messages), '[')) {\n messages := jsonParse(messages)\n}\nif (typeof(messages) == 'array') {\n for (let i, msg in messages) {\n print(concat('Message ', toString(i), ': [', msg.role, '] ', msg.content))\n }\n} else {\n print('Input:', input)\n}\nreturn true"+ "source": "// Print a preview of every event's input and output, then pass\nfor (let i, item in evaluation_events) {\n print(concat('Event ', toString(i), ' input: ', substring(item.input_text, 1, 100)))\n print(concat('Event ', toString(i), ' output: ', substring(item.output_text, 1, 100)))\n}\nreturn true"},{+ "key": "conversation_length","label": "Conversation length",- "source": "// Check that the conversation isn't too long\nlet max_turns := 10\nlet messages := input\nif (typeof(messages) == 'string' and startsWith(trim(messages), '[')) {\n messages := jsonParse(messages)\n}\nif (typeof(messages) != 'array') {\n print('Input is not a message array, skipping')\n return true\n}\nlet turns := length(messages)\nprint(concat(toString(turns), ' turns in conversation'))\nif (turns > max_turns) {\n print(concat('Exceeds limit of ', toString(max_turns), ' turns'))\n return false\n}\nreturn true"+ "source": "// Require each generation conversation to contain at most 10 messages\nlet max_messages := 10\nfor (let i, item in evaluation_events) {\n if (item.event == '$ai_generation') {\n let messages := item.input\n if (startsWith(trim(messages), '[')) {\n if (isValidJSON(messages)) {\n messages := jsonParse(messages)\n } else {\n print(concat('Could not parse input for generation ', item.uuid))\n }\n }\n if (typeof(messages) == 'array') {\n let message_count := length(messages)\n print(concat(toString(message_count), ' messages in conversation'))\n if (message_count > max_messages) {\n print(concat('Exceeds limit of ', toString(max_messages), ' messages'))\n return false\n }\n }\n }\n}\nreturn true"},{+ "key": "error_detection","label": "Error detection",- "source": "// Detect error patterns in the output and show the matching line\nlet patterns := [\n 'error', 'exception', 'traceback',\n 'failed', 'fatal', 'panic'\n]\nlet lines := splitByString('\\n', output)\nlet found := []\nfor (let i, line in lines) {\n for (let j, pattern in patterns) {\n if (line ilike concat('%', pattern, '%') and not has(found, pattern)) {\n found := arrayPushBack(found, pattern)\n let trimmed := trim(line)\n if (length(trimmed) > 120) {\n trimmed := concat(substring(trimmed, 1, 120), '...')\n }\n print(concat('Found \"', pattern, '\": ', trimmed))\n }\n }\n}\nif (length(found) > 0) {\n return false\n}\nreturn true"+ "source": "// Detect captured errors and common error patterns in event outputs\nlet patterns := ['error', 'exception', 'traceback', 'failed', 'fatal', 'panic']\nfor (let i, item in evaluation_events) {\n let is_error := toString(ifNull(item.properties.$ai_is_error, false)) == 'true'\n if (is_error or item.properties.$ai_error != null) {\n print(concat('Event ', item.uuid, ' is marked as errored'))\n return false\n }\n for (let j, pattern in patterns) {\n if (item.output_text ilike concat('%', pattern, '%')) {\n print(concat('Found \"', pattern, '\" in event ', item.uuid))\n return false\n }\n }\n}\nreturn true"},{+ "key": "output_quality","label": "Output quality",- "source": "// Rate output quality based on length\nlet len := length(output)\n\nif (len == 0) {\n print('Empty response')\n return false\n} else if (len < 50) {\n print('Response too short:', len, 'chars')\n return false\n} else if (len > 10000) {\n print('Response suspiciously long:', len, 'chars')\n return false\n} else {\n print('Response length OK:', len, 'chars')\n return true\n}"+ "source": "// Require every generation output to contain 50 to 10,000 characters\nlet generation_count := 0\nfor (let i, item in evaluation_events) {\n if (item.event == '$ai_generation') {\n generation_count := generation_count + 1\n let output_length := length(item.output_text)\n if (output_length < 50) {\n print('Response too short:', output_length, 'chars')\n return false\n }\n if (output_length > 10000) {\n print('Response suspiciously long:', output_length, 'chars')\n return false\n }\n }\n}\nif (generation_count == 0) {\n print('No generation events found')\n return false\n}\nreturn true"},{+ "key": "tools_called","label": "Tools called",- "source": "// Check that specific tools were called in the output\nlet expected := ['get_weather', 'get_news']\nlet found := []\nlet missing := []\nfor (let i, tool in expected) {\n if (output ilike concat('%', tool, '%')) {\n found := arrayPushBack(found, tool)\n } else {\n missing := arrayPushBack(missing, tool)\n }\n}\nprint('Found:', found)\nif (length(missing) > 0) {\n print('Missing:', missing)\n return false\n}\nreturn true"+ "source": "// Require each tool to be called at least once\nlet expected := ['get_weather', 'get_news']\nlet missing := []\nfor (let i, tool in expected) {\n let found := false\n for (let j, item in evaluation_events) {\n let tools_called := splitByString(',', toString(ifNull(item.properties.$ai_tools_called, '')))\n if (has(tools_called, tool)) {\n found := true\n }\n }\n if (not found) {\n missing := arrayPushBack(missing, tool)\n }\n}\nif (length(missing) > 0) {\n print('Missing:', missing)\n return false\n}\nreturn true"},{+ "key": "regex_safety_checks","label": "Regex safety checks",- "source": "// Run multiple regex safety checks and show matches\nlet checks := [\n ['No emails', '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+[.][a-zA-Z]{2,}'],\n ['No URLs', 'https?://[a-zA-Z0-9.-]+[.][a-zA-Z]{2,}'],\n ['No phone numbers', '[0-9]{3}[-. ][0-9]{3}[-. ][0-9]{4}'],\n ['No credit cards', '[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}']\n]\nlet failed := []\nfor (let i, check in checks) {\n if (output =~ check.2) {\n failed := arrayPushBack(failed, check.1)\n let words := splitByString(' ', output)\n for (let j, word in words) {\n if (match(word, check.2)) {\n print(concat(' ', check.1, ': found \"', word, '\"'))\n }\n }\n }\n}\nif (length(failed) > 0) {\n print(concat('Failed ', toString(length(failed)), ' of ', toString(length(checks)), ' checks'))\n return false\n}\nprint('All', length(checks), 'checks passed')\nreturn true"+ "source": "// Run regex safety checks against every event output\nlet checks := [\n ['No emails', '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+[.][a-zA-Z]{2,}'],\n ['No URLs', 'https?://[a-zA-Z0-9.-]+[.][a-zA-Z]{2,}'],\n ['No phone numbers', '[0-9]{3}[-. ][0-9]{3}[-. ][0-9]{4}'],\n ['No credit cards', '[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}']\n]\nlet failed := []\nfor (let i, item in evaluation_events) {\n for (let j, check in checks) {\n if (item.output_text =~ check.2 and not has(failed, check.1)) {\n failed := arrayPushBack(failed, check.1)\n print(concat(check.1, ' matched event ', item.uuid))\n }\n }\n}\nif (length(failed) > 0) {\n print(concat('Failed ', toString(length(failed)), ' of ', toString(length(checks)), ' checks'))\n return false\n}\nprint('All', length(checks), 'checks passed')\nreturn true"},{+ "key": "cost_latency","label": "Cost & latency guard",- "source": "// Check that cost and latency are within budget\nlet max_cost := 0.05\nlet max_latency := 10\n\nlet cost := ifNull(properties.$ai_total_cost_usd, 0)\nlet latency := ifNull(properties.$ai_latency, 0)\n\nif (cost > max_cost) {\n print(concat('Cost $', toString(cost), ' exceeds budget $', toString(max_cost)))\n return false\n}\nif (latency > max_latency) {\n print(concat('Latency ', toString(latency), 's exceeds limit ', toString(max_latency), 's'))\n return false\n}\nprint(concat('OK — cost: $', toString(cost), ', latency: ', toString(latency), 's'))\nreturn true"+ "source": "// Check aggregate cost and latency for the generation or trace\nlet max_cost := 0.05\nlet max_latency := 10\n\nlet cost := ifNull(target.total_cost_usd, 0)\nlet latency := ifNull(target.total_latency_seconds, 0)\n\nif (cost > max_cost) {\n print(concat('Cost $', toString(cost), ' exceeds budget $', toString(max_cost)))\n return false\n}\nif (latency > max_latency) {\n print(concat('Latency ', toString(latency), 's exceeds limit ', toString(max_latency), 's'))\n return false\n}\nprint(concat('OK - cost: $', toString(cost), ', latency: ', toString(latency), 's'))\nreturn true"},{+ "key": "refusal_detection","label": "Refusal detection",- "source": "// Detect when the model refuses to answer\nlet phrases := [\n 'I cannot', 'I can\\'t', 'I\\'m unable',\n 'I am unable', 'I\\'m sorry, but I',\n 'I must decline', 'I\\'m not able'\n]\nfor (let i, phrase in phrases) {\n if (output ilike concat('%', phrase, '%')) {\n print(concat('Refusal detected: \"', phrase, '\"'))\n return false\n }\n}\nreturn true"+ "source": "// Detect refusal phrases in any generation output\nlet phrases := [\n 'I cannot', 'I can\\'t', 'I\\'m unable',\n 'I am unable', 'I\\'m sorry, but I',\n 'I must decline', 'I\\'m not able'\n]\nfor (let i, item in evaluation_events) {\n if (item.event == '$ai_generation') {\n for (let j, phrase in phrases) {\n if (item.output_text ilike concat('%', phrase, '%')) {\n print(concat('Refusal detected: \"', phrase, '\"'))\n return false\n }\n }\n }\n}\nreturn true"},{+ "key": "na_guard","label": "N/A guard",- "source": "// Return N/A when the property being checked is absent\n// (requires \"Allow N/A responses\" to be enabled)\nlet model := properties.$ai_model\nif (model == null) {\n print('No model set — not applicable')\n return null\n}\n\n// Actual check: only pass certain models\nlet allowed := ['gpt-4', 'gpt-4o', 'claude-sonnet-4-20250514']\nif (not has(allowed, model)) {\n print(concat('Model ', model, ' is not in the allowed list'))\n return false\n}\nreturn true"+ "source": "// Return N/A when a generation has no model\n// (requires \"Allow N/A responses\" to be enabled)\nlet allowed := ['gpt-4', 'gpt-4o', 'claude-sonnet-4-20250514']\nlet generation_count := 0\nlet model_missing := false\nfor (let i, item in evaluation_events) {\n if (item.event == '$ai_generation') {\n generation_count := generation_count + 1\n let model := item.properties.$ai_model\n if (model == null) {\n model_missing := true\n } else if (not has(allowed, model)) {\n print(concat('Model ', model, ' is not in the allowed list'))\n return false\n }\n }\n}\nif (generation_count == 0 or model_missing) {\n print('No model set - not applicable')\n return null\n}\nreturn true"},{+ "key": "input_relevance","label": "Input relevance",- "source": "// Check that key terms from the input appear in the output\nlet words := splitByString(' ', input)\nlet key_terms := []\nfor (let i, word in words) {\n if (length(word) >= 5) {\n key_terms := arrayPushBack(key_terms, word)\n }\n}\nif (length(key_terms) == 0) {\n print('No key terms found in input (words >= 5 chars)')\n return true\n}\nlet found := 0\nlet missing := []\nfor (let i, term in key_terms) {\n if (output ilike concat('%', term, '%')) {\n found := found + 1\n } else {\n missing := arrayPushBack(missing, term)\n }\n}\nlet ratio := found / length(key_terms)\nprint(concat(toString(found), '/', toString(length(key_terms)), ' key terms found'))\nif (length(missing) > 0) {\n print('Missing:', missing)\n}\nif (ratio < 0.3) {\n print('Output may not be relevant to the input')\n return false\n}\nreturn true"+ "source": "// Check that key terms from each generation input appear in its output\nfor (let i, item in evaluation_events) {\n if (item.event == '$ai_generation') {\n let words := splitByString(' ', item.input_text)\n let key_terms := []\n for (let j, word in words) {\n if (length(word) >= 5) {\n key_terms := arrayPushBack(key_terms, word)\n }\n }\n if (length(key_terms) > 0) {\n let found := 0\n for (let j, term in key_terms) {\n if (item.output_text ilike concat('%', term, '%')) {\n found := found + 1\n }\n }\n let ratio := found / length(key_terms)\n print(concat(toString(found), '/', toString(length(key_terms)), ' key terms found'))\n if (ratio < 0.3) {\n print('Output may not be relevant to the input')\n return false\n }\n }\n }\n}\nreturn true"}]diff --git a/products/ai_observability/frontend/evaluations/hogEvalExamples.ts b/products/ai_observability/frontend/evaluations/hogEvalExamples.tsindex 57b5374a6b07..c2aba7671395 100644--- a/products/ai_observability/frontend/evaluations/hogEvalExamples.ts+++ b/products/ai_observability/frontend/evaluations/hogEvalExamples.ts@@ -1,8 +1,17 @@import examples from './hogEvalExamples.json'export interface HogEvalExample {+ key: stringlabel: stringsource: string}-export const HOG_EVAL_EXAMPLES: HogEvalExample[] = examples+export const HOG_EVAL_EXAMPLES: readonly HogEvalExample[] = examples++export function getHogEvalExample(key: string): HogEvalExample {+ const example = HOG_EVAL_EXAMPLES.find((candidate) => candidate.key === key)+ if (!example) {+ throw new Error(`Unknown Hog evaluation example: ${key}`)+ }+ return example+}diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.tsindex fe6cd8dba51c..e291ca2b7c57 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts@@ -7,7 +7,7 @@ import { initKeaTests } from '~/test/init'import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'import { EVALUATION_SUMMARY_MAX_RUNS } from './constants'import { evaluationReportLogic } from './evaluationReportLogic'-import { DEFAULT_HOG_SOURCE, DEFAULT_TRACE_HOG_SOURCE, llmEvaluationLogic } from './llmEvaluationLogic'+import { DEFAULT_HOG_SOURCE, llmEvaluationLogic } from './llmEvaluationLogic'import { EvaluationConfig, EvaluationReport, EvaluationRun } from './types'const mockProviderKeys: LLMProviderKey[] = [@@ -336,7 +336,7 @@ describe('llmEvaluationLogic', () => {await expectLogic(logic).toMatchValues({ hasUnsavedChanges: false })})- it('seeds the trace Hog default when switching to hog with a trace target', async () => {+ it('uses the target-independent Hog default for a trace target', async () => {await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])logic.actions.setEvaluationTarget('trace')@@ -344,12 +344,12 @@ describe('llmEvaluationLogic', () => {await expectLogic(logic).toMatchValues({evaluation: expect.objectContaining({- evaluation_config: { source: DEFAULT_TRACE_HOG_SOURCE },+ evaluation_config: { source: DEFAULT_HOG_SOURCE },}),})})- it('swaps the untouched Hog default when the target changes', async () => {+ it('keeps the untouched Hog default when the target changes', async () => {await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])logic.actions.setEvaluationType('hog')@@ -359,7 +359,30 @@ describe('llmEvaluationLogic', () => {logic.actions.setEvaluationTarget('trace')await expectLogic(logic).toMatchValues({- evaluation: expect.objectContaining({ evaluation_config: { source: DEFAULT_TRACE_HOG_SOURCE } }),+ evaluation: expect.objectContaining({ evaluation_config: { source: DEFAULT_HOG_SOURCE } }),+ })+ })++ it('replaces the legacy generation default when switching to trace', async () => {+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])++ logic.actions.loadEvaluationSuccess({+ ...mockEvaluation,+ evaluation_type: 'hog',+ evaluation_config: {+ source: `// Check that the output is not empty+let result := length(output) > 0+if (not result) {+ print('Output is empty')+}+return result`,+ },+ model_configuration: null,+ })+ logic.actions.setEvaluationTarget('trace')++ await expectLogic(logic).toMatchValues({+ evaluation: expect.objectContaining({ evaluation_config: { source: DEFAULT_HOG_SOURCE } }),})})diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.tsindex 6a16ac123351..06d720d4494e 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts@@ -32,6 +32,7 @@ import {isLLMJudgeEvaluation,} from './evaluationCapabilities'import { evaluationReportLogic, persistReportDraft } from './evaluationReportLogic'+import { getHogEvalExample } from './hogEvalExamples'import { EvaluationTemplateKey, defaultEvaluationTemplates } from './templates'import type {EvaluationConditionSet,@@ -52,21 +53,22 @@ import type {// evaluation is switched to the trace target. The backend re-defaults and clamps regardless.export const DEFAULT_TRACE_WINDOW_SECONDS = 30 * 60-export const DEFAULT_HOG_SOURCE = `// Check that the output is not empty+export const DEFAULT_HOG_SOURCE = getHogEvalExample('output_not_empty').source++const LEGACY_HOG_DEFAULT_SOURCES = [+ `// Check that the output is not emptylet result := length(output) > 0if (not result) {print('Output is empty')}-return result`--// Trace Hog globals expose `events` and `trace`, not a top-level `output`, so the generation-// default can't run against them — seed a trace-shaped check instead.-export const DEFAULT_TRACE_HOG_SOURCE = `// Check that the trace produced at least one event+return result`,+ `// Check that the trace produced at least one eventlet result := length(events) > 0if (not result) {print('Trace has no events')}-return result`+return result`,+]const DEFAULT_SENTIMENT_SOURCE = 'user_messages' as constconst DEFAULT_SENTIMENT_RUNS_FILTER = 'negative' as const@@ -86,7 +88,7 @@ function toHogEvaluation(evaluation: EvaluationConfig): HogEvaluation {return {...evaluation,evaluation_type: 'hog',- evaluation_config: { source: evaluation.target === 'trace' ? DEFAULT_TRACE_HOG_SOURCE : DEFAULT_HOG_SOURCE },+ evaluation_config: { source: DEFAULT_HOG_SOURCE },output_type: 'boolean',model_configuration: null,output_config: { ...evaluation.output_config, allows_na: false },@@ -621,25 +623,15 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([// Seed the window when switching to trace so the field shows a sane default;// clear the bag when switching back so we don't persist a stale window.const target_config = target === 'trace' ? { window_seconds: DEFAULT_TRACE_WINDOW_SECONDS } : {}- // Swap the default Hog source to match the new target, but only while it's still the- // untouched default for the other target — never clobber a source the user edited.- if (state.evaluation_type === 'hog') {- const source = state.evaluation_config.source- if (target === 'trace' && source === DEFAULT_HOG_SOURCE) {- return {- ...state,- target,- target_config,- evaluation_config: { ...state.evaluation_config, source: DEFAULT_TRACE_HOG_SOURCE },- }- }- if (target !== 'trace' && source === DEFAULT_TRACE_HOG_SOURCE) {- return {- ...state,- target,- target_config,- evaluation_config: { ...state.evaluation_config, source: DEFAULT_HOG_SOURCE },- }+ if (+ state.evaluation_type === 'hog' &&+ LEGACY_HOG_DEFAULT_SOURCES.includes(state.evaluation_config.source)+ ) {+ return {+ ...state,+ target,+ target_config,+ evaluation_config: { ...state.evaluation_config, source: DEFAULT_HOG_SOURCE },}}return { ...state, target, target_config }diff --git a/products/ai_observability/frontend/evaluations/templates.ts b/products/ai_observability/frontend/evaluations/templates.tsindex 86960def9af0..b75f411ff9d5 100644--- a/products/ai_observability/frontend/evaluations/templates.ts+++ b/products/ai_observability/frontend/evaluations/templates.ts@@ -1,3 +1,5 @@+import { getHogEvalExample } from './hogEvalExamples'+export interface LLMJudgeTemplate {key: stringname: string@@ -46,26 +48,10 @@ export const defaultEvaluationTemplates: readonly EvaluationTemplate[] = [{key: 'cost_latency',name: 'Cost & latency',- description: 'Flag expensive or slow generations using Hog code',+ description: 'Flag expensive or slow generations and traces using Hog code',evaluation_type: 'hog',icon: 'code',- source: `// Flag generations that are too expensive or too slow-let max_cost := 0.05-let max_latency := 10--let cost := ifNull(properties.$ai_total_cost_usd, 0)-let latency := ifNull(properties.$ai_latency, 0)--if (cost > max_cost) {- print(concat('Cost $', toString(cost), ' exceeds budget $', toString(max_cost)))- return false-}-if (latency > max_latency) {- print(concat('Latency ', toString(latency), 's exceeds limit ', toString(max_latency), 's'))- return false-}-print(concat('OK — cost: $', toString(cost), ', latency: ', toString(latency), 's'))-return true`,+ source: getHogEvalExample('cost_latency').source,},{key: 'hallucination',diff --git a/products/ai_observability/skills/creating-online-evaluations/SKILL.md b/products/ai_observability/skills/creating-online-evaluations/SKILL.mdindex a058f3a305fc..39051303fc06 100644--- a/products/ai_observability/skills/creating-online-evaluations/SKILL.md+++ b/products/ai_observability/skills/creating-online-evaluations/SKILL.md@@ -2,10 +2,10 @@name: creating-online-evaluationsdescription: >Author continuously-running online evaluations in PostHog AI observability, grounded in a real failure- mode you've identified. Use when the user wants an evaluation that automatically scores new- `$ai_generation` events going forward — "create an eval to catch X", "continuously check that responses- do Y", "turn this failure into an eval". Covers choosing the eval type (hog / llm_judge / sentiment),- gating on the team's provider key before an llm_judge eval, scoping which events fire via+ mode you've identified. Use when the user wants an evaluation that automatically scores new generations+ or whole traces going forward — "create an eval to catch X", "continuously check that responses do Y",+ "turn this failure into an eval". Covers choosing the target and eval type (hog / llm_judge / sentiment),+ gating on the team's provider key before an llm_judge eval, scoping which generations trigger it viaconditions (property filters + rollout sampling), creating it disabled, verifying scope, and enabling.Finding and ranking the failure modes worth evaluating is its own job — use exploring-ai-failures first.To debug or manage evaluations that already exist, use exploring-llm-evaluations.@@ -13,10 +13,10 @@ description: ># Creating online evaluations-An **online evaluation** scores `$ai_generation` events automatically as they arrive, forever, until-disabled. A good eval comes from a real failure mode you've found in production traffic, not from a guess-or a generic metric like "hallucination" or "helpfulness". This skill starts once that failure mode is-identified and turns it into a scoped, continuously-running eval.+An **online evaluation** automatically scores either each matching `$ai_generation` or the whole trace+containing it, until disabled. A good eval comes from a real failure mode you've found in production traffic,+not from a guess or a generic metric like "hallucination" or "helpfulness". This skill starts once that+failure mode is identified and turns it into a scoped, continuously-running eval.**First, know what you're evaluating.** Finding and ranking the failure modes worth catching is aseparate job. If the user doesn't specify what they want to evaluate, ask them. If they are still vague@@ -68,7 +68,34 @@ tool call must include an `order_id`". Then move to Phase 2.Reach for `hog` first, escalate to `llm_judge` if there is no deterministic way to check for what we want to check.-### 2.2 — Gate (llm_judge only)+### 2.2 — Choose the target++| Target | Behavior |+| ------------ | ------------------------------------------------------------------------------------------------------------------ |+| `generation` | Runs once for each matching `$ai_generation`, immediately after ingestion. This is the default. |+| `trace` | Runs once for the whole trace after the first matching generation and a configurable wait for the trace to finish. |++For a trace target, send `"target": "trace"` and+`"target_config": { "window_seconds": 1800 }`. The wait must be between 10 seconds and 2 hours and defaults+to 30 minutes. Conditions still match the generation that triggers the run; the evaluator itself receives+the complete trace. Sentiment evaluations support only the generation target.++New Hog source should use the globals shared by both targets:++| Global | Meaning |+| -------------------------------------- | ------------------------------------------------------------------------------------------------- |+| `evaluation_events` | One generation event for a generation target, or every captured event for a trace target. |+| `target` | The target's `type`, `id`, `total_cost_usd`, and `total_latency_seconds`. |+| `item.input_text` / `item.output_text` | Best-effort readable projections; use these for length, keyword, and regex checks. |+| `item.input` / `item.output` | Original serialized values; use these when the evaluator needs to parse the captured JSON itself. |++Generation evaluations still expose top-level `input`, `output`, `properties`, and `event`. Trace evaluations+still expose their original `events` and `trace` globals. Those globals are kept for compatibility with saved+evaluators. Do not use target-specific globals in new source that needs to work for both targets. The text+projections recognize common provider payloads but are not authoritative; use `item.input` / `item.output` when+exact structure matters.++### 2.3 — Gate (llm_judge only)Before creating an `llm_judge` eval, confirm it can actually run, or it errors on first fire. Hog andsentiment skip this.@@ -83,19 +110,21 @@ it as `model_configuration.provider_key_id`.If there's no `ok` key, stop and ask the user to add/validate one in the UI — the agent can't create keys.-### 2.3 — Create it disabled+### 2.4 — Create it disabledCreate with `enabled: false` so nothing fires until the scope is verified. Minimal `hog` example:```jsonposthog:llma-evaluation-create{- "name": "Output is valid JSON",- "description": "Fails when the assistant message can't be parsed as JSON",+ "name": "Output is not empty",+ "description": "Fails when a generation has no readable output","evaluation_type": "hog",- "evaluation_config": { "source": "try { jsonParse(jsonParse(output)[1].message.content); return true; } catch { return false; }" },+ "evaluation_config": { "source": "let count := 0\nfor (let i, item in evaluation_events) {\n if (item.event == '$ai_generation') {\n count := count + 1\n if (length(trim(item.output_text)) == 0) { return false }\n }\n}\nreturn count > 0" },"output_type": "boolean","output_config": { "allows_na": false },+ "target": "generation",+ "target_config": {},"conditions": [{ "id": "default", "rollout_percentage": 100, "properties": [{ "key": "$ai_model", "type": "event", "operator": "icontains", "value": "gpt" }] }],@@ -107,7 +136,7 @@ For `llm_judge`, swap `evaluation_config` to `{ "prompt": "…" }` and add`"model_configuration": { "provider": "openai", "model": "gpt-5-mini", "provider_key_id": "<uuid of an ok-state key from llma-provider-key-list>" }`.Full field reference: [references/evaluation-payload.md](references/evaluation-payload.md).-### 2.4 — Verify the scope before enabling+### 2.5 — Verify the scope before enabling`conditions` is where online evals go wrong: too broad and you evaluate (and bill) a firehose; too narrowand it never fires. Confirm the filter matches the events you expect, and roughly how many per day:@@ -121,29 +150,35 @@ WHERE event = '$ai_generation'AND timestamp >= now() - INTERVAL 7 DAY```+For generation targets, `count()` is the run volume. For trace targets, count distinct non-empty+`$ai_trace_id` values because matching generations from the same trace schedule only one run.+If volume is high, set `rollout_percentage` below 100 to sample. Spot-check the evaluator with`llma-evaluation-test-hog` (hog) or `llma-evaluation-run` against one generation (llm_judge).+Both tools currently use generation samples; for a trace target they can check shared source or prompt behavior,+but they do not reproduce the complete settled trace. Review the first live trace results before increasing rollout.> **Watch out:** some orgs reuse a single `$ai_trace_id` across 100k+ events. Scoping by trace-ID prefix> can match far more than expected — verify volume with the SQL above before enabling.-### 2.5 — Enable, then close the loop+### 2.6 — Enable, then close the loop```jsonposthog:llma-evaluation-update{ "evaluationId": "<uuid>", "enabled": true }```-It now runs on every new matching `$ai_generation`. This isn't one-and-done: the user should be aware that-they need to keep an eye on results and iterate if the outcome is not the expected one. To wire results-into a Slack feed, see `feature-usage-feed`.+It now runs on every new matching generation, or once per matching trace for a trace target. This isn't+one-and-done: the user should be aware that they need to keep an eye on results and iterate if the outcome+is not the expected one. To wire results into a Slack feed, see `feature-usage-feed`.## Scoping with conditions`conditions` is a **list** of condition sets — **OR between sets, AND within a set's `properties`**. Eachset is `{ id, rollout_percentage, properties[] }`. There is no time window inside conditions; sampling isonly `rollout_percentage` (0–100). Property filters use the standard PostHog shape-(`key`, `type`, `operator`, `value`).+(`key`, `type`, `operator`, `value`). For trace targets, these filters still select the generation that+triggers the eventual whole-trace evaluation.```json"conditions": [diff --git a/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2 b/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2index c0e5787cb1b5..d965ec052e95 100644--- a/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2+++ b/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2@@ -5,21 +5,32 @@ schemas below are rendered from the backend Pydantic models at build time, so th## Top-level fields-| Field | Required | Notes |-| --------------------- | -------- | --------------------------------------------------------------------------- |-| `name` | yes | Up to 400 chars. |-| `description` | no | Defaults to `""`. |-| `evaluation_type` | yes | `"hog"`, `"llm_judge"`, or `"sentiment"`. |-| `evaluation_config` | yes | Shape depends on `evaluation_type` (below). |-| `output_type` | yes | `"boolean"` for `hog`/`llm_judge`; `"sentiment"` for `sentiment`. |-| `output_config` | no | `{ "allows_na": bool }` for boolean; `{}` for sentiment. |-| `model_configuration` | llm_judge only | Provider/model/key. Rejected on `hog`/`sentiment`. |-| `conditions` | no | List of trigger condition sets (below). Omit to evaluate all generations. |-| `enabled` | no | Defaults to `false`. Create disabled, then flip with `llma-evaluation-update`. |+| Field | Required | Notes |+| --------------------- | -------------- | ------------------------------------------------------------------------------------- |+| `name` | yes | Up to 400 chars. |+| `description` | no | Defaults to `""`. |+| `evaluation_type` | yes | `"hog"`, `"llm_judge"`, or `"sentiment"`. |+| `evaluation_config` | yes | Shape depends on `evaluation_type` (below). |+| `output_type` | yes | `"boolean"` for `hog`/`llm_judge`; `"sentiment"` for `sentiment`. |+| `output_config` | no | `{ "allows_na": bool }` for boolean; `{}` for sentiment. |+| `model_configuration` | llm_judge only | Provider/model/key. Rejected on `hog`/`sentiment`. |+| `target` | no | `"generation"` (default) or `"trace"`. Sentiment supports only `"generation"`. |+| `target_config` | trace only | `{ "window_seconds": 10..7200 }`; defaults to 1800 seconds for a trace target. |+| `conditions` | no | Trigger condition sets (below). For traces, conditions match the triggering generation. |+| `enabled` | no | Defaults to `false`. Create disabled, then flip with `llma-evaluation-update`. |Valid `(evaluation_type, output_type)` pairs: `(hog, boolean)`, `(llm_judge, boolean)`,`(sentiment, sentiment)`.+## `target` and `target_config`++- `"target": "generation"` runs once for each matching generation and uses an empty `target_config`.+- `"target": "trace"` runs once for the whole trace after the first matching generation. Set+ `target_config.window_seconds` to control how long PostHog waits for the trace to finish before evaluating it.+- Conditions always match generation properties. For a trace target, that matching generation schedules the+ eventual whole-trace evaluation.+- Sentiment evaluations cannot use the trace target.+## `evaluation_config` by type### `llm_judge`@@ -69,7 +80,8 @@ Pin `provider_key_id` to an `ok`-state key; the eval runs on that key.## `conditions`A **list** of condition sets. **OR between sets, AND within a set's `properties`.** Omitting `conditions`-(or an empty list) evaluates every `$ai_generation`.+(or an empty list) matches every `$ai_generation`. A generation target evaluates each match; a trace target+evaluates each matching trace once.| Field | Required | Notes || -------------------- | -------- | --------------------------------------------------------------------- |@@ -101,16 +113,33 @@ and sample volume with `rollout_percentage`.```json{- "name": "Reply is under 500 tokens",+ "name": "Reply is under 2,000 characters","evaluation_type": "hog",- "evaluation_config": { "source": "return properties.$ai_output_tokens < 500;" },+ "evaluation_config": { "source": "for (let i, item in evaluation_events) { if (item.event == '$ai_generation' and length(item.output_text) >= 2000) { return false } } return true" },"output_type": "boolean","output_config": { "allows_na": false },+ "target": "generation",+ "target_config": {},"conditions": [{ "id": "default", "rollout_percentage": 100, "properties": [] }],"enabled": false}```+The same Hog source works for a whole trace. Change only the target fields:++```json+{+ "target": "trace",+ "target_config": { "window_seconds": 1800 }+}+```++New Hog source should use the shared `evaluation_events` and `target` globals. Top-level generation globals+such as `input`, `output`, `properties`, and `event`, plus the trace-only `events` and `trace` globals, remain+available for compatibility with saved evaluators. `item.input_text` and `item.output_text` are best-effort+readable projections of common provider payloads; use raw `item.input` and `item.output` when exact structure+matters.+### LLM judge```json@@ -122,6 +151,8 @@ and sample volume with `rollout_percentage`."output_type": "boolean","output_config": { "allows_na": true },"model_configuration": { "provider": "openai", "model": "gpt-5-mini", "provider_key_id": "<ok-state key uuid from llma-provider-key-list>" },+ "target": "generation",+ "target_config": {},"conditions": [{ "id": "default", "rollout_percentage": 100, "properties": [] }],"enabled": false}