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.

fix(replay-vision): re-prompt when an answer has broken characters (#113657)

Tue Haulund7c6a88865bd3
diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
index 8b215b8d19f0..dea899d71b7b 100644
--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
@@ -8,6 +8,7 @@ Each step validates its own output and re-prompts once on failure; required step
"""
import re
+import json
import math
import time
import asyncio
@@ -929,6 +930,17 @@ async def _run_step(
# The cap counts thoughts, so the usual "respond with raw JSON" correction would only re-run the
# same reasoning into the same wall. Name the cause so the re-prompt asks for less thinking.
error = "the response ran out of output tokens before the JSON was complete; reason more briefly"
+ answer = response.candidates[0].content
+ if parsed is not None and _has_control_chars(parsed.model_dump(mode="json")):
+ if attempt < _MAX_LLM_ATTEMPTS - 1:
+ parsed, error = None, _CONTROL_CHARS_ERROR
+ else:
+ # Postgres cannot store some of these characters, so a lost letter is better than a lost observation.
+ logger.warning("replay_vision.call_scanner_provider.control_chars_dropped", step=step.name)
+ scrubbed = json.dumps(_strip_control_chars(json.loads(text)), ensure_ascii=False)
+ parsed, error = _parse_and_validate(step, scrubbed)
+ # Later steps re-read this turn, so they get the cleaned answer rather than the broken characters.
+ answer = types.Content(role="model", parts=[types.Part(text=scrubbed)])
record_provider_call(
**metric_labels,
outcome="ok" if error is None else "output_cap_hit" if capped else "validation_failed",
@@ -936,7 +948,7 @@ async def _run_step(
)
if error is None:
- convo.append(response.candidates[0].content) # carry the answer into the next turn
+ convo.append(answer) # carry the answer into the next turn
return _StepResult(output=parsed)
last_error = error
@@ -984,6 +996,35 @@ def _is_runaway_number(exc: ValueError) -> bool:
return "integer string conversion" in str(exc)
+# The model sometimes writes an accented letter as a wrong `\u` escape, which decodes to a control character.
+# Tab, newline and carriage return are left out because a real answer can contain them.
+_CONTROL_CHARS_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")
+_CONTROL_CHARS_ERROR = (
+ "the answer contains control characters where letters belong; write accented and non-English letters "
+ "directly, never as \\u escapes"
+)
+
+
+def _has_control_chars(value: Any) -> bool:
+ if isinstance(value, str):
+ return _CONTROL_CHARS_RE.search(value) is not None
+ if isinstance(value, dict):
+ return any(_has_control_chars(key) or _has_control_chars(item) for key, item in value.items())
+ if isinstance(value, list):
+ return any(_has_control_chars(item) for item in value)
+ return False
+
+
+def _strip_control_chars(value: Any) -> Any:
+ if isinstance(value, str):
+ return _CONTROL_CHARS_RE.sub("", value)
+ if isinstance(value, dict):
+ return {_strip_control_chars(key): _strip_control_chars(item) for key, item in value.items()}
+ if isinstance(value, list):
+ return [_strip_control_chars(item) for item in value]
+ return value
+
+
def _hit_output_cap(response: Any) -> bool:
candidates = getattr(response, "candidates", None) or []
return bool(candidates) and getattr(candidates[0], "finish_reason", None) == types.FinishReason.MAX_TOKENS
diff --git a/products/replay_vision/backend/temporal/scanners/prompts/preamble.jinja b/products/replay_vision/backend/temporal/scanners/prompts/preamble.jinja
index 38b5bd06a803..64c6aefbc188 100644
--- a/products/replay_vision/backend/temporal/scanners/prompts/preamble.jinja
+++ b/products/replay_vision/backend/temporal/scanners/prompts/preamble.jinja
@@ -97,6 +97,10 @@ Consult this timeline before concluding the user was stuck or went nowhere. A ne
When a turn asks you to cite key moments, mark each one inline as `(t <seconds>)` — one moment per parens, using whole seconds of video time, counted from the start of the video file (e.g. `(t 92)`). Place each citation as a standalone parenthetical right after the moment it marks, so the sentence still reads cleanly with every `(t …)` removed: "the user reopened the picker three times (t 1540) before selecting (t 2415)". Cite sparingly — at most 1–2 per paragraph, reserved for turning points, blockers, and climaxes.
</citations>
+<text_output>
+Write every letter as itself, including accented and non-English letters such as "ç" or "ã", so interface text you quote reads exactly as it appears on screen. Never write a character as a `\u` escape.
+</text_output>
+
<confidence_calibration>
You'll be asked to rate your own `confidence` (0 to 1) in an answer, on one scale. At most 0.3 when the session never shows what the criterion is about (see relevance). Around 0.5 when there is some evidence but it is ambiguous or points both ways. Up to 0.8 when the conclusion rests on a single moment with no corroboration. 0.9 or above only for an unambiguous conclusion backed by two or more independent signals. Masked or missing content lowers confidence within these bands; it never raises it.
</confidence_calibration>
diff --git a/products/replay_vision/backend/tests/test_call_scanner_provider.py b/products/replay_vision/backend/tests/test_call_scanner_provider.py
index a972070c8e0b..171a4028a469 100644
--- a/products/replay_vision/backend/tests/test_call_scanner_provider.py
+++ b/products/replay_vision/backend/tests/test_call_scanner_provider.py
@@ -247,19 +247,38 @@ async def test_step_survives_a_response_with_no_candidates() -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize(
- "first",
+ "first,correction",
[
- _Resp(text="not json"),
- ValueError("Exceeds the limit (4300 digits) for integer string conversion: value has 16266 digits"),
+ (_Resp(text="not json"), "Respond with raw JSON only"),
+ (
+ ValueError("Exceeds the limit (4300 digits) for integer string conversion: value has 16266 digits"),
+ "Respond with raw JSON only",
+ ),
+ (_Resp(text='{"verdict":"conclu\\u0000"}'), "never as \\u escapes"),
],
)
-async def test_step_re_prompts_once_on_invalid_json(first: _Resp | Exception) -> None:
+async def test_step_re_prompts_once_on_invalid_json(first: _Resp | Exception, correction: str) -> None:
steps = [MissionStep(name="core", instruction="c", response_model=_Core)]
client = _FakeClient([first, _Resp(text='{"verdict":"yes"}')])
out = await _run(client, steps)
assert out["core"].verdict == "yes"
assert len(client.models.calls) == 2 # initial + one re-prompt
- assert "Respond with raw JSON only" in client.models.calls[1]["contents"][-1].text
+ assert correction in client.models.calls[1]["contents"][-1].text
+
+
+async def test_control_characters_left_after_the_re_prompt_are_dropped_not_the_answer() -> None:
+ steps = [MissionStep(name="core", instruction="c", response_model=_Core)]
+ client = _FakeClient(
+ [
+ _Resp(text='{"verdict":"a\\u0001\\u0000"}'),
+ _Resp(text='{"verdict":"nenhuma a\\u0000"}'),
+ _Resp(text='{"verdict":"yes"}'),
+ ]
+ )
+ out = await _run(client, [*steps, MissionStep(name="side", instruction="s", response_model=_Core)])
+ assert out["core"].verdict == "nenhuma a"
+ assert '"verdict": "nenhuma a"' in str(client.models.calls[2]["contents"])
@pytest.mark.asyncio