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(signals): cache the safety filter's system prompt (#101812)

Alex Lebedev4a3d34aed1c1
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index e56388215eab..db82be2f3a6d 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -1118,7 +1118,7 @@ Telemetry is best-effort; failures are logged, not raised.
## LLM Integration
-Most direct LLM calls use Anthropic via the shared `call_llm()` helper in `backend/temporal/llm.py`, with model selection driven by `SIGNAL_MATCHING_LLM_MODEL` (default: `claude-sonnet-5`). The emission stage (summarization, actionability) uses its own `SIGNAL_EMISSION_LLM_MODEL`, and the two safety stages use `SIGNAL_SAFETY_LLM_MODEL` (both default to `claude-sonnet-5`). `call_llm()` takes a `model` argument so a stage can pin its own model; the safety stages pass `SAFETY_MODEL` so a matching-model swap can never silently retune the security gate. Each model's request shape (assistant prefill, per-request temperature, extended thinking) is resolved from `MODEL_CAPABILITIES` in `backend/temporal/llm.py`, so swapping either default is a config change. Adaptive-thinking models run every call at `ADAPTIVE_MODEL_EFFORT` (`medium`), set through `effort_kwargs()` in the same module.
+Most direct LLM calls use Anthropic via the shared `call_llm()` helper in `backend/temporal/llm.py`, with model selection driven by `SIGNAL_MATCHING_LLM_MODEL` (default: `claude-sonnet-5`). The emission stage (summarization, actionability) uses its own `SIGNAL_EMISSION_LLM_MODEL`, and the two safety stages use `SIGNAL_SAFETY_LLM_MODEL` (both default to `claude-sonnet-5`). `call_llm()` takes a `model` argument so a stage can pin its own model; the safety stages pass `SAFETY_MODEL` so a matching-model swap can never silently retune the security gate. Each model's request shape (assistant prefill, per-request temperature, extended thinking) is resolved from `MODEL_CAPABILITIES` in `backend/temporal/llm.py`, so swapping either default is a config change. Adaptive-thinking models run every call at `ADAPTIVE_MODEL_EFFORT` (`medium`), set through `effort_kwargs()` in the same module. `call_llm()` also takes `cache_system_prompt`, which marks the system prompt as a prompt-cache prefix. The per-signal safety filter opts in because its prompt is above the model's cache minimum and runs continuously. No other stage opts in, for two different reasons: the report judge, matching and specificity prompts are static but sit below the minimum, so there is nothing to cache; query generation builds its prompt per team from the current signal type examples (`_build_query_generation_system_prompt()`), so the prefix changes between batches and a cache write would never be read.
That said, **not all “LLM-ish” behavior in Signals goes through `call_llm()` anymore**:
diff --git a/products/signals/backend/temporal/llm.py b/products/signals/backend/temporal/llm.py
index 8bb8627fd77f..704f118a5898 100644
--- a/products/signals/backend/temporal/llm.py
+++ b/products/signals/backend/temporal/llm.py
@@ -5,7 +5,7 @@ from typing import Final, Literal, Optional, TypedDict, TypeVar
from django.conf import settings
import structlog
-from anthropic.types import Message, MessageParam, OutputConfigParam
+from anthropic.types import Message, MessageParam, OutputConfigParam, TextBlockParam
from posthog.dataclasses import frozen
from posthog.helpers.tiktoken_encoding import TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model
@@ -147,6 +147,7 @@ async def call_llm(
stage: Optional[str] = None,
ai_product: Optional[str] = None,
model: Optional[str] = None,
+ cache_system_prompt: bool = False,
) -> T:
model = model or MATCHING_MODEL
# Native Anthropic Messages endpoint so prefilling and extended thinking carry over unchanged.
@@ -178,9 +179,16 @@ async def call_llm(
if prefill:
messages.append({"role": "assistant", "content": "{"})
+ # A cached system prompt is billed at about a tenth of the input price on every call after the
+ # first. Only a prompt above the model's cache minimum (1,024 tokens on Sonnet 5) and on a hot
+ # path pays for the cache write, so a call site opts in rather than every stage paying it.
+ system: str | list[TextBlockParam] = system_prompt
+ if cache_system_prompt:
+ system = [{"type": "text", "text": system_prompt, "cache_control": {"type": "ephemeral"}}]
+
create_kwargs: dict = {
"model": model,
- "system": system_prompt,
+ "system": system,
"messages": messages,
"max_tokens": MAX_RESPONSE_TOKENS,
"timeout": TIMEOUT,
diff --git a/products/signals/backend/temporal/safety_filter.py b/products/signals/backend/temporal/safety_filter.py
index a9ee8d6abb30..48835930e630 100644
--- a/products/signals/backend/temporal/safety_filter.py
+++ b/products/signals/backend/temporal/safety_filter.py
@@ -161,6 +161,7 @@ async def safety_filter(
stage="safety_filter",
ai_product="signals_safety",
model=SAFETY_MODEL,
+ cache_system_prompt=True,
)
except EmptyLLMResponseError:
return SafetyFilterJudgeResponse(
diff --git a/products/signals/backend/test/test_llm.py b/products/signals/backend/test/test_llm.py
index 553b1c6471fa..54925158a00b 100644
--- a/products/signals/backend/test/test_llm.py
+++ b/products/signals/backend/test/test_llm.py
@@ -86,6 +86,32 @@ async def test_without_ai_product_stays_on_python_gateway_even_with_env_set():
assert client.messages.create.call_args.kwargs["extra_headers"] == {"x-posthog-property-ai_stage": "match"}
+ "cache_system_prompt,expected_system",
+ [
+ (False, "s"),
+ (True, [{"type": "text", "text": "s", "cache_control": {"type": "ephemeral"}}]),
+ ],
+)
+async def test_cache_system_prompt_marks_the_system_block(
+ cache_system_prompt: bool, expected_system: str | list[dict[str, object]]
+) -> None:
+ client = _mock_anthropic_client()
+ with patch(f"{MODULE_PATH}.build_async_anthropic_client", return_value=client):
+ await call_llm(
+ team_id=1,
+ system_prompt="s",
+ user_prompt="u",
+ validate=lambda text: text,
+ stage="safety_filter",
+ ai_product="signals_safety",
+ cache_system_prompt=cache_system_prompt,
+ )
+
+ assert client.messages.create.call_args.kwargs["system"] == expected_system
+
+
@pytest.mark.asyncio
@override_settings(AI_GATEWAY_URL="https://ai-gateway.example/v1", AI_GATEWAY_API_KEY="phs_test")
async def test_non_message_response_raises_descriptive_error():
diff --git a/products/signals/backend/test/test_safety_filter.py b/products/signals/backend/test/test_safety_filter.py
index 5c59ce35fdaa..83c1f0fdcd31 100644
--- a/products/signals/backend/test/test_safety_filter.py
+++ b/products/signals/backend/test/test_safety_filter.py
@@ -29,6 +29,7 @@ async def test_safety_filter_wires_prompt_source_and_model(
) -> None:
# Guards the single prompt for every source, the source and date preamble, and SAFETY_MODEL wiring.
captured: dict[str, str] = {}
+ cache_flags: list[bool] = []
async def fake_call_llm(
*,
@@ -39,9 +40,11 @@ async def test_safety_filter_wires_prompt_source_and_model(
stage: str,
ai_product: str,
model: str,
+ cache_system_prompt: bool,
**_kwargs: object,
) -> SafetyFilterJudgeResponse:
captured.update(system_prompt=system_prompt, user_prompt=user_prompt, ai_product=ai_product, model=model)
+ cache_flags.append(cache_system_prompt)
return SafetyFilterJudgeResponse(safe=True)
with patch(f"{MODULE_PATH}.call_llm", new=fake_call_llm), time_machine.travel("2026-09-10", tick=False):
@@ -51,6 +54,7 @@ async def test_safety_filter_wires_prompt_source_and_model(
assert captured["system_prompt"] == SAFETY_FILTER_PROMPT
assert captured["model"] == SAFETY_MODEL
assert captured["ai_product"] == "signals_safety"
+ assert cache_flags == [True]
assert f"Source: {expected_source}" in captured["user_prompt"]
assert "Current date: 2026-09-10" in captured["user_prompt"]
assert "a finding" in captured["user_prompt"]