: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
fix(replay-vision): don't set tool_config alongside cached_content (#80523)
Tue Haulundd95606c88c10
diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.pyindex 2e4521ab4860..5893e763bd55 100644--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py@@ -421,6 +421,8 @@ async def _run_steps(step=step,convo=convo,cache_name=cache_name,+ video_part=video_part,+ preamble_text=preamble_text,dispatch=dispatch,team_id=team_id,metric_labels=metric_labels,@@ -458,6 +460,8 @@ async def _run_step(step: MissionStep,convo: list[Any],cache_name: str | None,+ video_part: types.Part,+ preamble_text: str,dispatch: Any,team_id: int,metric_labels: dict[str, str],@@ -469,6 +473,9 @@ async def _run_step("""config = _step_config(step, cache_name)forced_config = _step_config(step, cache_name, allow_tools=False)+ # The forced final turn runs inline (it can't reuse the cache, which pins the tool on). When the run is cached,+ # `convo` omits the video + preamble prefix — those live in the cache — so re-supply them inline for that turn.+ forced_prefix = [video_part, types.Part(text=preamble_text)] if cache_name else []async def _generate(c: list[Any], cfg: types.GenerateContentConfig = config) -> Any:return await client.models.generate_content(@@ -498,7 +505,10 @@ async def _run_step()started = time.monotonic()response = await _force_final_answer(- generate=lambda c: _generate(c, forced_config), convo=convo, exhausted=response, dispatch=dispatch+ generate=lambda c: _generate(forced_prefix + c, forced_config),+ convo=convo,+ exhausted=response,+ dispatch=dispatch,)except Exception:record_provider_call(**metric_labels, outcome="provider_error", seconds=time.monotonic() - started)@@ -585,20 +595,22 @@ async def _force_final_answer(*, generate: Any, convo: list[Any], exhausted: Anydef _step_config(step: MissionStep, cache_name: str | None, *, allow_tools: bool = True) -> types.GenerateContentConfig:"""Generation config for one step: its JSON schema, plus the events tool (from the cache when cached).- `allow_tools=False` is the forced final turn after the tool budget runs out — the model must answer from what it- has, so calling is suppressed: omit the tool inline, or disable function-calling on the cached tool.+ Normal turns offer the tool — from the cache when the video is cached (the tool lives there alongside it), or+ inline otherwise. The forced final turn (`allow_tools=False`, after the tool budget runs out) must answer from+ what it has, so no tool is offered. It never references the cache: Gemini rejects a `GenerateContent` request+ that sets `tools`, `tool_config`, or `system_instruction` alongside `cached_content`, so there's no way to+ disable the cached tool per-request. That turn always runs inline with the tool simply absent — the caller+ re-supplies the video + preamble inline for it (see `forced_prefix` in `_run_step`)."""kwargs: dict[str, Any] = {"response_mime_type": "application/json","response_json_schema": step.response_model.model_json_schema(),}+ if not allow_tools:+ return types.GenerateContentConfig(**kwargs) # inline, no tool to call — the model must answer nowif cache_name:kwargs["cached_content"] = cache_name # video, preamble, and the tool all live in the cache- if not allow_tools:- kwargs["tool_config"] = types.ToolConfig(- function_calling_config=types.FunctionCallingConfig(mode=types.FunctionCallingConfigMode.NONE)- )- elif allow_tools:+ else:kwargs["tools"] = [events_tool()]return types.GenerateContentConfig(**kwargs)diff --git a/products/replay_vision/backend/tests/test_call_scanner_provider.py b/products/replay_vision/backend/tests/test_call_scanner_provider.pyindex 33c845a15819..530da7ac33de 100644--- a/products/replay_vision/backend/tests/test_call_scanner_provider.py+++ b/products/replay_vision/backend/tests/test_call_scanner_provider.py@@ -136,6 +136,28 @@ async def test_tool_budget_exhaustion_forces_a_final_tool_free_answer() -> None:assert client.models.calls[-1]["config"].tools is None # tools removed on the forced turn+async def test_cached_tool_budget_exhaustion_forces_an_inline_tool_free_answer() -> None:+ # With the video cached, the forced final turn can't reuse the cache (Gemini rejects tools/tool_config alongside+ # cached_content). It must run inline with no tool and the video + preamble re-supplied — otherwise every+ # budget-exhausting cached scan hits a hard 400 and produces no observation.+ steps = [MissionStep(name="core", instruction="c", response_model=_Core)]+ responses = [_Resp(function_call=_fc("get_events_around", {"rec_t": 5})) for _ in range(7)]+ responses.append(_Resp(text='{"verdict":"yes"}'))+ client = _FakeClient(responses)+ out = await _run(client, steps, dispatch=lambda fc: {"events": []}, cache_name="caches/abc")+ assert out["core"].verdict == "yes"++ cached_turn, forced_turn = client.models.calls[0], client.models.calls[-1]+ assert cached_turn["config"].cached_content == "caches/abc" # normal turns still use the cache+ assert cached_turn["contents"][0] != _VIDEO # video lives in the cache, not inline++ assert forced_turn["config"].cached_content is None # forced turn drops the cache...+ assert forced_turn["config"].tools is None and forced_turn["config"].tool_config is None # ...and offers no tool+ assert forced_turn["contents"][0] == _VIDEO # video + preamble re-supplied inline so context isn't lost+ assert forced_turn["contents"][1].text == "PRE"++@pytest.mark.asyncioasync def test_step_survives_a_response_with_no_candidates() -> None:# Gemini can return zero candidates (safety filter / content policy); the step must fail cleanly rather than@@ -336,6 +358,18 @@ class TestStepConfig:assert config.cached_content == "caches/abc"assert config.response_json_schema is not None+ @pytest.mark.parametrize("cache_name", [None, "caches/abc"])+ def test_forced_turn_never_references_the_cache_or_sets_tool_config(self, cache_name: str | None) -> None:+ # Gemini rejects a request that sets tools, tool_config, or system_instruction alongside cached_content with+ # a hard 400. The forced final turn must run inline with the tool simply absent, even on a cached run.+ config = _step_config(+ MissionStep(name="core", instruction="c", response_model=_Core), cache_name=cache_name, allow_tools=False+ )+ assert config.tools is None+ assert config.tool_config is None+ assert config.cached_content is None+ assert config.response_json_schema is not None+@pytest.mark.asyncioasync def test_video_cache_creation_is_best_effort() -> None: