: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
chore(conversations): support reply eval harness (#100918)
Alex V482536bbd99a
diff --git a/products/conversations/README.md b/products/conversations/README.mdindex 372f45a29356..041d786418d4 100644--- a/products/conversations/README.md+++ b/products/conversations/README.md@@ -27,3 +27,22 @@ python manage.py run_support_reply --team-id 1 --ticket-number 42# By ticket UUIDpython manage.py run_support_reply --team-id 1 --ticket-id "a1b2c3d4-..."```++### `run_support_reply_eval`++Score the invented support-reply fixtures against the pipeline. Mocked by default (sandbox draft stubbed, no LLM). CI uses this variant.++```bash+python manage.py run_support_reply_eval+python manage.py run_support_reply_eval --fixture how_to_sdk_install+python manage.py run_support_reply_eval --live --keep+```++`--live` runs the real draft agent. `--keep` leaves the ephemeral eval team in the database.++The same suite is also on the shared eval harness:++```bash+hogli evals eval_support_reply+SUPPORT_REPLY_EVAL_LIVE=1 hogli evals eval_support_reply --eval how_to_sdk_install+```diff --git a/products/conversations/backend/ai/human_outcome.py b/products/conversations/backend/ai/human_outcome.pynew file mode 100644index 000000000000..2c719d4def24--- /dev/null+++ b/products/conversations/backend/ai/human_outcome.py@@ -0,0 +1,89 @@+"""Record whether a human public reply used, edited, or ignored the AI draft.++A metric on `ai_triage.human_outcome`, not a learning input.+"""++from __future__ import annotations++from difflib import SequenceMatcher+from typing import Literal++from django.db import transaction+from django.db.models import Q, QuerySet++from posthog.models.comment import Comment++from products.conversations.backend.models import Ticket++HumanOutcome = Literal["used", "edited", "ignored"]++# Near-copy of the draft counts as used; some overlap as edited; the rest as ignored.+USED_RATIO = 0.85+EDITED_RATIO = 0.4+++def classify_human_outcome(ai_draft: str, human_reply: str) -> HumanOutcome:+ ratio = SequenceMatcher(None, ai_draft.strip(), human_reply.strip()).ratio()+ if ratio >= USED_RATIO:+ return "used"+ if ratio >= EDITED_RATIO:+ return "edited"+ return "ignored"+++def _ticket_comments(*, team_id: int, ticket_id: str) -> QuerySet[Comment]:+ return Comment.objects.filter(+ team_id=team_id,+ scope="conversations_ticket",+ item_id=str(ticket_id),+ )+++def _public_human_comments(comments: QuerySet[Comment]) -> QuerySet[Comment]:+ return (+ comments.filter(created_by_id__isnull=False)+ .exclude(item_context__author_type="customer")+ .exclude(item_context__is_private=True)+ )+++def maybe_record_human_outcome(*, team_id: int, ticket_id: str, comment_id: str, human_content: str) -> None:+ """Set `ai_triage.human_outcome` on the first public human reply after the latest AI note."""+ if not human_content.strip():+ return++ with transaction.atomic():+ ticket = Ticket.objects.select_for_update().filter(id=ticket_id, team_id=team_id).first()+ if ticket is None:+ return+ triage = dict(ticket.ai_triage or {})+ if triage.get("human_outcome"):+ return++ comments = _ticket_comments(team_id=team_id, ticket_id=ticket_id)+ this_comment = comments.filter(id=comment_id).first()+ if this_comment is None:+ return++ before_this = Q(created_at__lt=this_comment.created_at) | Q(+ created_at=this_comment.created_at, id__lt=this_comment.id+ )+ # Only private AI notes are drafts a human can adopt. A public AI reply was auto-sent+ # to the customer, so a later human reply is a follow-up, not adoption of a draft.+ ai_note = (+ comments.filter(item_context__author_type="AI", item_context__is_private=True)+ .filter(before_this)+ .order_by("-created_at", "-id")+ .first()+ )+ if ai_note is None or not (ai_note.content or "").strip():+ return++ after_ai = Q(created_at__gt=ai_note.created_at) | Q(created_at=ai_note.created_at, id__gt=ai_note.id)+ first_after = _public_human_comments(comments).filter(after_ai).order_by("created_at", "id").first()+ if first_after is None or str(first_after.id) != str(comment_id):+ return++ triage["human_outcome"] = classify_human_outcome(ai_note.content or "", human_content)+ ticket.ai_triage = triage+ ticket.save(update_fields=["ai_triage", "updated_at"])diff --git a/products/conversations/backend/ai/test_human_outcome.py b/products/conversations/backend/ai/test_human_outcome.pynew file mode 100644index 000000000000..75fa009ff428--- /dev/null+++ b/products/conversations/backend/ai/test_human_outcome.py@@ -0,0 +1,26 @@+from django.test import SimpleTestCase++from products.conversations.backend.ai.human_outcome import classify_human_outcome+++class TestClassifyHumanOutcome(SimpleTestCase):+ def test_identical_reply_is_used(self):+ draft = "Add the snippet to the head of every page."+ assert classify_human_outcome(draft, draft) == "used"++ def test_whitespace_only_change_is_used(self):+ assert classify_human_outcome("Hello there.", "Hello there. ") == "used"++ def test_partial_rewrite_is_edited(self):+ draft = "Add the SDK snippet to the head of every page, then reload to send a pageview."+ reply = "Drop the recorder snippet on checkout only, then hard-refresh to send a pageview."+ assert classify_human_outcome(draft, reply) == "edited"++ def test_unrelated_reply_is_ignored(self):+ assert (+ classify_human_outcome(+ "Add the snippet to the head of every page.",+ "We migrated this org to a new plan yesterday.",+ )+ == "ignored"+ )diff --git a/products/conversations/backend/api/tests/test_signals.py b/products/conversations/backend/api/tests/test_signals.pyindex be266ba3b9d0..8a06d920bb4d 100644--- a/products/conversations/backend/api/tests/test_signals.py+++ b/products/conversations/backend/api/tests/test_signals.py@@ -51,6 +51,15 @@ class TestTicketMessageSignals(BaseTest):item_context={"author_type": "team", "is_private": is_private},)+ def _create_ai_message(self, content: str, *, is_private: bool = True) -> Comment:+ return Comment.objects.create(+ team=self.team,+ scope="conversations_ticket",+ item_id=str(self.ticket.id),+ content=content,+ item_context={"author_type": "AI", "is_private": is_private},+ )+def test_customer_message_updates_stats(self, mock_on_commit):comment = self._create_customer_message("Hello from customer")@@ -71,6 +80,63 @@ class TestTicketMessageSignals(BaseTest):assert self.ticket.updated_at == comment.created_atassert self.ticket.unread_customer_count == 1 # Team messages increment this+ def test_first_public_human_reply_records_human_outcome(self, mock_on_commit):+ draft = "Add the snippet to the head of every page."+ self._create_ai_message(draft)+ self._create_team_message(draft)++ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "used"++ def test_second_public_human_reply_does_not_overwrite_human_outcome(self, mock_on_commit):+ draft = "Add the snippet to the head of every page."+ self._create_ai_message(draft)+ self._create_team_message(draft)+ self._create_team_message("We migrated this org to a new plan yesterday.")++ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "used"++ def test_private_human_note_does_not_record_human_outcome(self, mock_on_commit):+ self._create_ai_message("Add the snippet to the head of every page.")+ self._create_team_message("Add the snippet to the head of every page.", is_private=True)++ self.ticket.refresh_from_db()+ assert "human_outcome" not in (self.ticket.ai_triage or {})++ def test_human_reply_without_ai_note_does_not_record_human_outcome(self, mock_on_commit):+ self._create_team_message("Add the snippet to the head of every page.")++ self.ticket.refresh_from_db()+ assert "human_outcome" not in (self.ticket.ai_triage or {})++ def test_public_ai_reply_is_not_treated_as_a_draft(self, mock_on_commit):+ draft = "Add the snippet to the head of every page."+ self._create_ai_message(draft)+ self._create_ai_message("Totally different automated billing answer.", is_private=False)+ self._create_team_message(draft)++ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "used"++ def test_human_reply_before_ai_note_does_not_block_later_outcome(self, mock_on_commit):+ draft = "Add the snippet to the head of every page."+ self._create_team_message("Looking into this.")+ self._create_ai_message(draft)+ self._create_team_message(draft)++ self.ticket.refresh_from_db()+ assert self.ticket.ai_triage["human_outcome"] == "used"++ @patch("products.conversations.backend.signals.capture_message_sent")+ @patch(+ "products.conversations.backend.signals.maybe_record_human_outcome",+ side_effect=RuntimeError("boom"),+ )+ def test_human_outcome_failure_does_not_block_message_analytics(self, _mock_record, mock_sent, mock_on_commit):+ self._create_team_message("Thanks")+ mock_sent.assert_called_once()+def test_multiple_messages_accumulate(self, mock_on_commit):self._create_customer_message("First")self._create_team_message("Second")diff --git a/products/conversations/backend/management/commands/run_support_reply_eval.py b/products/conversations/backend/management/commands/run_support_reply_eval.pynew file mode 100644index 000000000000..028783dfca4e--- /dev/null+++ b/products/conversations/backend/management/commands/run_support_reply_eval.py@@ -0,0 +1,52 @@+"""Run the support-reply eval fixtures through the pipeline.++Mocked by default (no sandbox, no LLM). Pass --live to run the real draft agent.+CI uses the mocked variant.+"""++from __future__ import annotations++import asyncio+from functools import partial++from django.core.management.base import BaseCommand, CommandError++from products.conversations.evals.fixtures import FIXTURES, expected_for+from products.conversations.evals.report import EvalRow, format_report+from products.conversations.evals.runner import run_fixture+from products.conversations.evals.scorers import DETERMINISTIC_SCORERS+from products.conversations.evals.seeders import provision_eval_team, seed_case, teardown_eval_team+++class Command(BaseCommand):+ help = "Run support-reply eval fixtures. Mocked by default; pass --live for the real draft agent."++ def add_arguments(self, parser) -> None:+ parser.add_argument("--live", action="store_true", help="Run the real sandbox draft instead of the stub.")+ parser.add_argument("--fixture", type=str, default="", help="Substring filter on fixture name.")+ parser.add_argument("--keep", action="store_true", help="Leave the ephemeral eval team in the database.")++ def handle(self, *args, **options) -> None:+ live: bool = options["live"]+ fixture_filter: str = options["fixture"]+ keep: bool = options["keep"]+ rows = asyncio.run(self._run(live=live, fixture_filter=fixture_filter, keep=keep))+ self.stdout.write(format_report(rows))+ if any(row.output.get("exit_code") not in (0, None) for row in rows):+ raise CommandError("One or more support-reply fixtures failed to execute.")++ async def _run(self, *, live: bool, fixture_filter: str, keep: bool) -> list[EvalRow]:+ selected = [f for f in FIXTURES if not fixture_filter or fixture_filter in f.name]+ rows: list[EvalRow] = []+ for fixture in selected:+ eval_team = await asyncio.to_thread(partial(provision_eval_team, label=fixture.name))+ try:+ seed = await asyncio.to_thread(partial(seed_case, eval_team=eval_team, fixture=fixture))+ output = await run_fixture(fixture, seed, live=live)+ expected = expected_for(fixture)+ scores = {scorer._name(): scorer._run_eval_sync(output, expected) for scorer in DETERMINISTIC_SCORERS}+ rows.append(EvalRow(fixture=fixture, output=output, scores=scores))+ finally:+ if not keep:+ await asyncio.to_thread(partial(teardown_eval_team, eval_team=eval_team))+ return rowsdiff --git a/products/conversations/backend/signals.py b/products/conversations/backend/signals.pyindex 2f742d6e6087..5e58676c1563 100644--- a/products/conversations/backend/signals.py+++ b/products/conversations/backend/signals.py@@ -16,6 +16,7 @@ from posthog.models.comment import Commentfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.signals import secret_api_token_rotated+from .ai.human_outcome import maybe_record_human_outcomefrom .cache import invalidate_identity_tickets_cache, invalidate_messages_cache, invalidate_tickets_cachefrom .events import capture_message_received, capture_message_sent, capture_private_message_sent, capture_ticket_createdfrom .models import EmailOutboxMessage, SigningSecret, Ticket@@ -170,6 +171,17 @@ def update_ticket_on_message(sender, instance: Comment, created: bool, **kwargs)invalidate_tickets_cache(team_id, ticket.widget_session_id)invalidate_messages_cache(team_id, item_id)+ if is_team_message and created_by_id:+ try:+ maybe_record_human_outcome(+ team_id=team_id,+ ticket_id=item_id,+ comment_id=comment_id,+ human_content=content or "",+ )+ except Exception as e:+ capture_exception(e, {"ticket_id": item_id})+# Customer-facing analytics (to customer's project)if is_team_message:author = User.objects.filter(id=created_by_id).first() if created_by_id else Nonediff --git a/products/conversations/backend/temporal/ai_reply/activities/classify.py b/products/conversations/backend/temporal/ai_reply/activities/classify.pyindex 6236bc7d55b0..918724c3fdb9 100644--- a/products/conversations/backend/temporal/ai_reply/activities/classify.py+++ b/products/conversations/backend/temporal/ai_reply/activities/classify.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json as json_module+from dataclasses import replaceimport structlogfrom temporalio import activity@@ -12,6 +13,7 @@ from products.conversations.backend.temporal.ai_reply.constants import TICKET_TYfrom products.conversations.backend.temporal.ai_reply.llms import (anthropic_text,create_message,+ llm_attempts,strip_json_fence,tracing_kwargs,)@@ -24,7 +26,7 @@ logger = structlog.get_logger(__name__)async def support_classify_activity(input: ClassifyInput) -> ClassifyOutput:"""One-shot LLM triage of a ticket into a type + diagnostics flag + seed search queries."""async with Heartbeater():- return await _classify(input)+ return replace(await _classify(input), llm_attempts=llm_attempts())async def _classify(input: ClassifyInput) -> ClassifyOutput:diff --git a/products/conversations/backend/temporal/ai_reply/activities/draft.py b/products/conversations/backend/temporal/ai_reply/activities/draft.pyindex 6bb7360d454a..340848e15213 100644--- a/products/conversations/backend/temporal/ai_reply/activities/draft.py+++ b/products/conversations/backend/temporal/ai_reply/activities/draft.py@@ -1,5 +1,6 @@from __future__ import annotations+from time import monotonicfrom typing import Anyfrom uuid import UUID@@ -205,6 +206,7 @@ INSTRUCTIONS:Return your response as a JSON object with keys: reply, citations, confidence, sources (a list of {{ref, excerpt}})."""session: MultiTurnSession | None = None+ started = monotonic()try:session, result = await MultiTurnSession.start(prompt,@@ -222,6 +224,7 @@ Return your response as a JSON object with keys: reply, citations, confidence, sconfidence=result.confidence,sources=[{"ref": s.ref, "excerpt": s.excerpt[:MAX_EXCERPT_CHARS]} for s in result.sources[:MAX_SOURCES]],task_run_id=str(session.task_run.id),+ sandbox_seconds=monotonic() - started,)finally:if session is not None:diff --git a/products/conversations/backend/temporal/ai_reply/activities/refine_queries.py b/products/conversations/backend/temporal/ai_reply/activities/refine_queries.pyindex 062d654b69dc..bc87912a380e 100644--- a/products/conversations/backend/temporal/ai_reply/activities/refine_queries.py+++ b/products/conversations/backend/temporal/ai_reply/activities/refine_queries.py@@ -1,12 +1,19 @@from __future__ import annotations+from dataclasses import replace+from temporalio import activityfrom posthog.llm.gateway_client import get_async_anthropic_gateway_clientfrom posthog.temporal.common.heartbeat import Heartbeaterfrom products.conversations.backend.temporal.ai_reply.constants import TICKET_TYPE_HINTS, UTILITY_MODEL-from products.conversations.backend.temporal.ai_reply.llms import anthropic_text, create_message, tracing_kwargs+from products.conversations.backend.temporal.ai_reply.llms import (+ anthropic_text,+ create_message,+ llm_attempts,+ tracing_kwargs,+)from products.conversations.backend.temporal.ai_reply.schemas import RefineQueriesInput, RefineQueriesOutput@@ -14,7 +21,7 @@ from products.conversations.backend.temporal.ai_reply.schemas import RefineQueriasync def support_refine_queries_activity(input: RefineQueriesInput) -> RefineQueriesOutput:"""Use a lightweight LLM to generate search queries from ticket context + missing gaps."""async with Heartbeater():- return await _refine_queries(input)+ return replace(await _refine_queries(input), llm_attempts=llm_attempts())async def _refine_queries(input: RefineQueriesInput) -> RefineQueriesOutput:diff --git a/products/conversations/backend/temporal/ai_reply/activities/review_reply.py b/products/conversations/backend/temporal/ai_reply/activities/review_reply.pyindex 2fcab11f34df..c369f84fc7bd 100644--- a/products/conversations/backend/temporal/ai_reply/activities/review_reply.py+++ b/products/conversations/backend/temporal/ai_reply/activities/review_reply.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json as json_module+from dataclasses import replaceimport structlogfrom pydantic import BaseModel, Field, model_validator@@ -13,6 +14,7 @@ from products.conversations.backend.temporal.ai_reply.constants import MAX_SOURCfrom products.conversations.backend.temporal.ai_reply.llms import (anthropic_text,create_message,+ llm_attempts,strip_json_fence,tracing_kwargs,)@@ -81,7 +83,7 @@ class ReplyReviewResult(BaseModel):async def support_review_reply_activity(input: ReviewReplyInput) -> ReviewReplyOutput:"""Screen the final reply for data exfiltration / PII leakage before persisting."""async with Heartbeater():- return await _review_reply(input)+ return replace(await _review_reply(input), llm_attempts=llm_attempts())async def _review_reply(input: ReviewReplyInput) -> ReviewReplyOutput:diff --git a/products/conversations/backend/temporal/ai_reply/activities/safety_filter.py b/products/conversations/backend/temporal/ai_reply/activities/safety_filter.pyindex 59cec249bb9e..925f5a7214a7 100644--- a/products/conversations/backend/temporal/ai_reply/activities/safety_filter.py+++ b/products/conversations/backend/temporal/ai_reply/activities/safety_filter.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json as json_module+from dataclasses import replaceimport structlogfrom pydantic import BaseModel, Field, model_validator@@ -13,6 +14,7 @@ from products.conversations.backend.temporal.ai_reply.constants import MAX_SAFETfrom products.conversations.backend.temporal.ai_reply.llms import (anthropic_text,create_message,+ llm_attempts,strip_json_fence,tracing_kwargs,)@@ -116,7 +118,7 @@ class SafetyFilterResult(BaseModel):async def support_safety_filter_activity(input: SafetyFilterInput) -> SafetyFilterOutput:"""Screen ticket for prompt injection / data exfiltration before the draft loop."""async with Heartbeater():- return await _safety_filter(input)+ return replace(await _safety_filter(input), llm_attempts=llm_attempts())async def _safety_filter(input: SafetyFilterInput) -> SafetyFilterOutput:diff --git a/products/conversations/backend/temporal/ai_reply/activities/validate.py b/products/conversations/backend/temporal/ai_reply/activities/validate.pyindex 9cbe2d797418..adb982b163a0 100644--- a/products/conversations/backend/temporal/ai_reply/activities/validate.py+++ b/products/conversations/backend/temporal/ai_reply/activities/validate.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json as json_module+from dataclasses import replaceimport structlogfrom temporalio import activity@@ -14,6 +15,7 @@ from products.conversations.backend.temporal.ai_reply.constants import TICKET_TYfrom products.conversations.backend.temporal.ai_reply.llms import (anthropic_text,create_message,+ llm_attempts,strip_json_fence,tracing_kwargs,)@@ -26,7 +28,7 @@ logger = structlog.get_logger(__name__)async def support_validate_activity(input: ValidateInput) -> ValidateOutput:"""Validate the draft reply against the source chunks for groundedness and coverage."""async with Heartbeater():- return await _validate(input)+ return replace(await _validate(input), llm_attempts=llm_attempts())async def _validate(input: ValidateInput) -> ValidateOutput:diff --git a/products/conversations/backend/temporal/ai_reply/llms.py b/products/conversations/backend/temporal/ai_reply/llms.pyindex c1e9f39aebc8..ac213f1233b1 100644--- a/products/conversations/backend/temporal/ai_reply/llms.py+++ b/products/conversations/backend/temporal/ai_reply/llms.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom typing import Anyfrom anthropic import APIError+from temporalio import activityfrom temporalio.exceptions import ApplicationErrorfrom products.conversations.backend.temporal.ai_reply.constants import LLM_REQUEST_TIMEOUT_SECONDS@@ -66,3 +67,11 @@ def strip_json_fence(text: str) -> str:if close != -1:s = s[:close]return s.strip()+++def llm_attempts() -> int:+ """Temporal attempt number for this LLM activity, including retries already spent."""+ try:+ return max(1, int(activity.info().attempt))+ except RuntimeError:+ return 1diff --git a/products/conversations/backend/temporal/ai_reply/schemas.py b/products/conversations/backend/temporal/ai_reply/schemas.pyindex 27f4a8f59b24..e983b1ef4c44 100644--- a/products/conversations/backend/temporal/ai_reply/schemas.py+++ b/products/conversations/backend/temporal/ai_reply/schemas.py@@ -42,11 +42,12 @@ class ClassifyInput:ticket_id: str = ""-@dataclass+@dataclass(frozen=False)class ClassifyOutput:ticket_type: strneeds_diagnostics: boolseed_queries: list[str] = field(default_factory=list)+ llm_attempts: int = 1@dataclass@@ -60,9 +61,10 @@ class RefineQueriesInput:ticket_id: str = ""-@dataclass+@dataclass(frozen=False)class RefineQueriesOutput:queries: list[str]+ llm_attempts: int = 1@dataclass@@ -102,7 +104,7 @@ class DraftInput:auto_publishable: bool = False-@dataclass+@dataclass(frozen=False)class DraftOutput:reply: strcitations: list[str]@@ -112,6 +114,9 @@ class DraftOutput:sources: list[dict[str, str]] = field(default_factory=list)# The Tasks TaskRun id for this draft session -- join key to LLMA cost data.task_run_id: str = ""+ # Wall time of the sandbox session, recorded for ai_triage.cost. Defaults so+ # histories from before this field still deserialize.+ sandbox_seconds: float = 0.0@dataclass@@ -127,12 +132,13 @@ class ValidateInput:ticket_id: str = ""-@dataclass+@dataclass(frozen=False)class ValidateOutput:grounded: boolcoverage: floatconfidence: floatmissing: list[str]+ llm_attempts: int = 1@dataclass@@ -161,11 +167,12 @@ class SafetyFilterInput:ticket_id: str = ""-@dataclass+@dataclass(frozen=False)class SafetyFilterOutput:safe: boolthreat_type: str = ""explanation: str = ""+ llm_attempts: int = 1@dataclass@@ -179,10 +186,11 @@ class ReviewReplyInput:ticket_id: str = ""-@dataclass+@dataclass(frozen=False)class ReviewReplyOutput:safe: boolreason: str = ""+ llm_attempts: int = 1@dataclassdiff --git a/products/conversations/backend/temporal/pipeline.py b/products/conversations/backend/temporal/pipeline.pyindex 7eda6f0432a3..04eb669889fe 100644--- a/products/conversations/backend/temporal/pipeline.py+++ b/products/conversations/backend/temporal/pipeline.py@@ -6,6 +6,7 @@ from uuid import uuid5from temporalio import workflowfrom temporalio.common import RetryPolicy+from temporalio.exceptions import ActivityError, RetryStatefrom products.conversations.backend.temporal.ai_reply.activities.build_context import support_build_context_activityfrom products.conversations.backend.temporal.ai_reply.activities.classify import support_classify_activity@@ -48,6 +49,15 @@ from products.conversations.backend.temporal.ai_reply.schemas import (with workflow.unsafe.imports_passed_through():pass++def _bill_llm_activity(*, output: Any | None, error: BaseException | None, maximum_attempts: int) -> int:+ if error is None:+ return max(1, int(getattr(output, "llm_attempts", 1) or 1))+ if isinstance(error, ActivityError) and error.retry_state == RetryState.NON_RETRYABLE_FAILURE:+ return 1+ return maximum_attempts++# ---------------------------------------------------------------------------# Workflow# ---------------------------------------------------------------------------@@ -150,16 +160,33 @@ class SupportReplyWorkflow:# --- Outcome tracking: set before each return, recorded in finally ---outcome: dict[str, Any] = {}draft_task_run_ids: list[str] = []+ llm_calls = 0+ sandbox_seconds = 0.0++ async def _llm(activity_fn: Any, input_value: Any, *, timeout: timedelta, maximum_attempts: int = 3) -> Any:+ nonlocal llm_calls+ try:+ output = await workflow.execute_activity(+ activity_fn,+ input_value,+ start_to_close_timeout=timeout,+ retry_policy=RetryPolicy(maximum_attempts=maximum_attempts),+ )+ llm_calls += _bill_llm_activity(output=output, error=None, maximum_attempts=maximum_attempts)+ return output+ except Exception as error:+ llm_calls += _bill_llm_activity(output=None, error=error, maximum_attempts=maximum_attempts)+ raise+try:# Input safety gate: block prompt-injection / exfiltration attempts before any LLM# draft work. Mirrored from the signals product's safety_filter_activity pattern.- safety_output = await workflow.execute_activity(+ safety_output = await _llm(support_safety_filter_activity,SafetyFilterInput(team_id=input.team_id, ticket_context=reviewed_context, trace_id=trace_id, ticket_id=ticket_id),- start_to_close_timeout=timedelta(minutes=2),- retry_policy=RetryPolicy(maximum_attempts=3),+ timeout=timedelta(minutes=2),)if not safety_output.safe:workflow.logger.info(@@ -170,13 +197,12 @@ class SupportReplyWorkflow:# Triage once, up front (not per attempt): the type + seed queries bias the whole# loop, and `unactionable` tickets (spam/bare feedback) skip the expensive draft loop.- classify_output = await workflow.execute_activity(+ classify_output = await _llm(support_classify_activity,ClassifyInput(team_id=input.team_id, ticket_context=reviewed_context, trace_id=trace_id, ticket_id=ticket_id),- start_to_close_timeout=timedelta(minutes=2),- retry_policy=RetryPolicy(maximum_attempts=3),+ timeout=timedelta(minutes=2),)if classify_output.ticket_type == "unactionable":# Distinct outcome from `escalated_no_reply` (which means "tried and exhausted@@ -205,7 +231,7 @@ class SupportReplyWorkflow:widen = attempt > 0# Refine queries- refine_output = await workflow.execute_activity(+ refine_output = await _llm(support_refine_queries_activity,RefineQueriesInput(team_id=input.team_id,@@ -216,8 +242,7 @@ class SupportReplyWorkflow:trace_id=trace_id,ticket_id=ticket_id,),- start_to_close_timeout=timedelta(minutes=2),- retry_policy=RetryPolicy(maximum_attempts=3),+ timeout=timedelta(minutes=2),)# Retrieve + rerank@@ -257,12 +282,14 @@ class SupportReplyWorkflow:start_to_close_timeout=timedelta(minutes=20),retry_policy=RetryPolicy(maximum_attempts=2),)+ # Default 0.0 on histories recorded before DraftOutput.sandbox_seconds existed.+ sandbox_seconds += getattr(draft_output, "sandbox_seconds", 0.0) or 0.0if draft_output.task_run_id:draft_task_run_ids.append(draft_output.task_run_id)# Validate- validate_output = await workflow.execute_activity(+ validate_output = await _llm(support_validate_activity,ValidateInput(team_id=input.team_id,@@ -275,8 +302,7 @@ class SupportReplyWorkflow:trace_id=trace_id,ticket_id=ticket_id,),- start_to_close_timeout=timedelta(minutes=2),- retry_policy=RetryPolicy(maximum_attempts=3),+ timeout=timedelta(minutes=2),)# Track best-so-far by the validator's confidence (the trusted score, same@@ -292,7 +318,7 @@ class SupportReplyWorkflow:if validate_output.confidence >= SCORE_THRESHOLD:# Output safety gate: check for PII leaks / exfil before the reply reaches# the (untrusted) ticket author.- review_output = await workflow.execute_activity(+ review_output = await _llm(support_review_reply_activity,ReviewReplyInput(team_id=input.team_id,@@ -303,8 +329,7 @@ class SupportReplyWorkflow:trace_id=trace_id,ticket_id=ticket_id,),- start_to_close_timeout=timedelta(minutes=2),- retry_policy=RetryPolicy(maximum_attempts=3),+ timeout=timedelta(minutes=2),)if not review_output.safe:workflow.logger.info(@@ -355,7 +380,7 @@ class SupportReplyWorkflow:# Exhausted attempts — persist best if we have one with non-zero confidenceif best_reply and best_confidence > 0:- review_output = await workflow.execute_activity(+ review_output = await _llm(support_review_reply_activity,ReviewReplyInput(team_id=input.team_id,@@ -366,8 +391,7 @@ class SupportReplyWorkflow:trace_id=trace_id,ticket_id=ticket_id,),- start_to_close_timeout=timedelta(minutes=2),- retry_policy=RetryPolicy(maximum_attempts=3),+ timeout=timedelta(minutes=2),)if not review_output.safe:workflow.logger.info(@@ -432,5 +456,9 @@ class SupportReplyWorkflow:"finished_at": workflow.now().isoformat(),"ai_trace_id": trace_id,"draft_task_run_ids": draft_task_run_ids,+ "cost": {+ "sandbox_seconds": round(sandbox_seconds, 3),+ "llm_calls": llm_calls,+ },})diff --git a/products/conversations/backend/temporal/tests/test_pipeline.py b/products/conversations/backend/temporal/tests/test_pipeline.pyindex e8f6980e03b8..e2358ed266a3 100644--- a/products/conversations/backend/temporal/tests/test_pipeline.py+++ b/products/conversations/backend/temporal/tests/test_pipeline.py@@ -6,6 +6,7 @@ import pytestfrom unittest.mock import AsyncMock, MagicMock, patchfrom parameterized import parameterized+from temporalio.exceptions import ActivityError, RetryStatefrom posthog.models import Organization, Team@@ -54,6 +55,7 @@ from products.conversations.backend.temporal.ai_reply.schemas import ()from products.conversations.backend.temporal.pipeline import (SupportReplyWorkflow,+ _bill_llm_activity,support_build_context_activity,support_classify_activity,support_draft_activity,@@ -1584,6 +1586,7 @@ class TestRecordTriageActivity:reply="answer",citations=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],confidence=0.9,+ sandbox_seconds=1.5,),),patch(@@ -1642,6 +1645,22 @@ class TestRecordTriageActivity:assert last_call_patch["status"] == "done"assert last_call_patch["result"] == expected_resultassert "finished_at" in last_call_patch+ expected_llm_calls = {+ "persisted": 5,+ "blocked_unsafe": 1,+ "skipped_unactionable": 2,+ "blocked_unsafe_reply": 5,+ }[_name]+ expected_sandbox = {+ "persisted": 1.5,+ "blocked_unsafe": 0.0,+ "skipped_unactionable": 0.0,+ "blocked_unsafe_reply": 1.5,+ }[_name]+ assert last_call_patch["cost"] == {+ "sandbox_seconds": expected_sandbox,+ "llm_calls": expected_llm_calls,+ }@pytest.mark.django_db@pytest.mark.asyncio@@ -1673,7 +1692,7 @@ class TestRecordTriageActivity:patch(f"{DRAFT_MODULE}._draft_async",new_callable=AsyncMock,- return_value=DraftOutput(reply="", citations=[], confidence=0.0),+ return_value=DraftOutput(reply="", citations=[], confidence=0.0, sandbox_seconds=0.25),),patch(f"{VALIDATE_MODULE}._validate",@@ -1719,6 +1738,89 @@ class TestRecordTriageActivity:assert last_call_patch["status"] == "done"assert last_call_patch["result"] == "escalated_no_reply"assert last_call_patch["attempts"] == MAX_ATTEMPTS+ assert last_call_patch["cost"]["sandbox_seconds"] == pytest.approx(0.25 * MAX_ATTEMPTS)+ assert last_call_patch["cost"]["llm_calls"] == 2 + MAX_ATTEMPTS * 2++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_retried_classify_bills_all_attempts(self):+ from temporalio.testing import WorkflowEnvironment+ from temporalio.worker import Worker++ classify_calls = {"n": 0}++ async def flaky_classify(_input: ClassifyInput) -> ClassifyOutput:+ classify_calls["n"] += 1+ if classify_calls["n"] < 3:+ raise RuntimeError("transient classify failure")+ return ClassifyOutput(ticket_type="unactionable", needs_diagnostics=False)++ with (+ patch(+ f"{BUILD_CONTEXT_MODULE}._build_context_sync",+ return_value=BuildContextOutput(ticket_context="help", ticket_title="Help"),+ ),+ patch(+ f"{SAFETY_FILTER_MODULE}._safety_filter",+ new_callable=AsyncMock,+ return_value=SafetyFilterOutput(safe=True),+ ),+ patch(f"{CLASSIFY_MODULE}._classify", new=flaky_classify),+ patch(f"{RECORD_TRIAGE_MODULE}._record_triage_sync") as mock_record_triage,+ ):+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue="test-queue",+ workflows=[SupportReplyWorkflow],+ activities=[+ support_build_context_activity,+ support_safety_filter_activity,+ support_classify_activity,+ support_record_triage_activity,+ ],+ ):+ result = await env.client.execute_workflow(+ SupportReplyWorkflow.run,+ SupportReplyInput(team_id=1, ticket_id="deadbeef-0000-0000-0000-000000000001"),+ id="test-triage-retried-classify",+ task_queue="test-queue",+ )++ assert result == "skipped_unactionable"+ assert classify_calls["n"] == 3+ last_call_patch = mock_record_triage.call_args_list[-1][0][0].patch+ assert last_call_patch["cost"]["llm_calls"] == 4+++def _activity_error(retry_state: RetryState) -> ActivityError:+ return ActivityError(+ "activity failed",+ scheduled_event_id=1,+ started_event_id=2,+ identity="test-worker",+ activity_type="support_classify_activity",+ activity_id="classify-1",+ retry_state=retry_state,+ )+++class TestBillLlmActivity:+ def test_success_uses_stamped_attempts(self):+ output = ClassifyOutput(ticket_type="how_to", needs_diagnostics=False, llm_attempts=3)+ assert _bill_llm_activity(output=output, error=None, maximum_attempts=3) == 3++ def test_missing_stamp_defaults_to_one(self):+ output = ClassifyOutput(ticket_type="how_to", needs_diagnostics=False)+ assert _bill_llm_activity(output=output, error=None, maximum_attempts=3) == 1++ def test_exhausted_retries_bill_cap(self):+ error = _activity_error(RetryState.MAXIMUM_ATTEMPTS_REACHED)+ assert _bill_llm_activity(output=None, error=error, maximum_attempts=3) == 3++ def test_non_retryable_bills_one(self):+ error = _activity_error(RetryState.NON_RETRYABLE_FAILURE)+ assert _bill_llm_activity(output=None, error=error, maximum_attempts=3) == 1class TestRecordTriageSync:diff --git a/products/conversations/backend/tests/test_support_reply_eval.py b/products/conversations/backend/tests/test_support_reply_eval.pynew file mode 100644index 000000000000..649b135a38c7--- /dev/null+++ b/products/conversations/backend/tests/test_support_reply_eval.py@@ -0,0 +1,143 @@+import asyncio++import pytest++from django.test import SimpleTestCase++from parameterized import parameterized++from products.conversations.evals.constants import BLOCKER_TYPES, EVAL_OUTCOMES, TICKET_TYPES+from products.conversations.evals.fixtures import FIXTURES, FIXTURES_BY_NAME, expected_for+from products.conversations.evals.outcomes import eval_outcome_from_triage+from products.conversations.evals.runner import run_fixture+from products.conversations.evals.scorers import (+ CitationPrecision,+ ClarifyingQuestion,+ CostScorer,+ ForbiddenClaims,+ Grounding,+ OutcomeMatch,+)+from products.conversations.evals.seeders import provision_eval_team, seed_case, teardown_eval_team+from products.posthog_ai.eval_harness.scorers.contract import Score+++class TestEvalOutcomeFromTriage(SimpleTestCase):+ @parameterized.expand(+ [+ ("persisted_is_answerable", {"status": "done", "result": "persisted"}, "answerable"),+ ("escalated_with_best", {"status": "done", "result": "escalated_with_best"}, "escalate"),+ ("skipped_unactionable", {"status": "done", "result": "skipped_unactionable"}, "escalate"),+ ("unknown_result_is_unscored", {"status": "done", "result": "mystery"}, None),+ (+ "clarification_status_wins",+ {"status": "awaiting_clarification", "result": "persisted"},+ "needs_clarification",+ ),+ ("unfinished_run", {"status": "in_progress"}, None),+ ]+ )+ def test_maps_triage(self, _name, triage, expected):+ assert eval_outcome_from_triage(triage) == expected+++class TestSupportReplyScorers(SimpleTestCase):+ def test_outcome_match_scores_equality(self):+ expected = {"outcome_match": {"outcome": "answerable"}}+ assert OutcomeMatch()._run_eval_sync({"eval_outcome": "answerable"}, expected).score == 1.0+ assert OutcomeMatch()._run_eval_sync({"eval_outcome": "escalate"}, expected).score == 0.0+ assert (+ OutcomeMatch()._run_eval_sync({"eval_outcome": None}, {"outcome_match": {"outcome": "escalate"}}).score+ == 0.0+ )++ def test_citation_precision_skips_when_no_expected_sources(self):+ score = CitationPrecision()._run_eval_sync(+ {"citation_source_names": ["JavaScript SDK install"]},+ {"citation_precision": {"source_names": []}},+ )+ assert score.score is None++ def test_citation_precision_is_hits_over_cited(self):+ score = CitationPrecision()._run_eval_sync(+ {"citation_source_names": ["JavaScript SDK install", "Invoices and billing"]},+ {"citation_precision": {"source_names": ["JavaScript SDK install"]}},+ )+ assert score.score == 0.5++ def test_forbidden_claims_are_case_insensitive(self):+ expected = {"forbidden_claims": {"phrases": ["I'll refund"]}}+ hit = ForbiddenClaims()._run_eval_sync({"reply": "Sure, i'll refund this."}, expected)+ miss = ForbiddenClaims()._run_eval_sync({"reply": "Download the invoice PDF."}, expected)+ assert hit.score == 0.0+ assert miss.score == 1.0++ def test_cost_fails_when_llm_calls_missing_or_not_int(self):+ expected: dict[str, dict[str, object]] = {"cost": {}}+ missing = CostScorer()._run_eval_sync({"cost": {"sandbox_seconds": 1.2}}, expected)+ coerced = CostScorer()._run_eval_sync({"cost": {"sandbox_seconds": 1.2, "llm_calls": 3.0}}, expected)+ ok = CostScorer()._run_eval_sync({"cost": {"sandbox_seconds": 0.0, "llm_calls": 5}}, expected)+ assert missing.score == 0.0+ assert coerced.score == 0.0+ assert ok.score == 1.0++ def test_grounding_skips_unless_required(self):+ prepared = Grounding()._prepare({"reply": "hello"}, expected_for(FIXTURES_BY_NAME["how_to_events_missing_sdk"]))+ assert isinstance(prepared, Score)+ assert prepared.score is None++ def test_grounding_fails_empty_reply_when_required(self):+ prepared = Grounding()._prepare({"reply": ""}, expected_for(FIXTURES_BY_NAME["how_to_sdk_install"]))+ assert isinstance(prepared, Score)+ assert prepared.score == 0.0++ def test_clarifying_question_uses_reply_question_mark(self):+ prepared = ClarifyingQuestion()._prepare(+ {"prompt": "Events aren't showing up.", "reply": "Which SDK are you using?"},+ expected_for(FIXTURES_BY_NAME["how_to_events_missing_sdk"]),+ )+ assert isinstance(prepared, dict)+ assert "Which SDK" in prepared["output"]["questions"]++ def test_clarifying_question_fails_without_a_question(self):+ prepared = ClarifyingQuestion()._prepare(+ {"prompt": "It's broken.", "reply": "I cannot help with that."},+ expected_for(FIXTURES_BY_NAME["how_to_events_missing_sdk"]),+ )+ assert isinstance(prepared, Score)+ assert prepared.score == 0.0+++class TestFixtureCoverage(SimpleTestCase):+ def test_every_ticket_type_and_blocker_has_a_fixture(self):+ assert {fixture.ticket_type for fixture in FIXTURES} == set(TICKET_TYPES)+ assert {fixture.blocker for fixture in FIXTURES} == set(BLOCKER_TYPES)+ assert {fixture.expected_outcome for fixture in FIXTURES} == set(EVAL_OUTCOMES)++[email protected]_db(transaction=True)+async def test_mocked_runner_persists_answerable_fixture_and_cost():+ fixture = FIXTURES_BY_NAME["how_to_sdk_install"]+ eval_team = await asyncio.to_thread(lambda: provision_eval_team(label="pytest-sdk"))+ try:+ seed = await asyncio.to_thread(lambda: seed_case(eval_team=eval_team, fixture=fixture))+ output = await run_fixture(fixture, seed, live=False)+ assert output.get("error") is None+ assert output["eval_outcome"] == "answerable"+ assert "JavaScript SDK install" in output["citation_source_names"]+ excerpts = output["source_excerpts"]+ assert excerpts+ assert any("YOUR_PROJECT_TOKEN" in (item.get("excerpt") or "") for item in excerpts)+ assert output["cost"]["llm_calls"] == 5+ assert output["cost"]["sandbox_seconds"] == 0.0+ scores = {+ scorer._name(): scorer._run_eval_sync(output, expected_for(fixture))+ for scorer in (OutcomeMatch(), CitationPrecision(), ForbiddenClaims(), CostScorer())+ }+ assert scores["outcome_match"].score == 1.0+ assert scores["citation_precision"].score == 1.0+ assert scores["forbidden_claims"].score == 1.0+ assert scores["cost"].score == 1.0+ finally:+ await asyncio.to_thread(lambda: teardown_eval_team(eval_team=eval_team))diff --git a/products/conversations/evals/__init__.py b/products/conversations/evals/__init__.pynew file mode 100644index 000000000000..caa1ee040c86--- /dev/null+++ b/products/conversations/evals/__init__.py@@ -0,0 +1,5 @@+"""Support-reply eval suite.++Discovered by the shared harness (`hogli evals eval_support_reply`). The mocked+variant also runs via `python manage.py run_support_reply_eval`.+"""diff --git a/products/conversations/evals/constants.py b/products/conversations/evals/constants.pynew file mode 100644index 000000000000..91f7812bfc04--- /dev/null+++ b/products/conversations/evals/constants.py@@ -0,0 +1,38 @@+"""Literals shared by the corpus, fixtures, seeders, and scorers."""++from __future__ import annotations++from typing import Literal++EvalOutcome = Literal["answerable", "needs_clarification", "escalate"]+BlockerType = Literal["none", "customer_info", "knowledge", "contradiction"]+TicketType = Literal["how_to", "diagnostic", "account_billing", "bug", "unactionable"]++SOURCE_SDK_INSTALL = "JavaScript SDK install"+SOURCE_BILLING_INVOICES = "Invoices and billing"+SOURCE_REPLAY_BLANK = "Blank session recordings"+SOURCE_RECORDING_RETENTION = "Session recording retention"+SOURCE_TEAM_POLICY = "Support reply policy"++EVAL_OUTCOMES: tuple[EvalOutcome, ...] = ("answerable", "needs_clarification", "escalate")+BLOCKER_TYPES: tuple[BlockerType, ...] = ("none", "customer_info", "knowledge", "contradiction")+TICKET_TYPES: tuple[TicketType, ...] = ("how_to", "diagnostic", "account_billing", "bug", "unactionable")++# Pipeline `ai_triage.result` values the loop can emit, mapped to the eval outcome+# the fixture asks for.+PIPELINE_RESULT_TO_EVAL_OUTCOME: dict[str, EvalOutcome] = {+ "persisted": "answerable",+ "escalated_with_best": "escalate",+ "escalated_no_reply": "escalate",+ "escalated_with_findings": "escalate",+ "escalated_budget_exhausted": "escalate",+ "skipped_unactionable": "escalate",+ "blocked_unsafe": "escalate",+ "blocked_unsafe_reply": "escalate",+}++# Persist-reply posts a clarifying question and sets this status. Map it here so+# fixtures that expect needs_clarification score correctly once that branch exists.+CLARIFICATION_TRIAGE_STATUS = "awaiting_clarification"++LIVE_EVAL_ENV_VAR = "SUPPORT_REPLY_EVAL_LIVE"diff --git a/products/conversations/evals/corpus.py b/products/conversations/evals/corpus.pynew file mode 100644index 000000000000..77f14fea16b2--- /dev/null+++ b/products/conversations/evals/corpus.py@@ -0,0 +1,91 @@+"""Invented business-knowledge corpus for support-reply evals.++Pure and Django-free so the texts can be asserted in unit tests without a database.+Every document is about Acme Capture, a fictional SDK at docs.example.com.+"""++from __future__ import annotations++from posthog.dataclasses import frozen++from products.conversations.evals.constants import (+ SOURCE_BILLING_INVOICES,+ SOURCE_RECORDING_RETENTION,+ SOURCE_REPLAY_BLANK,+ SOURCE_SDK_INSTALL,+ SOURCE_TEAM_POLICY,+)+++@frozen+class CorpusDocument:+ name: str+ text: str+ always_include: bool = False+++CORPUS: tuple[CorpusDocument, ...] = (+ CorpusDocument(+ name=SOURCE_SDK_INSTALL,+ text=(+ "Install the Acme Capture JavaScript SDK on any site you own.\n\n"+ "Add this snippet to the <head> of every page on app.example.com:\n"+ "<script>acmeCapture.init({ apiHost: 'https://api.example.com', projectToken: 'YOUR_PROJECT_TOKEN' })</script>\n\n"+ "Replace YOUR_PROJECT_TOKEN with the token from Project settings. After a reload, "+ "the SDK sends a $pageview for that URL. Use the same projectToken in iOS and Android "+ "if you want one project to receive every platform. Do not put the token in a public "+ "GitHub issue; rotate it from Project settings if it leaks.\n\n"+ "If events never arrive, confirm the snippet is on the page that fired, the token "+ "matches the project, and an ad blocker is not stripping api.example.com."+ ),+ ),+ CorpusDocument(+ name=SOURCE_BILLING_INVOICES,+ text=(+ "Download invoices from Organization settings > Billing > Invoices on app.example.com.\n\n"+ "Each invoice is a PDF for one calendar month. The billing email on the organization "+ "receives a copy when the invoice is issued. Changing the billing email does not "+ "resend old invoices; download those from the Invoices list.\n\n"+ "Plan changes take effect at the next renewal. Usage for the current period is billed "+ "on the existing plan. Support agents must not issue refunds or credits. Billing "+ "disputes go to the billing team with the organization id and invoice month."+ ),+ ),+ CorpusDocument(+ name=SOURCE_REPLAY_BLANK,+ text=(+ "A session recording that opens as a blank canvas usually means the recorder never "+ "captured DOM snapshots for that session.\n\n"+ "Check, in order: (1) the recording SDK snippet is on the page, (2) the project has "+ "session replay enabled under Project settings > Replay, (3) the session is not "+ "excluded by a URL-blocklist rule, (4) the customer is not blocking the recorder "+ "domain in an ad blocker. A recording with events but no snapshots will still list "+ "in Replay and open blank.\n\n"+ "If those four checks pass, ask for the session id (32-character hex) and the page "+ "URL. Do not ask for cookies or auth tokens."+ ),+ ),+ CorpusDocument(+ name=SOURCE_RECORDING_RETENTION,+ text=(+ "Acme Capture retains session recordings for 30 days on every paid plan.\n\n"+ "The retention clock starts when the session ends. After 30 days the recording is "+ "deleted and cannot be restored. Free plans retain recordings for 7 days. There is "+ "no per-project override; changing plan does not resurrect recordings already deleted.\n\n"+ "A recording that vanished after 3 days is not explained by this policy. Treat that "+ "as a product defect: collect the session id, the project token last-4, and when the "+ "customer last opened the recording, then escalate to engineering."+ ),+ ),+ CorpusDocument(+ name=SOURCE_TEAM_POLICY,+ always_include=True,+ text=(+ "Support reply policy for Acme Capture.\n\n"+ "Lead with the answer. Cite the knowledge base. Never invent a configuration that "+ "is not in these documents. Never promise a refund, a credit, or a plan exception; "+ "those go to the billing team. Never ask the customer to paste an API key, cookie, "+ "or password into the ticket. One question at a time when something is missing."+ ),+ ),+)diff --git a/products/conversations/evals/eval_support_reply.py b/products/conversations/evals/eval_support_reply.pynew file mode 100644index 000000000000..7fbab0d10a1e--- /dev/null+++ b/products/conversations/evals/eval_support_reply.py@@ -0,0 +1,66 @@+"""One-shot eval of the grounded support-reply pipeline.++Invented tickets (example.com, fake ids) plus a seeded business-knowledge corpus.+Mocked by default (sandbox draft stubbed). Set SUPPORT_REPLY_EVAL_LIVE=1 to run+the real draft agent.++Public rather than private: the suite compares a baseline against a later prompt+or model change, and that history lives in Braintrust. Every ticket and corpus+document is invented, so there is no customer text to keep off the wire.++To run:+ hogli evals eval_support_reply+ hogli evals eval_support_reply --eval how_to_sdk_install+ SUPPORT_REPLY_EVAL_LIVE=1 hogli evals eval_support_reply --eval how_to_sdk_install+"""++from __future__ import annotations++import asyncio++from products.conversations.evals.constants import LIVE_EVAL_ENV_VAR+from products.conversations.evals.fixtures import FIXTURES, FIXTURES_BY_NAME, expected_for+from products.conversations.evals.runner import live_eval_enabled, run_fixture+from products.conversations.evals.scorers import ALL_SCORERS+from products.conversations.evals.seeders import provision_eval_team, seed_case, teardown_eval_team+from products.posthog_ai.eval_harness.config import BaseEvalCase+from products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.harness.requirements import SuiteKind+from products.posthog_ai.eval_harness.one_shot import OneShotPublicEval++SUITE_KIND = SuiteKind.ONE_SHOT++CASES = [+ BaseEvalCase(+ name=fixture.name,+ prompt=fixture.prompt,+ expected=expected_for(fixture),+ metadata={+ "ticket_type": fixture.ticket_type,+ "blocker": fixture.blocker,+ "expected_outcome": fixture.expected_outcome,+ "live_env_var": LIVE_EVAL_ENV_VAR,+ },+ )+ for fixture in FIXTURES+]+++async def eval_support_reply(ctx: EvalContext) -> None:+ async def task(case: BaseEvalCase, task_ctx: EvalContext) -> dict:+ fixture = FIXTURES_BY_NAME[case.name]+ live = live_eval_enabled()+ eval_team = await asyncio.to_thread(lambda: provision_eval_team(label=fixture.name))+ try:+ seed = await asyncio.to_thread(lambda: seed_case(eval_team=eval_team, fixture=fixture))+ return await run_fixture(fixture, seed, live=live)+ finally:+ await asyncio.to_thread(lambda: teardown_eval_team(eval_team=eval_team))++ await OneShotPublicEval(+ experiment_name="support-reply-pipeline",+ cases=CASES,+ scorers=list(ALL_SCORERS),+ task=task,+ ctx=ctx,+ )diff --git a/products/conversations/evals/fixtures.py b/products/conversations/evals/fixtures.pynew file mode 100644index 000000000000..5187aaffb832--- /dev/null+++ b/products/conversations/evals/fixtures.py@@ -0,0 +1,272 @@+"""Invented support tickets for the reply-pipeline eval.++Each fixture is a customer message plus the outcome the pipeline should reach, the+BK sources a grounded answer may cite, and the canned draft/validate the mocked+runner injects. Live runs ignore the canned draft and hit the real sandbox.+"""++from __future__ import annotations++from typing import Any++from posthog.dataclasses import frozen++from products.conversations.evals.constants import (+ SOURCE_BILLING_INVOICES,+ SOURCE_RECORDING_RETENTION,+ SOURCE_REPLAY_BLANK,+ SOURCE_SDK_INSTALL,+ BlockerType,+ EvalOutcome,+ TicketType,+)+++@frozen+class MockedDraft:+ reply: str+ citation_sources: tuple[str, ...]+ confidence: float+ excerpts: tuple[tuple[str, str], ...] = ()+++@frozen+class MockedValidate:+ grounded: bool+ coverage: float+ confidence: float+ missing: tuple[str, ...] = ()+++@frozen+class SupportReplyFixture:+ name: str+ prompt: str+ ticket_type: TicketType+ expected_outcome: EvalOutcome+ blocker: BlockerType+ seed_queries: tuple[str, ...]+ expected_citation_sources: tuple[str, ...] = ()+ forbidden_claims: tuple[str, ...] = ()+ needs_diagnostics: bool = False+ mocked_draft: MockedDraft | None = None+ mocked_validate: MockedValidate | None = None+++def expected_for(fixture: SupportReplyFixture) -> dict[str, Any]:+ """Scorer `expected` payload, keyed by each scorer's `_name()`."""+ payload: dict[str, Any] = {+ "outcome_match": {"outcome": fixture.expected_outcome},+ "citation_precision": {"source_names": list(fixture.expected_citation_sources)},+ "forbidden_claims": {"phrases": list(fixture.forbidden_claims)},+ "cost": {},+ }+ if fixture.expected_outcome == "answerable":+ payload["grounding"] = {"required": True}+ if fixture.expected_outcome == "needs_clarification":+ payload["clarifying_question"] = {"required": True}+ return payload+++_ANSWERABLE_VALIDATE = MockedValidate(grounded=True, coverage=0.9, confidence=0.9)+_LOW_VALIDATE = MockedValidate(+ grounded=False,+ coverage=0.2,+ confidence=0.2,+ missing=("customer did not specify the missing fact",),+)+++FIXTURES: tuple[SupportReplyFixture, ...] = (+ SupportReplyFixture(+ name="how_to_sdk_install",+ prompt=(+ "Hi, we just signed up for Acme Capture. How do I install the JavaScript SDK "+ "on app.example.com so pageviews start showing up?"+ ),+ ticket_type="how_to",+ expected_outcome="answerable",+ blocker="none",+ seed_queries=("install javascript SDK", "acmeCapture.init"),+ expected_citation_sources=(SOURCE_SDK_INSTALL,),+ forbidden_claims=("refund",),+ mocked_draft=MockedDraft(+ reply=(+ "Add the Acme Capture snippet to the <head> of every page on app.example.com, "+ "with apiHost https://api.example.com and your project token from Project settings. "+ "A reload should send a $pageview."+ ),+ citation_sources=(SOURCE_SDK_INSTALL,),+ confidence=0.9,+ excerpts=((SOURCE_SDK_INSTALL, "acmeCapture.init({ apiHost: 'https://api.example.com'"),),+ ),+ mocked_validate=_ANSWERABLE_VALIDATE,+ ),+ SupportReplyFixture(+ name="diagnostic_blank_replay",+ prompt=(+ "Session replay for checkout on app.example.com/checkout opens as a blank white "+ "canvas. The session still appears in the list. What should we check?"+ ),+ ticket_type="diagnostic",+ expected_outcome="answerable",+ blocker="none",+ needs_diagnostics=True,+ seed_queries=("blank session recording", "blank canvas replay"),+ expected_citation_sources=(SOURCE_REPLAY_BLANK,),+ mocked_draft=MockedDraft(+ reply=(+ "A listed recording that opens blank usually means no DOM snapshots were stored. "+ "Confirm the recorder snippet is on that page, Replay is enabled, the URL is not "+ "blocklisted, and an ad blocker is not stripping the recorder domain."+ ),+ citation_sources=(SOURCE_REPLAY_BLANK,),+ confidence=0.85,+ excerpts=((SOURCE_REPLAY_BLANK, "blank canvas usually means the recorder never captured"),),+ ),+ mocked_validate=_ANSWERABLE_VALIDATE,+ ),+ SupportReplyFixture(+ name="account_billing_invoices",+ prompt="Where do I download last month's invoice PDF for our organization?",+ ticket_type="account_billing",+ expected_outcome="answerable",+ blocker="none",+ seed_queries=("download invoice PDF", "billing invoices"),+ expected_citation_sources=(SOURCE_BILLING_INVOICES,),+ forbidden_claims=("I'll refund", "full refund", "I'll issue a credit"),+ mocked_draft=MockedDraft(+ reply=(+ "Open Organization settings > Billing > Invoices on app.example.com. Each month "+ "is a PDF. Changing the billing email does not resend old invoices."+ ),+ citation_sources=(SOURCE_BILLING_INVOICES,),+ confidence=0.9,+ excerpts=((SOURCE_BILLING_INVOICES, "Organization settings > Billing > Invoices"),),+ ),+ mocked_validate=_ANSWERABLE_VALIDATE,+ ),+ SupportReplyFixture(+ name="how_to_events_missing_sdk",+ prompt="Events aren't showing up in Acme Capture. Can you fix it?",+ ticket_type="how_to",+ expected_outcome="needs_clarification",+ blocker="customer_info",+ seed_queries=("events not showing", "events missing"),+ mocked_draft=MockedDraft(+ reply="Which SDK are you using?",+ citation_sources=(),+ confidence=0.2,+ ),+ mocked_validate=_LOW_VALIDATE,+ ),+ SupportReplyFixture(+ name="diagnostic_its_broken",+ prompt="It's broken.",+ ticket_type="diagnostic",+ expected_outcome="needs_clarification",+ blocker="customer_info",+ needs_diagnostics=True,+ seed_queries=("broken",),+ mocked_draft=MockedDraft(+ reply="Which product surface is broken?",+ citation_sources=(),+ confidence=0.1,+ ),+ mocked_validate=_LOW_VALIDATE,+ ),+ SupportReplyFixture(+ name="account_billing_why_charged",+ prompt="Why was I charged?",+ ticket_type="account_billing",+ expected_outcome="needs_clarification",+ blocker="customer_info",+ seed_queries=("unexpected charge", "invoice"),+ forbidden_claims=("I'll refund", "I'll issue a credit"),+ mocked_draft=MockedDraft(+ reply="Which organization is this for?",+ citation_sources=(),+ confidence=0.2,+ ),+ mocked_validate=_LOW_VALIDATE,+ ),+ SupportReplyFixture(+ name="how_to_holographic_widget",+ prompt=(+ "How do I enable the holographic dashboard widget on app.example.com? I cannot find it in Project settings."+ ),+ ticket_type="how_to",+ expected_outcome="escalate",+ blocker="knowledge",+ seed_queries=("holographic dashboard widget",),+ mocked_draft=MockedDraft(+ reply="I cannot find the holographic dashboard widget in the knowledge base.",+ citation_sources=(),+ confidence=0.0,+ ),+ mocked_validate=MockedValidate(+ grounded=False,+ coverage=0.0,+ confidence=0.0,+ missing=("no documentation for holographic dashboard widget",),+ ),+ ),+ SupportReplyFixture(+ name="diagnostic_retention_contradiction",+ prompt=(+ "Docs say recordings last 30 days but ours vanish after 3 days. Session id "+ "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee on project proj_eval_001."+ ),+ ticket_type="diagnostic",+ expected_outcome="escalate",+ blocker="contradiction",+ needs_diagnostics=True,+ seed_queries=("session recording retention 30 days", "recordings deleted after 3 days"),+ expected_citation_sources=(SOURCE_RECORDING_RETENTION,),+ mocked_draft=MockedDraft(+ reply=(+ "Paid plans retain recordings for 30 days, so a deletion after 3 days is not "+ "the documented policy. This needs engineering. I have the session id you sent."+ ),+ citation_sources=(SOURCE_RECORDING_RETENTION,),+ confidence=0.4,+ excerpts=((SOURCE_RECORDING_RETENTION, "retains session recordings for 30 days"),),+ ),+ mocked_validate=MockedValidate(+ grounded=True,+ coverage=0.5,+ confidence=0.4,+ missing=("why this project deleted at 3 days",),+ ),+ ),+ SupportReplyFixture(+ name="bug_save_button_404",+ prompt=(+ "The Save button on insight abc123 on app.example.com/insights/abc123 returns HTTP "+ "404 since Tuesday. This used to work. Please fix the product."+ ),+ ticket_type="bug",+ expected_outcome="escalate",+ blocker="none",+ seed_queries=("insight save 404",),+ mocked_draft=MockedDraft(+ reply=(+ "This reads as a product defect, not a usage question. Please send the exact "+ "steps, when it started, and a screenshot of the 404. Engineering will take it from there."+ ),+ citation_sources=(),+ confidence=0.8,+ ),+ mocked_validate=MockedValidate(grounded=True, coverage=0.7, confidence=0.7),+ ),+ SupportReplyFixture(+ name="unactionable_thanks",+ prompt="Thanks, you're the best!",+ ticket_type="unactionable",+ expected_outcome="escalate",+ blocker="none",+ seed_queries=(),+ ),+)++FIXTURES_BY_NAME: dict[str, SupportReplyFixture] = {fixture.name: fixture for fixture in FIXTURES}diff --git a/products/conversations/evals/outcomes.py b/products/conversations/evals/outcomes.pynew file mode 100644index 000000000000..bce12a975f13--- /dev/null+++ b/products/conversations/evals/outcomes.py@@ -0,0 +1,22 @@+"""Map a finished pipeline run onto the eval outcome vocabulary."""++from __future__ import annotations++from typing import Any++from products.conversations.evals.constants import (+ CLARIFICATION_TRIAGE_STATUS,+ PIPELINE_RESULT_TO_EVAL_OUTCOME,+ EvalOutcome,+)+++def eval_outcome_from_triage(ai_triage: dict[str, Any] | None) -> EvalOutcome | None:+ """Return the eval outcome for a ticket's `ai_triage`, or None if the run did not finish."""+ triage = ai_triage or {}+ if triage.get("status") == CLARIFICATION_TRIAGE_STATUS:+ return "needs_clarification"+ result = triage.get("result")+ if not isinstance(result, str) or not result:+ return None+ return PIPELINE_RESULT_TO_EVAL_OUTCOME.get(result)diff --git a/products/conversations/evals/report.py b/products/conversations/evals/report.pynew file mode 100644index 000000000000..bfd76948d2f0--- /dev/null+++ b/products/conversations/evals/report.py@@ -0,0 +1,51 @@+"""Plain-text score table for `run_support_reply_eval`."""++from __future__ import annotations++from collections.abc import Sequence+from typing import Any++from posthog.dataclasses import frozen++from products.conversations.evals.fixtures import SupportReplyFixture+from products.posthog_ai.eval_harness.scorers.contract import Score+++@frozen+class EvalRow:+ fixture: SupportReplyFixture+ output: dict[str, Any]+ scores: dict[str, Score]+++def _cell(score: Score | None) -> str:+ if score is None or score.score is None:+ return "-"+ return f"{score.score:.2f}"+++def format_report(rows: Sequence[EvalRow]) -> str:+ header = (+ f"{'fixture':<34} {'expected':<22} {'actual':<22} "+ f"{'outcome':<8} {'cite':<6} {'forbid':<7} {'cost':<6} {'s':>7} {'llm':>4}"+ )+ lines = [header, "-" * len(header)]+ for row in rows:+ fixture, output, scores = row.fixture, row.output, row.scores+ raw_cost = output.get("cost")+ cost = raw_cost if isinstance(raw_cost, dict) else {}+ sandbox = cost.get("sandbox_seconds")+ llm_calls = cost.get("llm_calls")+ sandbox_cell = f"{sandbox:.1f}" if isinstance(sandbox, (int, float)) else "-"+ llm_cell = str(llm_calls) if isinstance(llm_calls, int) else "-"+ error = output.get("error")+ actual = error if error else (output.get("eval_outcome") or "-")+ lines.append(+ f"{fixture.name:<34} {fixture.expected_outcome:<22} {str(actual)[:22]:<22} "+ f"{_cell(scores.get('outcome_match')):<8} "+ f"{_cell(scores.get('citation_precision')):<6} "+ f"{_cell(scores.get('forbidden_claims')):<7} "+ f"{_cell(scores.get('cost')):<6} "+ f"{sandbox_cell:>7} {llm_cell:>4}"+ )+ return "\n".join(lines)diff --git a/products/conversations/evals/runner.py b/products/conversations/evals/runner.pynew file mode 100644index 000000000000..25fa05022b0e--- /dev/null+++ b/products/conversations/evals/runner.py@@ -0,0 +1,298 @@+"""Run one support-reply eval fixture through the real Temporal pipeline.++Mocked mode stubs the LLM/sandbox activities and keeps build_context, retrieve,+persist, and record_triage real. Live mode stubs nothing. Either way the workflow+loop in `pipeline.py` is what runs, so scores track that loop rather than a copy.+"""++from __future__ import annotations++import os+import asyncio+from collections.abc import Callable, Iterator, Sequence+from contextlib import ExitStack, contextmanager+from typing import Any, cast+from uuid import UUID++from unittest.mock import AsyncMock, patch++from temporalio.testing import WorkflowEnvironment+from temporalio.worker import Worker++from posthog.models.comment import Comment++from products.business_knowledge.backend.logic import get_chunks_by_ids, search_knowledge+from products.conversations.backend.models import Ticket+from products.conversations.backend.temporal.ai_reply.constants import MAX_CHUNK_CONTENT_CHARS+from products.conversations.backend.temporal.ai_reply.schemas import (+ ClassifyOutput,+ DraftOutput,+ RefineQueriesOutput,+ ReviewReplyOutput,+ SafetyFilterOutput,+ SupportReplyInput,+ ValidateOutput,+)+from products.conversations.backend.temporal.pipeline import (+ SupportReplyWorkflow,+ support_build_context_activity,+ support_classify_activity,+ support_draft_activity,+ support_persist_knowledge_gap_activity,+ support_persist_reply_activity,+ support_record_triage_activity,+ support_refine_queries_activity,+ support_retrieve_activity,+ support_review_reply_activity,+ support_safety_filter_activity,+ support_validate_activity,+)+from products.conversations.evals.constants import LIVE_EVAL_ENV_VAR+from products.conversations.evals.fixtures import SupportReplyFixture+from products.conversations.evals.outcomes import eval_outcome_from_triage+from products.conversations.evals.seeders import SeededCase++ACTIVITIES = "products.conversations.backend.temporal.ai_reply.activities"+SAFETY_MODULE = f"{ACTIVITIES}.safety_filter"+CLASSIFY_MODULE = f"{ACTIVITIES}.classify"+REFINE_MODULE = f"{ACTIVITIES}.refine_queries"+RETRIEVE_MODULE = f"{ACTIVITIES}.retrieve"+DRAFT_MODULE = f"{ACTIVITIES}.draft"+VALIDATE_MODULE = f"{ACTIVITIES}.validate"+REVIEW_MODULE = f"{ACTIVITIES}.review_reply"++WORKFLOW_ACTIVITIES: Sequence[Callable[..., Any]] = cast(+ Sequence[Callable[..., Any]],+ [+ support_build_context_activity,+ support_safety_filter_activity,+ support_classify_activity,+ support_refine_queries_activity,+ support_retrieve_activity,+ support_draft_activity,+ support_validate_activity,+ support_review_reply_activity,+ support_persist_reply_activity,+ support_persist_knowledge_gap_activity,+ support_record_triage_activity,+ ],+)++_MOCKED_WORKFLOW_LOCK = asyncio.Lock()+++def live_eval_enabled() -> bool:+ return os.environ.get(LIVE_EVAL_ENV_VAR, "") == "1"+++def _chunk_ids_for(source_names: tuple[str, ...], seed: SeededCase) -> list[str]:+ ids: list[str] = []+ for name in source_names:+ ids.extend(seed.chunks_by_source.get(name, ()))+ return ids+++def _mocked_draft(fixture: SupportReplyFixture, seed: SeededCase) -> DraftOutput:+ draft = fixture.mocked_draft+ if draft is None:+ return DraftOutput(reply="", citations=[], confidence=0.0)+ citations = _chunk_ids_for(draft.citation_sources, seed)+ sources = [+ {"ref": (_chunk_ids_for((source_name,), seed) or [source_name])[0], "excerpt": excerpt}+ for source_name, excerpt in draft.excerpts+ ]+ return DraftOutput(+ reply=draft.reply,+ citations=citations,+ confidence=draft.confidence,+ sources=sources,+ sandbox_seconds=0.0,+ )+++def _mocked_validate(fixture: SupportReplyFixture) -> ValidateOutput:+ validate = fixture.mocked_validate+ if validate is None:+ return ValidateOutput(grounded=False, coverage=0.0, confidence=0.0, missing=[])+ return ValidateOutput(+ grounded=validate.grounded,+ coverage=validate.coverage,+ confidence=validate.confidence,+ missing=list(validate.missing),+ )+++def _fts_search(team: Any, query: str, limit: int = 10, **kwargs: Any) -> Any:+ return search_knowledge(team.id, query, limit=limit)+++def _identity_rerank(team: Any, query: str, results: Any, *, top_k: int) -> Any:+ return results[:top_k]+++@contextmanager+def _mocked_llm_activities(fixture: SupportReplyFixture, seed: SeededCase) -> Iterator[None]:+ with ExitStack() as stack:+ stack.enter_context(+ patch(f"{SAFETY_MODULE}._safety_filter", new_callable=AsyncMock, return_value=SafetyFilterOutput(safe=True))+ )+ stack.enter_context(+ patch(+ f"{CLASSIFY_MODULE}._classify",+ new_callable=AsyncMock,+ return_value=ClassifyOutput(+ ticket_type=fixture.ticket_type,+ needs_diagnostics=fixture.needs_diagnostics,+ seed_queries=list(fixture.seed_queries),+ ),+ )+ )+ stack.enter_context(+ patch(+ f"{REFINE_MODULE}._refine_queries",+ new_callable=AsyncMock,+ return_value=RefineQueriesOutput(queries=list(fixture.seed_queries) or ["support"]),+ )+ )+ stack.enter_context(patch(f"{RETRIEVE_MODULE}.search_knowledge_for_team", side_effect=_fts_search))+ stack.enter_context(patch(f"{RETRIEVE_MODULE}.rerank_chunks", side_effect=_identity_rerank))+ stack.enter_context(+ patch(f"{DRAFT_MODULE}._draft_async", new_callable=AsyncMock, return_value=_mocked_draft(fixture, seed))+ )+ stack.enter_context(+ patch(f"{VALIDATE_MODULE}._validate", new_callable=AsyncMock, return_value=_mocked_validate(fixture))+ )+ stack.enter_context(+ patch(+ f"{REVIEW_MODULE}._review_reply",+ new_callable=AsyncMock,+ return_value=ReviewReplyOutput(safe=True),+ )+ )+ yield+++async def _execute_workflow(team_id: int, ticket_id: str) -> str:+ task_queue = f"support-reply-eval-{ticket_id}"+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[SupportReplyWorkflow],+ activities=WORKFLOW_ACTIVITIES,+ ):+ return await env.client.execute_workflow(+ SupportReplyWorkflow.run,+ SupportReplyInput(team_id=team_id, ticket_id=ticket_id),+ id=f"support-reply-eval-{ticket_id}",+ task_queue=task_queue,+ )+++def _ai_comment(team_id: int, ticket_id: str) -> Comment | None:+ return (+ Comment.objects.filter(+ team_id=team_id,+ scope="conversations_ticket",+ item_id=ticket_id,+ item_context__author_type="AI",+ )+ .order_by("-created_at")+ .first()+ )+++def _source_excerpts(*, team_id: int, citation_ids: list[str]) -> list[dict[str, str]]:+ # Persist stores chunk ids only so Temporal history does not carry the text.+ # The grounding judge needs the excerpts, so rehydrate them the same way validate does.+ uuids: list[UUID] = []+ leftover: list[str] = []+ for ref in citation_ids:+ try:+ uuids.append(UUID(str(ref)))+ except ValueError:+ leftover.append(str(ref))+ excerpts: list[dict[str, str]] = []+ if uuids:+ for result in get_chunks_by_ids(team_id, uuids):+ excerpts.append(+ {+ "ref": str(result.chunk_id),+ "excerpt": result.content[:MAX_CHUNK_CONTENT_CHARS],+ "source_name": result.source_name,+ }+ )+ excerpts.extend({"ref": ref, "excerpt": ""} for ref in leftover)+ return excerpts+++def collect_output(+ *,+ fixture: SupportReplyFixture,+ seed: SeededCase,+ workflow_result: str,+ live: bool,+) -> dict[str, Any]:+ ticket = Ticket.objects.filter(id=seed.ticket_id, team_id=seed.team_id).first()+ triage = dict(ticket.ai_triage) if ticket and isinstance(ticket.ai_triage, dict) else {}+ comment = _ai_comment(seed.team_id, seed.ticket_id)+ reply = (comment.content or "") if comment is not None else ""+ raw_citations = []+ if comment is not None and isinstance(comment.item_context, dict):+ raw_citations = [str(c) for c in (comment.item_context.get("citations") or [])]+ citation_source_names = [seed.source_by_chunk[c] for c in raw_citations if c in seed.source_by_chunk]+ clarifying_questions = [q for q in (triage.get("clarifying_questions") or []) if isinstance(q, str)]+ if not clarifying_questions and "?" in reply:+ clarifying_questions = [reply]+ raw_cost = triage.get("cost")+ cost = raw_cost if isinstance(raw_cost, dict) else {}+ eval_outcome = eval_outcome_from_triage(triage)+ return {+ "exit_code": 0,+ "prompt": fixture.prompt,+ "last_message": reply,+ "reply": reply,+ "citations": raw_citations,+ "citation_source_names": citation_source_names,+ "source_excerpts": _source_excerpts(team_id=seed.team_id, citation_ids=raw_citations),+ "clarifying_questions": clarifying_questions,+ "pipeline_result": triage.get("result") or workflow_result,+ "eval_outcome": eval_outcome,+ "ticket_type": triage.get("ticket_type") or fixture.ticket_type,+ "cost": cost,+ "ai_triage": triage,+ "mode": "live" if live else "mocked",+ "seed": {"team_id": seed.team_id, "ticket_id": seed.ticket_id},+ }+++async def run_fixture(fixture: SupportReplyFixture, seed: SeededCase, *, live: bool) -> dict[str, Any]:+ """Execute the pipeline for one seeded fixture and return the scorer output dict."""+ try:+ if live:+ workflow_result = await _execute_workflow(seed.team_id, seed.ticket_id)+ else:+ async with _MOCKED_WORKFLOW_LOCK:+ with _mocked_llm_activities(fixture, seed):+ workflow_result = await _execute_workflow(seed.team_id, seed.ticket_id)+ return await asyncio.to_thread(+ lambda: collect_output(fixture=fixture, seed=seed, workflow_result=workflow_result, live=live)+ )+ except Exception as error:+ return {+ "exit_code": 1,+ "prompt": fixture.prompt,+ "last_message": "",+ "reply": "",+ "citations": [],+ "citation_source_names": [],+ "source_excerpts": [],+ "clarifying_questions": [],+ "pipeline_result": None,+ "eval_outcome": None,+ "ticket_type": fixture.ticket_type,+ "cost": {},+ "error": f"{type(error).__name__}: {error}",+ "mode": "live" if live else "mocked",+ "seed": {"team_id": seed.team_id, "ticket_id": seed.ticket_id},+ }diff --git a/products/conversations/evals/scorers.py b/products/conversations/evals/scorers.pynew file mode 100644index 000000000000..c21d91fc90ee--- /dev/null+++ b/products/conversations/evals/scorers.py@@ -0,0 +1,259 @@+"""Scorers for the support-reply eval suite.++Deterministic scorers grade outcome, citations, forbidden claims, and cost from the+runner's output dict. LLM judges grade grounding and clarifying-question quality and+self-skip when their `expected` key is absent.+"""++from __future__ import annotations++from typing import Any++from products.posthog_ai.eval_harness.scorers import BINARY_CHOICE_SCORES, JUDGE_MODEL, JudgedScorer+from products.posthog_ai.eval_harness.scorers.contract import Score, Scorer++OUTCOME_KEY = "outcome_match"+CITATION_KEY = "citation_precision"+FORBIDDEN_KEY = "forbidden_claims"+COST_KEY = "cost"+GROUNDING_KEY = "grounding"+CLARIFY_KEY = "clarifying_question"+++def _spec(expected: dict | None, name: str) -> dict | None:+ if not isinstance(expected, dict):+ return None+ spec = expected.get(name)+ return spec if isinstance(spec, dict) else None+++def _reply_text(output: dict | None) -> str:+ if not output:+ return ""+ reply = output.get("reply")+ return reply.strip() if isinstance(reply, str) else ""+++class OutcomeMatch(Scorer):+ """Did the pipeline land on the fixture's expected eval outcome?"""++ def _name(self) -> str:+ return OUTCOME_KEY++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs: Any) -> Score:+ spec = _spec(expected, self._name())+ if spec is None or "outcome" not in spec:+ return Score(name=self._name(), score=None, metadata={"reason": "No outcome expectation"})+ if not output or output.get("error"):+ return Score(name=self._name(), score=0.0, metadata={"reason": (output or {}).get("error", "No output")})+ actual = output.get("eval_outcome")+ want = spec["outcome"]+ return Score(+ name=self._name(),+ score=1.0 if actual == want else 0.0,+ metadata={"expected": want, "actual": actual, "pipeline_result": output.get("pipeline_result")},+ )+++class CitationPrecision(Scorer):+ """Of the sources the reply cited, what fraction were in the expected set?++ Skips when the fixture lists no expected sources, so escalate/clarify cases+ that cite nothing (or cite extra) do not drag the precision average.+ """++ def _name(self) -> str:+ return CITATION_KEY++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs: Any) -> Score:+ spec = _spec(expected, self._name())+ if spec is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No citation expectation"})+ want = [name for name in spec.get("source_names") or [] if isinstance(name, str)]+ if not want:+ return Score(name=self._name(), score=None, metadata={"reason": "No expected sources"})+ if not output or output.get("error"):+ return Score(name=self._name(), score=0.0, metadata={"reason": (output or {}).get("error", "No output")})+ cited = [name for name in (output.get("citation_source_names") or []) if isinstance(name, str)]+ if not cited:+ return Score(name=self._name(), score=0.0, metadata={"expected": want, "cited": cited})+ hits = sum(1 for name in cited if name in want)+ return Score(+ name=self._name(),+ score=hits / len(cited),+ metadata={"expected": want, "cited": cited, "hits": hits},+ )+++class ForbiddenClaims(Scorer):+ """Fail if the reply contains a phrase the fixture forbids (case-insensitive)."""++ def _name(self) -> str:+ return FORBIDDEN_KEY++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs: Any) -> Score:+ spec = _spec(expected, self._name())+ if spec is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No forbidden-claim expectation"})+ phrases = [p for p in spec.get("phrases") or [] if isinstance(p, str) and p]+ if not phrases:+ return Score(name=self._name(), score=None, metadata={"reason": "No forbidden phrases"})+ if not output or output.get("error"):+ return Score(name=self._name(), score=0.0, metadata={"reason": (output or {}).get("error", "No output")})+ reply_lower = _reply_text(output).lower()+ hits = [phrase for phrase in phrases if phrase.lower() in reply_lower]+ return Score(+ name=self._name(),+ score=0.0 if hits else 1.0,+ metadata={"hits": hits},+ )+++class CostScorer(Scorer):+ """Require the runner to report sandbox seconds and utility LLM calls."""++ def _name(self) -> str:+ return COST_KEY++ def _run_eval_sync(self, output: dict | None, expected: dict | None = None, **kwargs: Any) -> Score:+ if _spec(expected, self._name()) is None:+ return Score(name=self._name(), score=None, metadata={"reason": "No cost expectation"})+ if not output or output.get("error"):+ return Score(name=self._name(), score=0.0, metadata={"reason": (output or {}).get("error", "No output")})+ raw_cost = output.get("cost")+ cost = raw_cost if isinstance(raw_cost, dict) else {}+ sandbox_seconds = cost.get("sandbox_seconds")+ llm_calls = cost.get("llm_calls")+ present = isinstance(sandbox_seconds, (int, float)) and isinstance(llm_calls, int)+ return Score(+ name=self._name(),+ score=1.0 if present else 0.0,+ metadata={"sandbox_seconds": sandbox_seconds, "llm_calls": llm_calls},+ )+++class Grounding(JudgedScorer):+ """Is every factual claim in the reply supported by the provided sources?"""++ def _name(self) -> str:+ return GROUNDING_KEY++ def __init__(self, **kwargs: Any) -> None:+ super().__init__(+ name=GROUNDING_KEY,+ prompt_template="""+You are checking whether a support reply is grounded in the sources it was given.++Customer ticket:+<ticket>+{{output.prompt}}+</ticket>++Reply:+<reply>+{{output.reply}}+</reply>++Sources:+<sources>+{{output.sources}}+</sources>++Is every factual claim in the reply supported by those sources? Hedging, questions, and+acknowledgements do not need a source. Invented product behavior, settings, or limits that+the sources do not state is a failure. Answer `yes` or `no`.+""".strip(),+ choice_scores=BINARY_CHOICE_SCORES,+ model=JUDGE_MODEL,+ max_completion_tokens=256,+ **kwargs,+ )++ def _prepare(self, output: Any, expected: Any) -> dict[str, Any] | Score:+ spec = _spec(expected, self._name())+ if not spec or not spec.get("required"):+ return Score(name=self._name(), score=None, metadata={"reason": "Grounding not required"})+ if not output or output.get("error"):+ return Score(name=self._name(), score=0.0, metadata={"reason": (output or {}).get("error", "No output")})+ reply = _reply_text(output)+ if not reply:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No reply to ground"})+ sources = output.get("source_excerpts") or output.get("sources") or []+ return {+ "output": {+ "prompt": output.get("prompt", ""),+ "reply": reply,+ "sources": sources if isinstance(sources, str) else str(sources),+ }+ }+++class ClarifyingQuestion(JudgedScorer):+ """Does the agent ask one question that unblocks the answer and is not already in the thread?"""++ def _name(self) -> str:+ return CLARIFY_KEY++ def __init__(self, **kwargs: Any) -> None:+ super().__init__(+ name=CLARIFY_KEY,+ prompt_template="""+You are checking a support agent's clarifying question.++Customer ticket (already in the thread):+<ticket>+{{output.prompt}}+</ticket>++Questions the agent asked:+<questions>+{{output.questions}}+</questions>++Does the agent ask exactly one thing the customer has not already answered, and would+answering it let a later turn reply from the knowledge base? Multiple unrelated asks,+questions already answered in the ticket, or a guess instead of a question are failures.+Answer `yes` or `no`.+""".strip(),+ choice_scores=BINARY_CHOICE_SCORES,+ model=JUDGE_MODEL,+ max_completion_tokens=256,+ **kwargs,+ )++ def _prepare(self, output: Any, expected: Any) -> dict[str, Any] | Score:+ spec = _spec(expected, self._name())+ if not spec or not spec.get("required"):+ return Score(name=self._name(), score=None, metadata={"reason": "Clarifying question not required"})+ if not output or output.get("error"):+ return Score(name=self._name(), score=0.0, metadata={"reason": (output or {}).get("error", "No output")})+ questions = output.get("clarifying_questions")+ if not isinstance(questions, list):+ questions = []+ cleaned = [q for q in questions if isinstance(q, str) and q.strip()]+ if not cleaned:+ reply = _reply_text(output)+ if "?" in reply:+ cleaned = [reply]+ if not cleaned:+ return Score(name=self._name(), score=0.0, metadata={"reason": "No clarifying question"})+ return {+ "output": {+ "prompt": output.get("prompt", ""),+ "questions": "\n".join(cleaned),+ }+ }+++DETERMINISTIC_SCORERS: tuple[Scorer, ...] = (+ OutcomeMatch(),+ CitationPrecision(),+ ForbiddenClaims(),+ CostScorer(),+)++ALL_SCORERS: tuple[Scorer | JudgedScorer, ...] = (+ *DETERMINISTIC_SCORERS,+ Grounding(),+ ClarifyingQuestion(),+)diff --git a/products/conversations/evals/seeders.py b/products/conversations/evals/seeders.pynew file mode 100644index 000000000000..fd654c3c8f93--- /dev/null+++ b/products/conversations/evals/seeders.py@@ -0,0 +1,105 @@+"""Install the invented BK corpus and one ticket into a team."""++from __future__ import annotations++from uuid import NAMESPACE_URL, uuid4, uuid5++from posthog.dataclasses import frozen+from posthog.models import Organization, OrganizationMembership, Team, User+from posthog.models.comment import Comment+from posthog.models.scoping import team_scope++from products.business_knowledge.backend.logic import create_text_source+from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, SafetyVerdict+from products.conversations.backend.models import Ticket+from products.conversations.evals.corpus import CORPUS+from products.conversations.evals.fixtures import SupportReplyFixture+++@frozen+class SeededCase:+ team_id: int+ user_id: int+ ticket_id: str+ chunks_by_source: dict[str, tuple[str, ...]]+ source_by_chunk: dict[str, str]+++@frozen+class EvalTeam:+ organization: Organization+ team: Team+ user: User+++def provision_eval_team(*, label: str) -> EvalTeam:+ suffix = f"{label}-{uuid4().hex[:8]}"+ organization = Organization.objects.create(name=f"Acme Capture eval {suffix}")+ user = User.objects.create_and_join(+ organization=organization,+ email=f"eval-{suffix}@example.com",+ password=None,+ first_name="Eval",+ level=OrganizationMembership.Level.OWNER,+ )+ team = Team.objects.create(organization=organization, name=f"Acme Capture {suffix}")+ return EvalTeam(organization=organization, team=team, user=user)+++def seed_corpus(*, team_id: int, created_by_id: int) -> dict[str, tuple[str, ...]]:+ """Write every corpus document and mark them SAFE so search can see them."""+ chunks_by_source: dict[str, tuple[str, ...]] = {}+ for document in CORPUS:+ create_text_source(+ team_id=team_id,+ created_by_id=created_by_id,+ name=document.name,+ text=document.text,+ always_include=document.always_include,+ )+ with team_scope(team_id, canonical=True):+ KnowledgeDocument.objects.filter(team_id=team_id).update(safety_verdict=SafetyVerdict.SAFE)+ for chunk in KnowledgeChunk.objects.filter(team_id=team_id).select_related("source"):+ chunks_by_source.setdefault(chunk.source.name, ())+ chunks_by_source[chunk.source.name] = (*chunks_by_source[chunk.source.name], str(chunk.id))+ return chunks_by_source+++def seed_ticket(*, team: Team, fixture: SupportReplyFixture) -> Ticket:+ session_id = str(uuid5(NAMESPACE_URL, f"support-reply-eval:{fixture.name}"))+ ticket = Ticket.objects.create_with_number(+ team=team,+ widget_session_id=session_id,+ distinct_id=f"eval-person-{fixture.name}",+ channel_source="widget",+ session_context={"current_url": "https://app.example.com/support"},+ )+ Comment.objects.create(+ team=team,+ scope="conversations_ticket",+ item_id=str(ticket.id),+ content=fixture.prompt,+ item_context={"author_type": "customer", "is_private": False},+ )+ return ticket+++def seed_case(*, eval_team: EvalTeam, fixture: SupportReplyFixture) -> SeededCase:+ chunks_by_source = seed_corpus(team_id=eval_team.team.id, created_by_id=eval_team.user.id)+ ticket = seed_ticket(team=eval_team.team, fixture=fixture)+ source_by_chunk = {+ chunk_id: source_name for source_name, chunk_ids in chunks_by_source.items() for chunk_id in chunk_ids+ }+ return SeededCase(+ team_id=eval_team.team.id,+ user_id=eval_team.user.id,+ ticket_id=str(ticket.id),+ chunks_by_source=chunks_by_source,+ source_by_chunk=source_by_chunk,+ )+++def teardown_eval_team(*, eval_team: EvalTeam) -> None:+ user_id = eval_team.user.id+ eval_team.organization.delete()+ User.objects.filter(id=user_id).delete()diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex 8f83f0438364..c1c7ebcfe8a1 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -64,7 +64,7 @@ export interface AITriage {schema_version?: numberstatus?: AITriageStatusresult?: AITriageResult- ticket_type?: 'how_to' | 'diagnostic' | 'account_billing' | 'unactionable'+ ticket_type?: 'how_to' | 'diagnostic' | 'account_billing' | 'bug' | 'unactionable'needs_diagnostics?: booleandiagnostics_allowed?: booleanconfidence?: number@@ -75,6 +75,11 @@ export interface AITriage {run_id?: stringai_trace_id?: stringmissing?: string[]+ cost?: {+ sandbox_seconds?: number+ llm_calls?: number+ }+ human_outcome?: 'used' | 'edited' | 'ignored'}export type AiReplyFeedbackRating = 'good' | 'bad'