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): cap gemini 3.8 flash at three event lookups per step (#100810)

Tue Haulund026d58caf402
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 5ff371917b2e..abd3dde004dd 100644
--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
@@ -36,9 +36,14 @@ from posthog.temporal.common.heartbeat import Heartbeater
from products.replay_vision.backend.consent import is_ai_data_processing_approved
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.models.replay_scanner import ScannerModel
from products.replay_vision.backend.tags import slugify_tag
from products.replay_vision.backend.temporal.constants import replay_vision_distinct_id
-from products.replay_vision.backend.temporal.conversation import function_calls, run_tool_loop
+from products.replay_vision.backend.temporal.conversation import (
+ DEFAULT_MAX_TOOL_ITERATIONS,
+ function_calls,
+ run_tool_loop,
+)
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.errors import ConsentWithdrawnError, FailureKind, ScannerFailureError
from products.replay_vision.backend.temporal.events_tool import build_events_index, dispatch_events_tool, events_tool
@@ -79,6 +84,18 @@ _MAX_LLM_ATTEMPTS = 2 # one initial call + one re-prompt with the validation er
# One clean re-ask after a validation failure. The per-step re-prompt above retries inside the same conversation,
# where the model stays anchored on the answer it just got wrong; a fresh conversation is an independent draw.
_MAX_MISSION_ATTEMPTS = 2
+
+# Event lookups a step may spend before the forced tool-free answer. Gemini 3.8 Flash follows "look it up"
+# far more eagerly than earlier Flash models, and each extra round-trip appends an uncached tool response and
+# another reasoning pass, so its scans cost more at the same list price. Cap it lower than the loop default.
+_MAX_TOOL_ITERATIONS_BY_MODEL: dict[str, int] = {ScannerModel.GEMINI_3_8_FLASH: 3}
+
+
+def _tool_budget(model: str) -> int:
+ """Event lookups per step for `model`, accepting either the bare id or the `models/` form the API takes."""
+ return _MAX_TOOL_ITERATIONS_BY_MODEL.get(model.removeprefix("models/"), DEFAULT_MAX_TOOL_ITERATIONS)
+
+
# Snapshot `verify_positives` values that draw; anything else (including a typo) behaves as `off`.
_VERIFY_MODES = ("shadow", "enforce")
# Activity time kept free of verify draws, so assembling and returning the result never races the timeout.
@@ -193,6 +210,7 @@ async def run_scan(
events_truncated=llm_inputs.events_truncated,
product_context=llm_inputs.product_context,
event_descriptions=llm_inputs.event_descriptions,
+ tool_budget=_tool_budget(snapshot.model),
)
video_part = types.Part(file_data=types.FileData(file_uri=file_uri, mime_type=mime_type))
@@ -701,7 +719,9 @@ async def _run_step(
for attempt in range(_MAX_LLM_ATTEMPTS):
started = time.monotonic()
try:
- response = await run_tool_loop(generate=_generate, convo=convo, dispatch=dispatch)
+ response = await run_tool_loop(
+ generate=_generate, convo=convo, dispatch=dispatch, max_tool_iterations=_tool_budget(model)
+ )
if function_calls(response):
# Tool budget spent and the model still wants a lookup. Rather than hard-fail, complete the
# round-trip and force one final tool-free turn so it answers from what it has already seen.
diff --git a/products/replay_vision/backend/temporal/scanners/base.py b/products/replay_vision/backend/temporal/scanners/base.py
index 8ed764206b77..a852df883695 100644
--- a/products/replay_vision/backend/temporal/scanners/base.py
+++ b/products/replay_vision/backend/temporal/scanners/base.py
@@ -9,6 +9,7 @@ from pydantic import BaseModel, Field, field_validator, model_validator
from posthog.dataclasses import frozen
+from products.replay_vision.backend.temporal.conversation import DEFAULT_MAX_TOOL_ITERATIONS
from products.replay_vision.backend.temporal.scanners.prompt_env import render_prompt
# `(t 123)` / `(t 123, 456)` / `(t 12, t 34)` citation markers. The prompt asks for one moment per parens, but the
@@ -195,6 +196,7 @@ class BaseScanner(BaseModel, frozen=True):
events_truncated: bool = False,
product_context: str = "",
event_descriptions: dict[str, str] | None = None,
+ tool_budget: int = DEFAULT_MAX_TOOL_ITERATIONS,
) -> str:
"""The conversation's shared opening: framing, footer, events tool, calibration, navigation timeline, and
session metadata and identity. `navigation` and `session_identity` take dumped model dicts (plain dicts keep
@@ -209,6 +211,8 @@ class BaseScanner(BaseModel, frozen=True):
events_truncated=events_truncated,
product_context=product_context,
event_descriptions=event_descriptions or {},
+ tool_budget=tool_budget,
+ default_tool_budget=DEFAULT_MAX_TOOL_ITERATIONS,
)
def core_steps(self) -> list[MissionStep]:
diff --git a/products/replay_vision/backend/temporal/scanners/prompts/preamble.jinja b/products/replay_vision/backend/temporal/scanners/prompts/preamble.jinja
index af6100a0b965..0aa5f1f4004a 100644
--- a/products/replay_vision/backend/temporal/scanners/prompts/preamble.jinja
+++ b/products/replay_vision/backend/temporal/scanners/prompts/preamble.jinja
@@ -38,7 +38,7 @@ The replay reconstructs each page from DOM snapshots, so states the user never s
<events_tool>
You have a tool, `get_events_around`: pass a footer `REC_T` and it returns the events within a few seconds of that moment, each tagged with its own `rec_t`. Fields include `event`, `$current_url`, `$event_type`, `elements_chain_*` (what was interacted with), and `$exception_types`/`$exception_values`.
-Use it liberally — call it for any moment that looks interesting, and always before you judge whether the user succeeded, failed, or hit friction, which are easy to misread from the video alone. `$rageclick` (the same element clicked again and again) and `$dead_click` (a click that changed nothing) are the highest-signal friction events: treat them as ground truth, concluding one only when `get_events_around` confirms it at that `REC_T`, not from interaction bursts on tabs, dropdowns, or other re-clickable controls.
+{% if tool_budget < default_tool_budget %}You can call it up to {{ tool_budget }} times per task, so spend those calls on the moments that decide your answer: always look up the moment where you judge whether the user succeeded, failed, or hit friction, which are easy to misread from the video alone, and skip moments that would not change your verdict.{% else %}Use it liberally — call it for any moment that looks interesting, and always before you judge whether the user succeeded, failed, or hit friction, which are easy to misread from the video alone.{% endif %} `$rageclick` (the same element clicked again and again) and `$dead_click` (a click that changed nothing) are the highest-signal friction events: treat them as ground truth, concluding one only when `get_events_around` confirms it at that `REC_T`, not from interaction bursts on tabs, dropdowns, or other re-clickable controls.
{% if events_truncated %}
This session produced more events than the tool can hold, so only the earliest portion is available. Later moments may return nothing even though something happened there — treat a missing result near the end of the session as "unknown", not as "nothing happened".
{% endif %}</events_tool>
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 8e09909ff622..3bdc720ff834 100644
--- a/products/replay_vision/backend/tests/test_call_scanner_provider.py
+++ b/products/replay_vision/backend/tests/test_call_scanner_provider.py
@@ -80,10 +80,16 @@ def _fc(name: str, args: dict[str, Any]) -> Any:
return type("FC", (), {"name": name, "args": args})()
-async def _run(client: _FakeClient, steps: list[MissionStep], dispatch: Any = lambda c: {}, cache_name=None):
+async def _run(
+ client: _FakeClient,
+ steps: list[MissionStep],
+ dispatch: Any = lambda c: {},
+ cache_name=None,
+ model: str = "models/gemini-3-flash-preview",
+):
return await _run_steps(
client=client,
- model="models/gemini-3-flash-preview",
+ model=model,
steps=steps,
video_part=_VIDEO,
preamble_text="PRE",
@@ -184,17 +190,21 @@ async def test_step_runs_a_tool_call_then_answers() -> None:
@pytest.mark.asyncio
-async def test_tool_budget_exhaustion_forces_a_final_tool_free_answer() -> None:
+ "model,budget",
+ [("models/gemini-3-flash-preview", 6), ("models/gemini-3.8-flash", 3)],
+)
+async def test_tool_budget_exhaustion_forces_a_final_tool_free_answer(model: str, budget: int) -> None:
# The model keeps calling the tool until the budget is gone; instead of hard-failing, the step forces one final
# turn with tools removed and the model answers from what it has already seen.
steps = [MissionStep(name="core", instruction="c", response_model=_Core)]
- # initial generate + 6 tool iterations = 7 function-call responses, then the forced tool-free answer.
- responses = [_Resp(function_call=_fc("get_events_around", {"rec_t": 5})) for _ in range(7)]
+ # initial generate + `budget` tool iterations = budget + 1 function-call responses, then the forced answer.
+ responses = [_Resp(function_call=_fc("get_events_around", {"rec_t": 5})) for _ in range(budget + 1)]
responses.append(_Resp(text='{"verdict":"yes"}'))
client = _FakeClient(responses)
- out = await _run(client, steps, dispatch=lambda fc: {"events": []})
+ out = await _run(client, steps, dispatch=lambda fc: {"events": []}, model=model)
assert out["core"].verdict == "yes"
- assert len(client.models.calls) == 8 # 7 tool turns + 1 forced answer
+ assert len(client.models.calls) == budget + 2 # tool turns + 1 forced answer
assert client.models.calls[0]["config"].tools is not None # tool offered during the loop
assert client.models.calls[-1]["config"].tools is None # tools removed on the forced turn