: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(workflows): pass an AI task's structured output back to the step (#97290)
Harley Alexander647f002823dd
diff --git a/posthog/cdp/workflow_step_resume.py b/posthog/cdp/workflow_step_resume.pyindex ede8724f5f17..da2b687323f5 100644--- a/posthog/cdp/workflow_step_resume.py+++ b/posthog/cdp/workflow_step_resume.py@@ -18,7 +18,7 @@ def _json_size(value: Any) -> int:return len(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))-def _cap_value(value: Any, budget: int) -> Any:+def cap_value(value: Any, budget: int) -> Any:if isinstance(value, str):lower, upper = 0, min(len(value), RESULT_STRING_CAP)while lower < upper:@@ -32,7 +32,9 @@ def _cap_value(value: Any, budget: int) -> Any:result: dict[str, Any] = {}for key, item in value.items():available = budget - _json_size({**result, key: None}) + 4- capped = _cap_value(item, available)+ if available <= 0:+ break+ capped = cap_value(item, available)if capped is not None and _json_size(capped) <= available:result[key] = cappedreturn result@@ -40,7 +42,7 @@ def _cap_value(value: Any, budget: int) -> Any:items: list[Any] = []for item in value:available = budget - _json_size(items) - bool(items)- capped = _cap_value(item, available)+ capped = cap_value(item, available)if capped is None or _json_size(capped) > available or (isinstance(item, str) and capped != item):breakitems.append(capped)@@ -71,7 +73,7 @@ def emit_workflow_step_resume(properties={"origin_key": origin_key,"status": status,- "result": _cap_value(result or {}, RESULT_BYTE_CAP),+ "result": cap_value(result or {}, RESULT_BYTE_CAP),},),)diff --git a/products/tasks/backend/facade/workflow_tasks.py b/products/tasks/backend/facade/workflow_tasks.pyindex acd6575613df..bc744df08aba 100644--- a/products/tasks/backend/facade/workflow_tasks.py+++ b/products/tasks/backend/facade/workflow_tasks.py@@ -5,6 +5,11 @@ and starts the task through this boundary."""from products.tasks.backend.facade.contracts import WorkflowTaskRateLimits, WorkflowTaskSlackContext+from products.tasks.backend.logic.services.workflow_task_output import (+ OUTPUT_FIELD_TYPES,+ WorkflowTaskOutputFieldsInvalid,+ build_output_schema,+)from products.tasks.backend.logic.services.workflow_task_skills import (MAX_ATTACHED_SKILLS,WorkflowTaskSkillsInvalid,@@ -24,9 +29,11 @@ from products.tasks.backend.logic.services.workflow_tasks import (__all__ = ["MAX_ATTACHED_SKILLS",+ "OUTPUT_FIELD_TYPES","WorkflowTaskConnectorsInvalid","WorkflowTaskLimitExceeded","WorkflowTaskOriginKeyConflict",+ "WorkflowTaskOutputFieldsInvalid","WorkflowTaskOwnerIneligible","WorkflowTaskRateCapped","WorkflowTaskRateLimits",@@ -34,6 +41,7 @@ __all__ = ["WorkflowTaskSlackContext","WorkflowTaskTeamRateCapped","WorkflowTaskUsageLimited",+ "build_output_schema","create_workflow_task","resolve_connectors","validate_skill_names",diff --git a/products/tasks/backend/logic/services/workflow_step_resume.py b/products/tasks/backend/logic/services/workflow_step_resume.pyindex 18f5c5cf54ae..f80d7f3fb5f2 100644--- a/products/tasks/backend/logic/services/workflow_step_resume.py+++ b/products/tasks/backend/logic/services/workflow_step_resume.py@@ -3,8 +3,14 @@ from uuid import UUIDfrom celery import current_app-from posthog.cdp.workflow_step_resume import WorkflowStepResumeStatus, emit_workflow_step_resume-+from posthog.cdp.workflow_step_resume import (+ RESULT_BYTE_CAP,+ WorkflowStepResumeStatus,+ cap_value,+ emit_workflow_step_resume,+)++from products.tasks.backend.logic.services.workflow_task_output import RUN_OUTPUT_RESERVED_KEYSfrom products.tasks.backend.models import Task, TaskRun_STATUS_BY_RUN_STATUS: dict[str, WorkflowStepResumeStatus] = {@@ -19,10 +25,54 @@ FINAL_MESSAGE_GRACE_SECONDS = 30DEFERRED_RESUME_TASK = "products.tasks.backend.tasks.tasks.resume_workflow_step_for_run_deferred"+def _validation_warnings(schema: dict[str, Any], structured: dict[str, Any]) -> list[str]:+ # Deferred: jsonschema is heavy and only a run with a schema needs it.+ from jsonschema import Draft202012Validator, ValidationError # noqa: PLC0415+ from referencing import Registry # noqa: PLC0415++ try:+ # An empty registry fails closed on any reference the schema does not carry itself.+ Draft202012Validator(schema, registry=Registry()).validate(structured)+ except ValidationError as error:+ return [f"The task finished, but its output does not match the output variables: {error.message}"]+ except Exception as error:+ return [f"The task finished, but its output could not be checked against the output variables: {error}"]+ return []+++def _cut_warnings(structured: dict[str, Any]) -> list[str]:+ capped = cap_value(structured, RESULT_BYTE_CAP)+ cut = [name for name, value in structured.items() if capped.get(name) != value]+ if not cut:+ return []+ return [f"The task's output was cut to fit the step result: {', '.join(cut)}"]+++def _structured_output_for_run(task_run: TaskRun) -> tuple[dict[str, Any] | None, list[str]]:+ """The agent's fields from `run.output` and the warnings the step should log.++ The agent's fields sit at the top level of `run.output`, next to bookkeeping the tasks+ product writes there under reserved names.+ """+ schema = task_run.task.json_schema+ if not schema:+ return None, []+ output = task_run.output if isinstance(task_run.output, dict) else {}+ structured = {key: value for key, value in output.items() if key not in RUN_OUTPUT_RESERVED_KEYS}+ if task_run.status != TaskRun.Status.COMPLETED:+ return structured, []+ return structured, _validation_warnings(schema, structured) + _cut_warnings(structured)++def _result_for_run(task_run: TaskRun) -> dict[str, Any]:output = task_run.output or {}+ structured, warnings = _structured_output_for_run(task_run)+ # `output` goes first: the byte cap trims later keys first, and prose can lose its tail while+ # a structured field cannot.return {"run_id": str(task_run.id),+ "output": structured,+ "warnings": warnings or None,"final_message": output.get("final_message"),"pr_urls": output.get("pr_urls") or ([output["pr_url"]] if output.get("pr_url") else None),"error_message": task_run.error_message,diff --git a/products/tasks/backend/logic/services/workflow_task_output.py b/products/tasks/backend/logic/services/workflow_task_output.pynew file mode 100644index 000000000000..c702d0325915--- /dev/null+++ b/products/tasks/backend/logic/services/workflow_task_output.py@@ -0,0 +1,60 @@+"""The output fields a workflow step asks its AI task for, and the schema they become."""++import re+from collections.abc import Mapping+from typing import Any++from posthog.cdp.workflow_step_resume import RESULT_BYTE_CAP, RESULT_STRING_CAP++OUTPUT_FIELD_TYPES = ("string", "number", "boolean")+MAX_OUTPUT_FIELDS = 20+_OUTPUT_FIELD_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")+# Keys the tasks product writes into `TaskRun.output` next to the agent's fields.+RUN_OUTPUT_RESERVED_KEYS = frozenset(+ {"final_message", "pr_url", "pr_urls", "head_branches", "pr_state", "pr_merged", "ci_status", "commit_push"}+)+++class WorkflowTaskOutputFieldsInvalid(ValueError):+ pass+++def build_output_schema(fields: Mapping[str, str]) -> dict[str, Any]:+ """The JSON Schema the agent runtime enforces for the step's output fields.++ Built here from a flat name-to-type map so no caller hands the validator a schema of its+ own. Strings carry the step's per-string cap so the agent sees the limit up front.+ """+ if not fields:+ raise WorkflowTaskOutputFieldsInvalid("output_fields must name at least one field")+ if len(fields) > MAX_OUTPUT_FIELDS:+ raise WorkflowTaskOutputFieldsInvalid(f"output_fields allows at most {MAX_OUTPUT_FIELDS} fields")+ properties: dict[str, dict[str, Any]] = {}+ for name, field_type in fields.items():+ if not _OUTPUT_FIELD_NAME.match(name):+ raise WorkflowTaskOutputFieldsInvalid(+ f"output field {name!r} must be a name of letters, digits and underscores, not starting with a digit"+ )+ if name in RUN_OUTPUT_RESERVED_KEYS:+ raise WorkflowTaskOutputFieldsInvalid(f"output field {name!r} is reserved by the task result")+ if field_type not in OUTPUT_FIELD_TYPES:+ raise WorkflowTaskOutputFieldsInvalid(+ f"output field {name!r} has type {field_type!r}; expected one of {', '.join(OUTPUT_FIELD_TYPES)}"+ )+ properties[name] = {"type": field_type}+ if field_type == "string":+ properties[name]["maxLength"] = RESULT_STRING_CAP+ return {"type": "object", "properties": properties, "required": list(properties)}+++def output_fields_sentence(output_schema: Mapping[str, Any] | None) -> str | None:+ """Tells the agent which fields the step reads and the budget they share with the message."""+ properties = (output_schema or {}).get("properties") or {}+ if not properties:+ return None+ listed = ", ".join(f"{name} ({spec.get('type', 'any')})" for name, spec in properties.items())+ return (+ f"The workflow reads these fields from your structured output before it reads your final "+ f"message: {listed}. Keep each text field within {RESULT_STRING_CAP} characters. The fields "+ f"and the message share a {RESULT_BYTE_CAP} byte budget, and the fields take priority."+ )diff --git a/products/tasks/backend/logic/services/workflow_tasks.py b/products/tasks/backend/logic/services/workflow_tasks.pyindex ceab46f48255..2fee22937522 100644--- a/products/tasks/backend/logic/services/workflow_tasks.py+++ b/products/tasks/backend/logic/services/workflow_tasks.py@@ -7,6 +7,7 @@ never touches tasks internals.import jsonimport uuid+from collections.abc import Mappingfrom datetime import timedeltafrom typing import Any@@ -33,6 +34,7 @@ from products.tasks.backend.logic.services.run_actor import (loop_owner_eligible_for_credentials,user_has_current_team_access,)+from products.tasks.backend.logic.services.workflow_task_output import output_fields_sentencefrom products.tasks.backend.logic.services.workflow_task_skills import (AttachedSkill,render_skills_manifest,@@ -147,6 +149,7 @@ def create_workflow_task(event: dict[str, Any] | None = None,slack_context: contracts.WorkflowTaskSlackContext | None = None,rate_limits: contracts.WorkflowTaskRateLimits | None = None,+ output_schema: dict[str, Any] | None = None,) -> contracts.WorkflowTaskDTO:"""Create a workflow-origin task and start its agent run.@@ -174,6 +177,9 @@ def create_workflow_task(is dropped, rather than failing the create, when it resolves to no Slack integration ofthis team, when the channel is externally shared without an approval, or when anotherlive run already owns the thread.++ `output_schema` is the schema `build_output_schema` made from the step's output fields. It+ becomes `Task.json_schema`, which the agent runtime enforces at the end of the run."""replay = _find_replayed_task(team.id, hog_flow_id, origin_key)if replay is not None:@@ -318,6 +324,7 @@ def create_workflow_task(event,skills,slack_reply_context=slack_binding is not None,+ output_schema=output_schema,)# Derived from the thread context rather than tested separately, because the two# must travel together: a context passed without an explicit origin defaults the@@ -347,6 +354,7 @@ def create_workflow_task(posthog_mcp_scopes=posthog_mcp_scopes,hog_flow_id=hog_flow_id,origin_key=origin_key,+ output_schema=output_schema,extra_run_state=extra_run_state,runtime_adapter=runtime_adapter_for(model),model=model,@@ -451,6 +459,7 @@ def _render_run_message(skills: list[AttachedSkill] | None = None,*,slack_reply_context: bool = False,+ output_schema: Mapping[str, Any] | None = None,) -> str:# PostHog Code strips this established wrapper from user-message bubbles while still# sending its contents to the agent (same contract as render_loop_run_message).@@ -458,6 +467,9 @@ def _render_run_message(# system-generated, and it must sit above <triggering_event>, which the framing text tells# the agent to read as data rather than instructions.instructions = [WORKFLOW_SLACK_FRAMING_BLOCK if slack_reply_context else WORKFLOW_FRAMING_BLOCK]+ fields_sentence = output_fields_sentence(output_schema)+ if fields_sentence:+ instructions.append(fields_sentence)skills_manifest = render_skills_manifest(skills or [])if skills_manifest:instructions.append(skills_manifest)diff --git a/products/tasks/backend/tests/test_workflow_step_resume.py b/products/tasks/backend/tests/test_workflow_step_resume.pyindex e84ae84e29d9..7a6825d9c9e3 100644--- a/products/tasks/backend/tests/test_workflow_step_resume.py+++ b/products/tasks/backend/tests/test_workflow_step_resume.py@@ -6,6 +6,8 @@ from unittest.mock import patchfrom parameterized import parameterized+from posthog.cdp.workflow_step_resume import RESULT_BYTE_CAP+from products.tasks.backend.facade.api import update_task_runfrom products.tasks.backend.logic.services.workflow_step_resume import (DEFERRED_RESUME_TASK,@@ -29,6 +31,8 @@ class TestResumeWorkflowStepForRun(BaseTest):origin_key: str | None = "job:step:1",status: str = TaskRun.Status.COMPLETED,final_message: str | None = "Collected 3 PRs",+ json_schema: dict | None = None,+ structured_output: dict | None = None,) -> TaskRun:task = Task.objects.create(team=self.team,@@ -37,8 +41,9 @@ class TestResumeWorkflowStepForRun(BaseTest):origin_product=origin_product,origin_key=origin_key,hog_flow_id=uuid.uuid4() if origin_key else None,+ json_schema=json_schema,)- output = {"pr_url": "https://example.com/pr/1"}+ output: dict = {"pr_url": "https://example.com/pr/1", **(structured_output or {})}if final_message is not None:output["final_message"] = final_messagereturn TaskRun.objects.create(@@ -69,12 +74,67 @@ class TestResumeWorkflowStepForRun(BaseTest):status=expected,result={"run_id": str(run.id),+ "output": None,+ "warnings": None,"final_message": "Collected 3 PRs","pr_urls": ["https://example.com/pr/1"],"error_message": "boom" if run_status == TaskRun.Status.FAILED else None,},)+ _SCHEMA = {+ "type": "object",+ "properties": {"verdict": {"type": "string"}, "score": {"type": "number"}},+ "required": ["verdict", "score"],+ }++ @parameterized.expand(+ [+ ("matching_output", TaskRun.Status.COMPLETED, {"verdict": "ship", "score": 0.9}, None),+ (+ "missing_field",+ TaskRun.Status.COMPLETED,+ {"verdict": "ship"},+ [+ "The task finished, but its output does not match the output variables: 'score' is a required property"+ ],+ ),+ (+ "field_too_long_for_the_step_result",+ TaskRun.Status.COMPLETED,+ {"verdict": "x" * (RESULT_BYTE_CAP + 1), "score": 0.9},+ ["The task's output was cut to fit the step result: verdict"],+ ),+ ("failed_run_is_not_judged", TaskRun.Status.FAILED, {}, None),+ ]+ )+ def test_reports_the_agent_output_against_the_task_schema(+ self, _name: str, status: str, structured_output: dict, warnings: list[str] | None+ ) -> None:+ run = self._run(status=status, json_schema=self._SCHEMA, structured_output=structured_output)++ with patch(_RESUME) as resume:+ resume_workflow_step_for_run(run)++ result = resume.call_args.kwargs["result"]+ assert result["output"] == structured_output+ assert result["warnings"] == warnings+ assert resume.call_args.kwargs["status"] == ("failed" if status == TaskRun.Status.FAILED else "completed")++ def test_a_schema_the_validator_cannot_use_warns_instead_of_blocking_the_wake(self) -> None:+ schema = {"type": "object", "properties": {"verdict": {"$ref": "https://example.com/s.json"}}}+ run = self._run(json_schema=schema, structured_output={"verdict": "ship"})++ with patch(_RESUME) as resume:+ resume_workflow_step_for_run(run)++ result = resume.call_args.kwargs["result"]+ assert result["output"] == {"verdict": "ship"}+ assert result["warnings"] == [+ "The task finished, but its output could not be checked against the output variables: "+ "Unresolvable: https://example.com/s.json"+ ]+@parameterized.expand([("not_from_a_workflow", Task.OriginProduct.USER_CREATED, None, TaskRun.Status.COMPLETED),diff --git a/products/tasks/backend/tests/test_workflow_tasks_api.py b/products/tasks/backend/tests/test_workflow_tasks_api.pyindex 0225dcb8a32d..f7fb06111ac6 100644--- a/products/tasks/backend/tests/test_workflow_tasks_api.py+++ b/products/tasks/backend/tests/test_workflow_tasks_api.py@@ -670,6 +670,30 @@ class TestWorkflowTasksAPI(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert not Task.objects.filter(hog_flow_id=self.hog_flow.id).exists()+ def test_the_output_fields_become_the_tasks_json_schema_and_reach_the_prompt(self) -> None:+ response = self._post({"output_fields": {"verdict": "string", "score": "number"}})++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ task = Task.objects.get(id=response.json()["id"])+ assert task.json_schema == {+ "type": "object",+ "properties": {+ "verdict": {"type": "string", "maxLength": RESULT_STRING_CAP},+ "score": {"type": "number"},+ },+ "required": ["verdict", "score"],+ }+ prompt = TaskRun.objects.get(task=task).state["initial_prompt_override"]+ assert "verdict (string), score (number)" in prompt+ assert f"Keep each text field within {RESULT_STRING_CAP} characters" in prompt++ def test_rejects_output_fields_the_step_result_cannot_carry(self) -> None:+ response = self._post({"output_fields": {"final_message": "string"}})++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "output_fields"+ assert not Task.objects.filter(hog_flow_id=self.hog_flow.id).exists()+def test_includes_the_triggering_event_in_the_agent_prompt(self) -> None:response = self._post({"event": {"event": "$slack_message_received", "properties": {"text": "Database latency alert fired"}}}@@ -985,6 +1009,10 @@ class TestWorkflowTaskCreateSerializer(SimpleTestCase):{"prompt": "p", "slack_context": {"integration_id": 1, "thread_ts": "1.0"}},"slack_context",),+ ("output_field_unknown_type", {"prompt": "p", "output_fields": {"verdict": "object"}}, "output_fields"),+ ("output_field_bad_name", {"prompt": "p", "output_fields": {"task-result": "string"}}, "output_fields"),+ ("output_field_reserved_name", {"prompt": "p", "output_fields": {"pr_urls": "string"}}, "output_fields"),+ ("output_fields_empty", {"prompt": "p", "output_fields": {}}, "output_fields"),("slack_context_bad_integration_id",{diff --git a/products/workflows/backend/api/workflow_tasks.py b/products/workflows/backend/api/workflow_tasks.pyindex e94b97917159..9c1f6a2ec8d0 100644--- a/products/workflows/backend/api/workflow_tasks.py+++ b/products/workflows/backend/api/workflow_tasks.py@@ -14,15 +14,18 @@ from posthog.models.team.team import Teamfrom products.tasks.backend.facade.workflow_tasks import (MAX_ATTACHED_SKILLS,+ OUTPUT_FIELD_TYPES,WorkflowTaskConnectorsInvalid,WorkflowTaskLimitExceeded,WorkflowTaskOriginKeyConflict,+ WorkflowTaskOutputFieldsInvalid,WorkflowTaskOwnerIneligible,WorkflowTaskRateCapped,WorkflowTaskRateLimits,WorkflowTaskSlackContext,WorkflowTaskTeamRateCapped,WorkflowTaskUsageLimited,+ build_output_schema,create_workflow_task,)from products.workflows.backend.models import HogFlow, TeamWorkflowsConfig@@ -132,6 +135,23 @@ class WorkflowTaskCreateSerializer(serializers.Serializer):required=False,help_text="Stable key for this invocation. A retried request with the same key returns the existing task.",)+ output_fields = serializers.DictField(+ child=serializers.ChoiceField(choices=OUTPUT_FIELD_TYPES),+ required=False,+ allow_null=True,+ help_text=(+ "Fields the agent must return, as {name: string|number|boolean}. They come back on the step "+ "result as `output.<name>`; text fields are cut at 1500 characters."+ ),+ )++ def validate_output_fields(self, value: dict[str, str] | None) -> dict[str, Any] | None:+ if value is None:+ return None+ try:+ return build_output_schema(value)+ except WorkflowTaskOutputFieldsInvalid as exc:+ raise serializers.ValidationError(str(exc))class WorkflowTaskResponseSerializer(serializers.Serializer):@@ -218,6 +238,7 @@ class WorkflowTaskViewSet(viewsets.GenericViewSet):WorkflowTaskSlackContext(**data["slack_context"]) if data.get("slack_context") else None),rate_limits=rate_limits,+ output_schema=data.get("output_fields"),)except WorkflowTaskConnectorsInvalid as error:raise serializers.ValidationError(