Skip to content

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

feat(replay-vision): color verdicts and scores by the prompt's valence (#112900)

Tue Haulundd46486a94405
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index e8008ba3cdfe..7f07b03e5637 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -525,6 +525,7 @@ replay_scanner_machine_fields = [
"search_last_viewed_at",
"prompt_question",
"prompt_question_source",
+ "prompt_valence",
"limit_notified_period_start",
"admission_budget_used",
"admission_budget_refreshed_at",
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 2888e80d2f31..49c1f339bfa2 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -63,9 +63,14 @@ from products.replay_vision.backend.models.replay_observation import (
from products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabel
from products.replay_vision.backend.models.replay_observation_media import ReplayObservationMedia
from products.replay_vision.backend.models.replay_observation_view import ReplayObservationView
-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerOrigin, ScannerType
+from products.replay_vision.backend.models.replay_scanner import (
+ PromptValence,
+ ReplayScanner,
+ ScannerOrigin,
+ ScannerType,
+)
from products.replay_vision.backend.observation_formatting import summarize_observation
-from products.replay_vision.backend.prompt_questions import question_for_snapshot
+from products.replay_vision.backend.prompt_questions import question_for_snapshot, valence_for_snapshot
from products.replay_vision.backend.scanner_access import (
accessible_observations,
can_read_targeted_experiment,
@@ -390,6 +395,24 @@ class ReplayObservationSerializer(serializers.ModelSerializer):
source=getattr(obj, "scanner_prompt_question_source", "") or "",
)
+ prompt_valence = serializers.SerializerMethodField(
+ help_text=(
+ "For a monitor or scorer: `good` when a yes or a high score is good news for the team, `bad` when it "
+ "is a problem, `neutral` when neither. Judged by AI from the prompt. Null for other scanner types, "
+ "when not judged, or when the prompt has changed since this observation was scanned."
+ ),
+ )
+
+ @extend_schema_field(serializers.ChoiceField(choices=PromptValence.choices, allow_null=True))
+ def get_prompt_valence(self, obj: ReplayObservation) -> PromptValence | None:
+ snapshot = obj.scanner_snapshot or {}
+ return valence_for_snapshot(
+ snapshot_config=snapshot.get("scanner_config"),
+ scanner_type=snapshot.get("scanner_type"),
+ valence=getattr(obj, "scanner_prompt_valence", "") or "",
+ source=getattr(obj, "scanner_prompt_question_source", "") or "",
+ )
+
summary_line = serializers.SerializerMethodField(
help_text=(
"One line of plain text saying what the scanner found: its verdict, score, tags or title, then its "
@@ -416,6 +439,7 @@ class ReplayObservationSerializer(serializers.ModelSerializer):
"scanner_snapshot",
"scanner_result",
"prompt_question",
+ "prompt_valence",
"triggered_by",
"triggered_by_user",
"backfill_id",
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index cb6f1fc03eaf..c728b6633c71 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -2323,6 +2323,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
# Same prompt, so the source's question still describes it.
prompt_question=source.prompt_question,
prompt_question_source=source.prompt_question_source,
+ prompt_valence=source.prompt_valence,
query=source.query,
sampling_rate=source.sampling_rate,
sampling_mode=source.sampling_mode,
diff --git a/products/replay_vision/backend/migrations/0110_replayscanner_prompt_valence.py b/products/replay_vision/backend/migrations/0110_replayscanner_prompt_valence.py
new file mode 100644
index 000000000000..d7a4bdccaf50
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0110_replayscanner_prompt_valence.py
@@ -0,0 +1,24 @@
+# Generated by Django 5.2.18 on 2026-10-06 20:27
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("replay_vision", "0109_alter_replayobservation_error_reason"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="replayscanner",
+ name="prompt_valence",
+ field=models.CharField(
+ blank=True,
+ choices=[("good", "Good"), ("bad", "Bad"), ("neutral", "Neutral")],
+ db_default="",
+ default="",
+ help_text="Whether a yes or a high score is good or bad news, judged by AI from the prompt. Empty when not judged: the scanner type has no direction, or the model was unavailable.",
+ max_length=16,
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 6240efa167d1..f8f31b70b9ba 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0109_alter_replayobservation_error_reason
+0110_replayscanner_prompt_valence
diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.py
index 8ed410daf431..2d09138db866 100644
--- a/products/replay_vision/backend/models/replay_observation.py
+++ b/products/replay_vision/backend/models/replay_observation.py
@@ -224,6 +224,7 @@ def hydrate_for_serialization(
scanner_origin=F("scanner__origin"),
scanner_prompt_question=F("scanner__prompt_question"),
scanner_prompt_question_source=F("scanner__prompt_question_source"),
+ scanner_prompt_valence=F("scanner__prompt_valence"),
viewed=viewed,
)
)
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index 0f39d3aec619..fc81923e75a1 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -98,6 +98,14 @@ class ScannerOrigin(models.TextChoices):
INLINE = "inline", "Inline"
+class PromptValence(models.TextChoices):
+ """Whether the answer a monitor or scorer looks for is good or bad news for the team."""
+
+ GOOD = "good", "Good"
+ BAD = "bad", "Bad"
+ NEUTRAL = "neutral", "Neutral"
+
+
def prompt_fingerprint(prompt: str) -> str:
"""Identifies a prompt's text, so a condensed question can be matched to the prompt it came from."""
return hashlib.sha256(prompt.encode()).hexdigest()
@@ -307,6 +315,16 @@ class ReplayScanner(Taggable, ModelActivityMixin, UUIDModel):
db_default="",
help_text="`prompt_fingerprint` of the prompt `prompt_question` was condensed from. A mismatch means it is stale.",
)
+ # Condensed in the same model call as `prompt_question`, so `prompt_question_source` dates it too.
+ prompt_valence = models.CharField(
+ max_length=16,
+ blank=True,
+ default="",
+ db_default="",
+ choices=PromptValence.choices,
+ help_text="Whether a yes or a high score is good or bad news, judged by AI from the prompt. Empty when "
+ "not judged: the scanner type has no direction, or the model was unavailable.",
+ )
# Not "monthly": this resets with the org's billing period, which is only a calendar month
# until billing syncs a real one. See quota.current_period_bounds.
diff --git a/products/replay_vision/backend/prompt_questions.py b/products/replay_vision/backend/prompt_questions.py
index 6a36d7ae167d..4b42168c4274 100644
--- a/products/replay_vision/backend/prompt_questions.py
+++ b/products/replay_vision/backend/prompt_questions.py
@@ -2,8 +2,8 @@
The observation page shows this question above the answer, with the full prompt one click away. It is
written in the same save as the prompt it came from, so a scanner never carries a question for a different
-prompt. `prompt_question_source` records which prompt that was, so an observation scanned with an older
-prompt can tell the question no longer describes it.
+prompt. `prompt_question_source` records which prompt and scale that was, so an observation scanned with an older
+prompt or scale can tell the question no longer describes it.
"""
import uuid
@@ -22,7 +22,13 @@ from posthog.dataclasses import frozen
from products.replay_vision.backend.consent import is_ai_data_processing_approved
from products.replay_vision.backend.distinct_ids import replay_vision_distinct_id
-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerOrigin, prompt_fingerprint
+from products.replay_vision.backend.models.replay_scanner import (
+ PromptValence,
+ ReplayScanner,
+ ScannerOrigin,
+ ScannerType,
+ prompt_fingerprint,
+)
logger = structlog.get_logger(__name__)
@@ -48,35 +54,65 @@ How to phrase it for each scanner type:
- scorer: what is being measured, for example "How strong is the buying intent in this session?"
- summarizer: what the summary covers, for example "What happened in this session around checkout drop-off?"
+For a monitor or a scorer, also judge the valence: is a "yes", or a high score, good or bad news for the team
+that wrote the instructions?
+- good: it is what they hope to see, for example "Did the user complete checkout?" or "How strong is the buying intent?"
+- bad: it is a problem, for example "Did the user hit an error?" or "How frustrated did the user appear?"
+- neutral: neither, for example "Did the user use the dark theme?"
+For a classifier or a summarizer, answer neutral.
+
Respond with JSON matching the schema.
"""
-# Questions for the scanner templates the app offers, keyed by the template's exact prompt, so a scanner
-# made from one needs no model call. Most scanners are unedited copies of a template. Keep the prompts in
+# Questions and valences for the scanner templates the app offers, keyed by the template's exact prompt, so a
+# scanner made from one needs no model call. Most scanners are unedited copies of a template. Keep the prompts in
# step with `frontend/replay_scanners/scannerTemplates.ts`: a prompt that no longer matches falls back to
# the model.
-TEMPLATE_QUESTIONS: dict[str, str] = {
- "Answer yes if the user appears stuck on a page: scrolling without engaging, hovering over elements with no clear CTA, or abandoning the session shortly after arriving. Otherwise answer no.": "Did the user get stuck on a page?",
- "Summarize what the user did in this session: which pages they visited, what they tried to accomplish, and any notable moments like errors, confusion, or successful completions. Be concrete and don't speculate.": "What did the user do in this session?",
- "Classify what the user appeared to be trying to accomplish in this session, based on their primary actions. Pick from the configured categories.": "What was the user trying to accomplish in this session?",
- "Score how frustrated the user appeared during this session. 0 means a smooth session with no visible friction. 10 means clear, sustained frustration: rage clicks, repeated failures, abandonment. Use the full range; most sessions land somewhere in the middle.": "How frustrated did the user appear during this session?",
- "Classify what happened in this session. Did the user complete what they were trying to do, abandon partway through, hit an error that blocked them, or just browse without a clear task? Pick from the configured categories.": "How did this session end for the user?",
+TEMPLATE_QUESTIONS: dict[str, tuple[str, PromptValence]] = {
+ "Answer yes if the user appears stuck on a page: scrolling without engaging, hovering over elements with no clear CTA, or abandoning the session shortly after arriving. Otherwise answer no.": (
+ "Did the user get stuck on a page?",
+ PromptValence.BAD,
+ ),
+ "Summarize what the user did in this session: which pages they visited, what they tried to accomplish, and any notable moments like errors, confusion, or successful completions. Be concrete and don't speculate.": (
+ "What did the user do in this session?",
+ PromptValence.NEUTRAL,
+ ),
+ "Classify what the user appeared to be trying to accomplish in this session, based on their primary actions. Pick from the configured categories.": (
+ "What was the user trying to accomplish in this session?",
+ PromptValence.NEUTRAL,
+ ),
+ "Score how frustrated the user appeared during this session. 0 means a smooth session with no visible friction. 10 means clear, sustained frustration: rage clicks, repeated failures, abandonment. Use the full range; most sessions land somewhere in the middle.": (
+ "How frustrated did the user appear during this session?",
+ PromptValence.BAD,
+ ),
+ "Classify what happened in this session. Did the user complete what they were trying to do, abandon partway through, hit an error that blocked them, or just browse without a clear task? Pick from the configured categories.": (
+ "How did this session end for the user?",
+ PromptValence.NEUTRAL,
+ ),
}
+_DIRECTIONAL_TYPES = frozenset({ScannerType.MONITOR, ScannerType.SCORER})
+
class _LlmQuestion(BaseModel):
question: str = Field(description="The single question the scanner answers about each session.")
+ valence: PromptValence = Field(description="Whether a yes, or a high score, is good or bad news for the team.")
@frozen
class PromptQuestion:
question: str
source: str
+ valence: PromptValence | None = None
def as_fields(self) -> dict[str, str]:
"""The scanner columns this question fills, for a create or update call."""
- return {"prompt_question": self.question, "prompt_question_source": self.source}
+ return {
+ "prompt_question": self.question,
+ "prompt_question_source": self.source,
+ "prompt_valence": self.valence or "",
+ }
def _prompt_of(scanner_config: object) -> str:
@@ -99,7 +135,21 @@ def _clean(question: str) -> str | None:
return question
-def _generate(*, prompt: str, scanner_type: str, team_id: int) -> str | None:
+def _scale_line(scanner_config: object) -> str:
+ """A scorer's scale often says which end is good ("frustration" or "satisfaction"), so the model sees it too."""
+ scale = scanner_config.get("scale") if isinstance(scanner_config, dict) else None
+ if not isinstance(scale, dict):
+ return ""
+ label = scale.get("label")
+ return f"\n\nScale: {scale.get('min')} to {scale.get('max')}" + (f", measuring {label}" if label else "")
+
+
+def _source_of(scanner_config: object) -> str:
+ """Fingerprints every model input from the config, so a scale edit dates the question and valence like a prompt edit."""
+ return prompt_fingerprint(_prompt_of(scanner_config) + _scale_line(scanner_config))
+
+
+def _generate(*, prompt: str, scale_line: str, scanner_type: str, team_id: int) -> _LlmQuestion | None:
config = GenerateContentConfig(
system_instruction=_SYSTEM_PROMPT,
response_mime_type="application/json",
@@ -117,14 +167,14 @@ def _generate(*, prompt: str, scanner_type: str, team_id: int) -> str | None:
)
response = client.models.generate_content(
model=_QUESTION_MODEL,
- contents=f"Scanner type: {scanner_type}\n\nInstructions:\n{prompt}",
+ contents=f"Scanner type: {scanner_type}{scale_line}\n\nInstructions:\n{prompt}",
config=config,
posthog_distinct_id=replay_vision_distinct_id(team_id),
posthog_trace_id=str(uuid.uuid4()),
posthog_properties={"ai_product": "replay_vision", "feature": "prompt_question", "team_id": team_id},
posthog_groups={"project": str(team_id)},
)
- return _clean(_LlmQuestion.model_validate_json(response.text or "").question)
+ return _LlmQuestion.model_validate_json(response.text or "")
except Exception:
logger.exception("replay_vision.prompt_question.generate_failed", team_id=team_id)
return None
@@ -151,7 +201,8 @@ def template_question(scanner_config: object) -> PromptQuestion | None:
prompt = _prompt_of(scanner_config)
if prompt not in TEMPLATE_QUESTIONS:
return None
- return PromptQuestion(question=TEMPLATE_QUESTIONS[prompt], source=prompt_fingerprint(prompt))
+ question, valence = TEMPLATE_QUESTIONS[prompt]
+ return PromptQuestion(question=question, source=_source_of(scanner_config), valence=valence)
def condense_prompt(*, team_id: int, scanner_type: str, scanner_config: object, metered: bool = True) -> PromptQuestion:
@@ -159,19 +210,22 @@ def condense_prompt(*, team_id: int, scanner_type: str, scanner_config: object,
first line, so every scanner carries a question to show. `metered` counts the call against the team's
hourly budget; the backfill, run by an operator, skips it."""
prompt = _prompt_of(scanner_config)
- source = prompt_fingerprint(prompt)
+ source = _source_of(scanner_config)
if not prompt.strip():
return PromptQuestion(question="", source=source)
if (template := template_question(scanner_config)) is not None:
return template
- question = None
+ answer = None
# The prompt is the team's own text, but it still only goes to the model under the org's AI consent.
if is_ai_data_processing_approved(team_id) and (not metered or _take_model_call(team_id)):
- question = _generate(prompt=prompt, scanner_type=scanner_type, team_id=team_id)
+ answer = _generate(
+ prompt=prompt, scale_line=_scale_line(scanner_config), scanner_type=scanner_type, team_id=team_id
+ )
+ question = _clean(answer.question) if answer else None
if question is None:
logger.warning("replay_vision.prompt_question.fell_back", team_id=team_id)
question = fallback_question(prompt)
- return PromptQuestion(question=question, source=source)
+ return PromptQuestion(question=question, source=source, valence=answer.valence if answer else None)
def question_fields_for_save(
@@ -182,8 +236,8 @@ def question_fields_for_save(
current_source: str = "",
) -> dict[str, str]:
"""The question columns to write with a save that sets `scanner_config`, or nothing when the prompt is the
- one the current question already came from. Call it before the save's transaction opens."""
- if prompt_fingerprint(_prompt_of(scanner_config)) == current_source:
+ and scale the current question already came from. Call it before the save's transaction opens."""
+ if _source_of(scanner_config) == current_source:
return {}
return condense_prompt(team_id=team_id, scanner_type=scanner_type, scanner_config=scanner_config).as_fields()
@@ -192,18 +246,32 @@ def scanner_question(scanner: ReplayScanner) -> str:
"""The question for the scanner's current prompt. A question written for another prompt, or none yet, falls
back to the prompt's first line."""
prompt = _prompt_of(scanner.scanner_config)
- if scanner.prompt_question and scanner.prompt_question_source == prompt_fingerprint(prompt):
+ if scanner.prompt_question and scanner.prompt_question_source == _source_of(scanner.scanner_config):
return scanner.prompt_question
return fallback_question(prompt)
+def _from_snapshot_prompt(snapshot_config: object, source: str) -> bool:
+ return source == _source_of(snapshot_config)
+
+
def question_for_snapshot(*, snapshot_config: object, question: str, source: str) -> str | None:
"""The scanner's question if it came from the prompt this observation was scanned with, else None."""
- if not question or source != prompt_fingerprint(_prompt_of(snapshot_config)):
+ if not question or not _from_snapshot_prompt(snapshot_config, source):
return None
return question
+def valence_for_snapshot(
+ *, snapshot_config: object, scanner_type: object, valence: str, source: str
+) -> PromptValence | None:
+ """The scanner's valence if its type answers with a direction and it came from the prompt this observation was
+ scanned with, else None."""
+ if scanner_type not in _DIRECTIONAL_TYPES or not valence or not _from_snapshot_prompt(snapshot_config, source):
+ return None
+ return PromptValence(valence)
+
+
@frozen
class BackfillResult:
checked: int
@@ -218,10 +286,11 @@ def backfill_prompt_questions(
dry_run: bool = False,
) -> BackfillResult:
"""Give every scanner whose question is missing or came from another prompt a question for its current prompt.
+ A monitor or scorer whose current question has no valence gets only a valence, so its question keeps its wording.
Writes through a queryset update, so the scanner's version, updated_at and activity log stay untouched.
The update is conditional on the prompt still being the one condensed, so an edit that lands mid-run wins.
- Each distinct prompt is condensed once per run and scanner type, since many scanners share one word for word.
+ Each distinct prompt is condensed once per run, team and scanner type, since many scanners share one word for word.
Inline scanners only take a template's question, the same rule `create_inline_scanner` follows.
"""
scanners = ReplayScanner.all_origins.order_by("created_at")
@@ -230,15 +299,20 @@ def backfill_prompt_questions(
if team_id is not None:
scanners = scanners.filter(team_id=team_id)
checked = written = 0
- condensed: dict[tuple[str, str], PromptQuestion] = {}
+ condensed: dict[tuple[int, str, str], PromptQuestion] = {}
for scanner in scanners.only(
- "id", "team_id", "origin", "scanner_type", "scanner_config", "prompt_question_source"
+ "id", "team_id", "origin", "scanner_type", "scanner_config", "prompt_question_source", "prompt_valence"
).iterator():
if limit is not None and written >= limit:
break
checked += 1
- source = prompt_fingerprint(_prompt_of(scanner.scanner_config))
- if source == scanner.prompt_question_source:
+ source = _source_of(scanner.scanner_config)
+ # A question written before the scale joined the fingerprint still matches its prompt, so it keeps its wording.
+ question_is_current = scanner.prompt_question_source in (
+ source,
+ prompt_fingerprint(_prompt_of(scanner.scanner_config)),
+ )
+ if question_is_current and (scanner.scanner_type not in _DIRECTIONAL_TYPES or scanner.prompt_valence):
continue
inline_template = template_question(scanner.scanner_config) if scanner.origin == ScannerOrigin.INLINE else None
if scanner.origin == ScannerOrigin.INLINE and inline_template is None:
@@ -246,8 +320,8 @@ def backfill_prompt_questions(
if dry_run:
written += 1
continue
- # The phrasing depends on the scanner type, so the same prompt on another type gets its own question.
- key = (source, scanner.scanner_type)
+ # Keyed by team too, since the answer can echo a team's own scale label.
+ key = (scanner.team_id, source, scanner.scanner_type)
question = inline_template or condensed.get(key)
if question is None:
question = condense_prompt(
@@ -256,9 +330,19 @@ def backfill_prompt_questions(
scanner_config=scanner.scanner_config,
metered=False,
)
- condensed[key] = question
+ # A failed call has no valence; the next scanner with this prompt tries the model again.
+ if question.valence:
+ condensed[key] = question
+ fields = question.as_fields()
# Zero rows when the prompt was edited mid-run, which is then not a write of ours.
- written += ReplayScanner.all_origins.filter(pk=scanner.pk, scanner_config=scanner.scanner_config).update(
- **question.as_fields()
- )
+ unchanged = ReplayScanner.all_origins.filter(pk=scanner.pk, scanner_config=scanner.scanner_config)
+ if question_is_current:
+ # A failed model call carries no valence, and writing its question would replace a model-written one.
+ fields = {"prompt_question_source": source}
+ if question.valence:
+ fields["prompt_valence"] = question.valence
+ unchanged = unchanged.filter(prompt_valence="")
+ elif scanner.prompt_question_source == source:
+ continue
+ written += unchanged.update(**fields)
return BackfillResult(checked=checked, written=written)
diff --git a/products/replay_vision/backend/tests/test_prompt_questions.py b/products/replay_vision/backend/tests/test_prompt_questions.py
index 9dd4be6115fb..454d2f6ac65e 100644
--- a/products/replay_vision/backend/tests/test_prompt_questions.py
+++ b/products/replay_vision/backend/tests/test_prompt_questions.py
@@ -9,6 +9,8 @@ from django.utils import timezone
from parameterized import parameterized
+from posthog.models.team import Team
+
from products.replay_vision.backend.inline_scan import create_inline_scanner
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
@@ -32,14 +34,16 @@ from products.replay_vision.backend.prompt_questions import (
)
from products.replay_vision.backend.tests.helpers import snapshot_for
-TEMPLATE_PROMPT, TEMPLATE_QUESTION = next(iter(TEMPLATE_QUESTIONS.items()))
+TEMPLATE_PROMPT, (TEMPLATE_QUESTION, _) = next(iter(TEMPLATE_QUESTIONS.items()))
PROMPT = "Did the user struggle to complete checkout?\n\nAnswer yes if they retried the payment form."
LONG_FIRST_LINE = "Look at " + "the checkout flow and " * 20
-def _model_says(client: MagicMock, question: str) -> None:
+def _model_says(client: MagicMock, question: str, valence: str = "bad") -> None:
client.return_value.models.generate_content.side_effect = None
- client.return_value.models.generate_content.return_value = MagicMock(text=json.dumps({"question": question}))
+ client.return_value.models.generate_content.return_value = MagicMock(
+ text=json.dumps({"question": question, "valence": valence})
+ )
class TestPromptQuestions(APIBaseTest):
@@ -72,23 +76,39 @@ class TestPromptQuestions(APIBaseTest):
@parameterized.expand(
[
- ("model_answer", "Did the user struggle at checkout?", PROMPT, True, "Did the user struggle at checkout?"),
- ("not_a_question", "Checkout struggles", PROMPT, True, "Did the user struggle to complete checkout?"),
+ (
+ "model_answer",
+ "Did the user struggle at checkout?",
+ PROMPT,
+ True,
+ "Did the user struggle at checkout?",
+ "bad",
+ ),
+ (
+ "not_a_question_keeps_valence",
+ "Checkout struggles",
+ PROMPT,
+ True,
+ "Did the user struggle to complete checkout?",
+ "bad",
+ ),
(
"too_long",
"Did " + "x" * MAX_QUESTION_CHARS + "?",
PROMPT,
True,
"Did the user struggle to complete checkout?",
+ "bad",
),
- ("model_error", None, PROMPT, True, "Did the user struggle to complete checkout?"),
- ("client_setup_fails", "setup-fails", PROMPT, True, "Did the user struggle to complete checkout?"),
+ ("model_error", None, PROMPT, True, "Did the user struggle to complete checkout?", ""),
+ ("client_setup_fails", "setup-fails", PROMPT, True, "Did the user struggle to complete checkout?", ""),
(
"no_ai_consent",
"Did the user struggle at checkout?",
PROMPT,
False,
"Did the user struggle to complete checkout?",
+ "",
),
(
"long_first_line_is_cut",
@@ -96,12 +116,21 @@ class TestPromptQuestions(APIBaseTest):
LONG_FIRST_LINE,
True,
LONG_FIRST_LINE[: MAX_QUESTION_CHARS - 1].rstrip() + "…",
+ "",
),
- ("empty_prompt", "Did anything happen?", " ", True, ""),
- ("template_needs_no_call", "Did anything happen?", TEMPLATE_PROMPT, False, TEMPLATE_QUESTION),
+ ("empty_prompt", "Did anything happen?", " ", True, "", ""),
+ ("template_needs_no_call", "Did anything happen?", TEMPLATE_PROMPT, False, TEMPLATE_QUESTION, "bad"),
]
)
- def test_condense_prompt(self, _name: str, reply: str | None, prompt: str, consent: bool, expected: str) -> None:
+ def test_condense_prompt(
+ self,
+ _name: str,
+ reply: str | None,
+ prompt: str,
+ consent: bool,
+ expected: str,
+ expected_valence: str,
+ ) -> None:
if reply is None:
self.client_mock.return_value.models.generate_content.side_effect = RuntimeError("provider down")
elif reply == "setup-fails":
@@ -114,6 +143,7 @@ class TestPromptQuestions(APIBaseTest):
question = condense_prompt(team_id=self.team.id, scanner_type="monitor", scanner_config={"prompt": prompt})
assert question.question == expected
+ assert (question.valence or "") == expected_valence
assert question.source == prompt_fingerprint(prompt)
if not consent:
self.client_mock.return_value.models.generate_content.assert_not_called()
@@ -182,8 +212,32 @@ class TestPromptQuestions(APIBaseTest):
assert scanner.prompt_question == "Did the user abandon their cart?"
assert scanner.prompt_question_source == prompt_fingerprint("Did the user abandon their cart?")
+ def test_scale_label_edit_judges_the_valence_again(self) -> None:
+ _model_says(self.client_mock, "How frustrated did the user appear?", valence="bad")
+ config: dict[str, Any] = {"prompt": PROMPT, "scale": {"min": 0, "max": 10, "label": "frustration"}}
+ created = self.client.post(
+ self.scanners_url,
+ data={
+ "name": "mood",
+ "scanner_type": ScannerType.SCORER,
+ "scanner_config": config,
+ "model": ScannerModel.GEMINI_3_8_FLASH,
+ },
+ format="json",
+ )
+ assert created.status_code == 201, created.json()
+
+ _model_says(self.client_mock, "How satisfied did the user appear?", valence="good")
+ config["scale"]["label"] = "satisfaction"
+ edited = self.client.patch(
+ f"{self.scanners_url}{created.json()['id']}/", data={"scanner_config": config}, format="json"
+ )
+ assert edited.status_code == 200, edited.json()
+ scanner = ReplayScanner.objects.get(id=created.json()["id"])
+ assert (scanner.prompt_question, scanner.prompt_valence) == ("How satisfied did the user appear?", "good")
+
def test_observation_shows_the_question_only_for_the_prompt_it_was_scanned_with(self) -> None:
- scanner = self._scanner(prompt_question="Did the user struggle at checkout?")
+ scanner = self._scanner(prompt_question="Did the user struggle at checkout?", prompt_valence="bad")
scanner.prompt_question_source = prompt_fingerprint(PROMPT)
scanner.save()
observation = ReplayObservation.objects.create(
@@ -198,6 +252,7 @@ class TestPromptQuestions(APIBaseTest):
url = f"/api/projects/{self.team.id}/vision/observations/{observation.id}/"
assert self.client.get(url).json()["prompt_question"] == "Did the user struggle at checkout?"
+ assert self.client.get(url).json()["prompt_valence"] == "bad"
ReplayScanner.objects.filter(pk=scanner.pk).update(
scanner_config={"prompt": "Did the user abandon their cart?"},
@@ -205,6 +260,7 @@ class TestPromptQuestions(APIBaseTest):
prompt_question_source=prompt_fingerprint("Did the user abandon their cart?"),
)
assert self.client.get(url).json()["prompt_question"] is None
+ assert self.client.get(url).json()["prompt_valence"] is None
def test_backfill_fills_only_stale_questions_without_touching_the_scanner_version(self) -> None:
stale = self._scanner(name="stale")
@@ -215,19 +271,23 @@ class TestPromptQuestions(APIBaseTest):
)
fresh = self._scanner(name="fresh")
ReplayScanner.objects.filter(pk=fresh.pk).update(
- prompt_question="Kept as is?", prompt_question_source=prompt_fingerprint(PROMPT)
+ prompt_question="Kept as is?", prompt_question_source=prompt_fingerprint(PROMPT), prompt_valence="good"
+ )
+ unjudged = self._scanner(name="unjudged")
+ ReplayScanner.objects.filter(pk=unjudged.pk).update(
+ prompt_question="Judged before valence?", prompt_question_source=prompt_fingerprint(PROMPT)
)
version = ReplayScanner.objects.get(pk=stale.pk).scanner_version
dry = backfill_prompt_questions(team_id=self.team.id, dry_run=True)
- assert (dry.checked, dry.written) == (4, 3)
+ assert (dry.checked, dry.written) == (5, 4)
assert ReplayScanner.objects.get(pk=stale.pk).prompt_question == ""
self.client_mock.return_value.models.generate_content.reset_mock()
result = backfill_prompt_questions(team_id=self.team.id)
- assert result.written == 3
- # The copy shares the stale scanner's prompt and the template needs none, so one call covers all three.
+ assert result.written == 4
+ # The other monitors share the stale scanner's prompt and the template needs none, so one call covers all four.
assert self.client_mock.return_value.models.generate_content.call_count == 1
assert ReplayScanner.objects.get(pk=copy.pk).prompt_question == "Did the user struggle at checkout?"
assert ReplayScanner.objects.get(pk=template.pk).prompt_question == TEMPLATE_QUESTION
@@ -236,6 +296,40 @@ class TestPromptQuestions(APIBaseTest):
assert stale.prompt_question_source == prompt_fingerprint(PROMPT)
assert stale.scanner_version == version
assert ReplayScanner.objects.get(pk=fresh.pk).prompt_question == "Kept as is?"
+ unjudged.refresh_from_db()
+ assert (unjudged.prompt_question, unjudged.prompt_valence) == ("Judged before valence?", "bad")
+
+ def test_backfill_never_shares_an_answer_across_teams(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other team")
+ scale = {"min": 0, "max": 10, "label": "checkout friction"}
+ ours = self._scanner(scanner_type=ScannerType.SCORER, scanner_config={"prompt": PROMPT, "scale": scale})
+ theirs = self._scanner(
+ team=other_team, scanner_type=ScannerType.SCORER, scanner_config={"prompt": PROMPT, "scale": scale}
+ )
+ ReplayScanner.all_origins.filter(pk__in=[ours.pk, theirs.pk]).update(
+ prompt_question="", prompt_question_source=""
+ )
+
+ backfill_prompt_questions()
+
+ assert self.client_mock.return_value.models.generate_content.call_count == 2
+
+ def test_backfill_retries_the_model_for_each_scanner_after_a_failed_call(self) -> None:
+ unjudged = self._scanner(name="unjudged")
+ retried = self._scanner(name="retried")
+ ReplayScanner.objects.filter(pk__in=[unjudged.pk, retried.pk]).update(
+ prompt_question="Judged before valence?", prompt_question_source=prompt_fingerprint(PROMPT)
+ )
+ reply = MagicMock(text=json.dumps({"question": "Did the user struggle at checkout?", "valence": "bad"}))
+ self.client_mock.return_value.models.generate_content.side_effect = [RuntimeError("provider down"), reply]
+
+ result = backfill_prompt_questions(team_id=self.team.id)
+
+ assert result.written == 1
+ unjudged.refresh_from_db()
+ retried.refresh_from_db()
+ assert (unjudged.prompt_question, unjudged.prompt_valence) == ("Judged before valence?", "")
+ assert (retried.prompt_question, retried.prompt_valence) == ("Judged before valence?", "bad")
def test_inline_scanners_only_ever_get_a_template_question(self) -> None:
self.client_mock.return_value.models.generate_content.reset_mock()
diff --git a/products/replay_vision/frontend/components/ObservationDockCard.stories.tsx b/products/replay_vision/frontend/components/ObservationDockCard.stories.tsx
index 3d7dce7c1eda..7b45356cba8b 100644
--- a/products/replay_vision/frontend/components/ObservationDockCard.stories.tsx
+++ b/products/replay_vision/frontend/components/ObservationDockCard.stories.tsx
@@ -39,6 +39,7 @@ const observation = (overrides: Partial<ReplayObservationApi> = {}): ReplayObser
signals_count: 1,
},
prompt_question: 'Did the user struggle to complete checkout?',
+ prompt_valence: 'bad',
triggered_by: 'schedule',
triggered_by_user: null,
distinct_id: 'user_2m1x9d',
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 4c632b57044a..65968442832e 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -688,6 +688,14 @@ export interface ScannerResultApi {
session_duration_s?: number | null
}
+export type PromptValenceEnumApi = (typeof PromptValenceEnumApi)[keyof typeof PromptValenceEnumApi]
+
+export const PromptValenceEnumApi = {
+ Good: 'good',
+ Bad: 'bad',
+ Neutral: 'neutral',
+} as const
+
/**
* * `schedule` - Schedule
* * `on_demand` - On demand
@@ -792,6 +800,8 @@ export interface ReplayObservationApi {
* @nullable
*/
readonly prompt_question: string | null
+ /** For a monitor or scorer: `good` when a yes or a high score is good news for the team, `bad` when it is a problem, `neutral` when neither. Judged by AI from the prompt. Null for other scanner types, when not judged, or when the prompt has changed since this observation was scanned. */
+ readonly prompt_valence: PromptValenceEnumApi | null
/** Whether this observation came from the schedule, an on-demand request, a retry of a failed or ineligible observation, or a historical backfill.
*
* * `schedule` - Schedule
diff --git a/products/replay_vision/frontend/observations/ObservationHeadline.tsx b/products/replay_vision/frontend/observations/ObservationHeadline.tsx
index 1ef6a3825ea0..4be29a1a630a 100644
--- a/products/replay_vision/frontend/observations/ObservationHeadline.tsx
+++ b/products/replay_vision/frontend/observations/ObservationHeadline.tsx
@@ -3,7 +3,7 @@ import { Tooltip } from '@posthog/lemon-ui'
import { LabeledRow } from '../components/LabeledRow'
import { ObservationPrimaryOutput } from '../components/ObservationCard'
-import type { ReplayObservationApi, ScannerTypeEnumApi } from '../generated/api.schemas'
+import type { PromptValenceEnumApi, ReplayObservationApi, ScannerTypeEnumApi } from '../generated/api.schemas'
import { configFromSnapshot, type ScorerScannerConfig } from '../replay_scanners/types'
import {
type MonitorVerdict,
@@ -30,10 +30,29 @@ const HEADLINE_LABEL: Record<ScannerTypeEnumApi, string> = {
}
// The `--success`/`--danger` family LemonTag uses. The `text-success` utility maps to a different, brighter green.
-const VERDICT_STYLE: Record<MonitorVerdict, { icon: typeof IconCheckCircle; className: string }> = {
- yes: { icon: IconCheckCircle, className: 'text-success-dark dark:text-success-light' },
- no: { icon: IconXCircle, className: 'text-danger-dark dark:text-danger-light' },
- inconclusive: { icon: IconQuestion, className: 'text-secondary dark:text-default' },
+const GOOD_CLASS = 'text-success-dark dark:text-success-light'
+const BAD_CLASS = 'text-danger-dark dark:text-danger-light'
+
+const VERDICT_ICON: Record<MonitorVerdict, typeof IconCheckCircle> = {
+ yes: IconCheckCircle,
+ no: IconXCircle,
+ inconclusive: IconQuestion,
+}
+
+type Direction = 'good' | 'bad'
+
+function direction(valence: PromptValenceEnumApi | null): Direction | null {
+ return valence === 'good' || valence === 'bad' ? valence : null
+}
+
+function verdictClass(verdict: MonitorVerdict, yesIs: Direction | null): string {
+ if (verdict === 'inconclusive') {
+ return 'text-secondary dark:text-default'
+ }
+ if (!yesIs) {
+ return 'text-default'
+ }
+ return (verdict === 'yes') === (yesIs === 'good') ? GOOD_CLASS : BAD_CLASS
}
function scorerScale(observation: ReplayObservationApi): { min: number; max: number | null; label: string | null } {
@@ -67,9 +86,10 @@ function headlineLabel(observation: ReplayObservationApi, scannerType: ScannerTy
return `${label} · ${shown}`
}
-/** Red at the bottom of the scale, amber in the middle, green at the top. */
-function scoreColor(score: number, min: number, max: number): string {
- const position = max > min ? Math.min(1, Math.max(0, (score - min) / (max - min))) : 1
+/** Red at the bad end of the scale through amber to green at the good end. */
+function scoreColor(score: number, min: number, max: number, highIs: Direction): string {
+ const fromMin = max > min ? Math.min(1, Math.max(0, (score - min) / (max - min))) : 1
+ const position = highIs === 'good' ? fromMin : 1 - fromMin
return position < 0.5
? `color-mix(in oklab, var(--warning) ${Math.round(position * 200)}%, var(--danger))`
: `color-mix(in oklab, var(--success) ${Math.round((position - 0.5) * 200)}%, var(--warning))`
@@ -89,10 +109,10 @@ function HeadlineValue({
if (!verdict) {
return <span className="text-xl font-bold text-muted">—</span>
}
- const { icon: Icon, className } = VERDICT_STYLE[verdict]
+ const Icon = VERDICT_ICON[verdict]
return (
<span
- className={`inline-flex items-center gap-1.5 text-xl font-bold ${className}`}
+ className={`inline-flex items-center gap-1.5 text-xl font-bold ${verdictClass(verdict, direction(observation.prompt_valence))}`}
data-attr="vision-observation-verdict"
>
<Icon className="text-2xl" />
@@ -104,12 +124,14 @@ function HeadlineValue({
if (scannerType === 'scorer') {
const score = readScore(observation)
const { min, max } = scorerScale(observation)
+ const highIs = direction(observation.prompt_valence)
+ const color = score !== null && max !== null && highIs ? scoreColor(score, min, max, highIs) : null
return (
<span className="text-3xl font-bold tabular-nums">
<span
// The color is a position on a continuous scale, which Tailwind classes can't express.
// eslint-disable-next-line react/forbid-dom-props
- style={score !== null && max !== null ? { color: scoreColor(score, min, max) } : undefined}
+ style={color ? { color } : undefined}
>
{score ?? '—'}
</span>
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
index ba840a7da9aa..8a9e29463f4e 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
@@ -415,6 +415,7 @@ const observation = (overrides: Partial<ReplayObservationApi> = {}): ReplayObser
signals_count: 0,
},
prompt_question: null,
+ prompt_valence: null,
triggered_by: 'schedule',
triggered_by_user: null,
distinct_id: 'user_8f3k2j',
@@ -558,6 +559,7 @@ const observationDetail = observation({
// keep the one-paragraph reasoning most scans produce.
const monitorObservationDetail = observation({
prompt_question: 'Did the user struggle to complete checkout?',
+ prompt_valence: 'bad',
id: '00000000-0000-0000-0000-0000000000d2',
session_id: '01966b3f-70a1-7c52-a4d5-3f9b2e8c1d11',
recording_subject_email: '[email protected]',
@@ -1478,21 +1480,24 @@ const classifierObservationDetail = observationDetailFor(
'Which friction patterns appear in this session?'
)
-const scorerObservationDetail = observationDetailFor(
- {
- ...scorerOverviewScanner,
- scanner_config: { prompt: SCORER_DETAIL_PROMPT, scale: { min: 0, max: 10, label: 'buying intent' } },
- },
- '00000000-0000-0000-0000-0000000000d5',
- {
- score: 8.5,
- label: 'buying intent',
- confidence: 0.41,
- reasoning:
- 'The user spent about two minutes on the pricing page comparing the Growth and Enterprise plans, then opened the Billing tab and started to add a card before closing the form. Right after that they invited two teammates from the Members page. Looking at billing and then inviting a team puts this in the high band of the prompt, but not at the top, because the payment details were never saved and the rest of the session was spent back in the product.',
- },
- 'How strong is the buying intent in this session?'
-)
+const scorerObservationDetail: ReplayObservationApi = {
+ ...observationDetailFor(
+ {
+ ...scorerOverviewScanner,
+ scanner_config: { prompt: SCORER_DETAIL_PROMPT, scale: { min: 0, max: 10, label: 'buying intent' } },
+ },
+ '00000000-0000-0000-0000-0000000000d5',
+ {
+ score: 8.5,
+ label: 'buying intent',
+ confidence: 0.41,
+ reasoning:
+ 'The user spent about two minutes on the pricing page comparing the Growth and Enterprise plans, then opened the Billing tab and started to add a card before closing the form. Right after that they invited two teammates from the Members page. Looking at billing and then inviting a team puts this in the high band of the prompt, but not at the top, because the payment details were never saved and the rest of the session was spent back in the product.',
+ },
+ 'How strong is the buying intent in this session?'
+ ),
+ prompt_valence: 'good',
+}
const observationDetailStory = (detail: ReplayObservationApi): StoryObj => ({
parameters: { pageUrl: urls.replayVisionObservation(detail.id) },
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 488397fb36ad..a60813af7f73 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -44937,6 +44937,15 @@ export namespace Schemas {
session_duration_s?: number | null;
}
+ export type PromptValenceEnum = typeof PromptValenceEnum[keyof typeof PromptValenceEnum];
+
+
+ export const PromptValenceEnum = {
+ Good: 'good',
+ Bad: 'bad',
+ Neutral: 'neutral',
+ } as const;
+
/**
* * `schedule` - Schedule
* * `on_demand` - On demand
@@ -45042,6 +45051,8 @@ export namespace Schemas {
* @nullable
*/
readonly prompt_question: string | null;
+ /** For a monitor or scorer: `good` when a yes or a high score is good news for the team, `bad` when it is a problem, `neutral` when neither. Judged by AI from the prompt. Null for other scanner types, when not judged, or when the prompt has changed since this observation was scanned. */
+ readonly prompt_valence: PromptValenceEnum | null;
/** Whether this observation came from the schedule, an on-demand request, a retry of a failed or ineligible observation, or a historical backfill.
*
* * `schedule` - Schedule