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(ai-gateway): select Jev models from managed prompts (#108646)

Paul D'Ambraa7037cb334f0
diff --git a/posthog/emoji_search/match.py b/posthog/emoji_search/match.py
index ffe91946f011..ad6f166548b2 100644
--- a/posthog/emoji_search/match.py
+++ b/posthog/emoji_search/match.py
@@ -10,10 +10,11 @@ from django.core.cache import cache
import structlog
from posthog.llm.gateway_client import team_distinct_id
+from posthog.llm.managed_decision_model import ManagedDecisionModel
from posthog.llm.system_one import ChoiceAnswer, ChoiceQuestion, SystemOneRequestFailed
from posthog.llm.system_one_client import GATEWAY_MAX_QUESTIONS, build_system_one_client
-MODEL = "posthog/hogference/jevk5-fp8-0.2"
+EMOJI_MODEL = ManagedDecisionModel("emoji-search-suggestions")
CACHE_SECONDS = 30 * 24 * 60 * 60
OPTIONS_PER_QUESTION = 15
logger = structlog.get_logger(__name__)
@@ -134,7 +135,9 @@ def suggest_emojis(query: str, *, team_id: int) -> EmojiSearchResult:
return EmojiSearchResult([])
catalog = load_catalog()
- cache_key = f"emoji_search:v4:{catalog.fingerprint}:{team_id}:{hashlib.sha256(query.encode()).hexdigest()}"
+ model = EMOJI_MODEL.current()
+ digest = hashlib.sha256(f"{model}\n{query}".encode()).hexdigest()
+ cache_key = f"emoji_search:v4:{catalog.fingerprint}:{team_id}:{digest}"
try:
cached = cache.get(cache_key)
except Exception:
@@ -149,7 +152,7 @@ def suggest_emojis(query: str, *, team_id: int) -> EmojiSearchResult:
pass
client = build_system_one_client(
- model=MODEL, ai_product="emoji_search", distinct_id=team_distinct_id(team_id), timeout=1.2
+ model=model, ai_product="emoji_search", distinct_id=team_distinct_id(team_id), timeout=1.2
)
state = {"emoji_search": query}
subgroup_result = client.decide(state=state, questions=build_subgroup_questions(catalog))
diff --git a/posthog/emoji_search/test_match.py b/posthog/emoji_search/test_match.py
index 65a824707377..7bfc28b7d580 100644
--- a/posthog/emoji_search/test_match.py
+++ b/posthog/emoji_search/test_match.py
@@ -29,6 +29,18 @@ def answer_questions(questions, selected):
class TestSuggestEmojis(SimpleTestCase):
+ @patch("posthog.emoji_search.match.build_system_one_client")
+ def test_model_change_recomputes_cached_suggestions(self, build_client) -> None:
+ cache.clear()
+ build_client.return_value.decide.side_effect = lambda *, state, questions: answer_questions(questions, ())
+ models = ["posthog/hogference/jevk5-fp8-0.2", "posthog/hogference/jeeves-0.1"]
+
+ with patch("posthog.emoji_search.match.EMOJI_MODEL.current", side_effect=models):
+ suggest_emojis("jurassic park", team_id=1)
+ suggest_emojis("jurassic park", team_id=1)
+
+ assert [call.kwargs["model"] for call in build_client.call_args_list] == models
+
@patch("posthog.emoji_search.match.build_system_one_client")
def test_failed_emoji_batch_keeps_successful_results_without_caching_them(self, build_client) -> None:
cache.clear()
diff --git a/posthog/llm/managed_decision_model.py b/posthog/llm/managed_decision_model.py
new file mode 100644
index 000000000000..2df48348eebb
--- /dev/null
+++ b/posthog/llm/managed_decision_model.py
@@ -0,0 +1,96 @@
+import time
+import functools
+import threading
+from collections.abc import Callable
+from concurrent.futures import ThreadPoolExecutor
+from typing import Any
+
+import structlog
+import posthoganalytics
+from posthoganalytics.ai.prompts import PromptResult, Prompts
+
+DEFAULT_DECISION_MODEL = "posthog/hogference/jevk5-fp8-0.2"
+PROMPT_LABEL = "production"
+PROMPT_REFRESH_SECONDS = 60
+
+logger = structlog.get_logger(__name__)
+
+
+def app_prompts() -> Prompts:
+ # PostHog's own prompts live in the US project, and EU has no copy of that project, so every region
+ # reads them through the SDK. One client per process keeps the last good copy when a fetch fails.
+ # It is built on first use, because apps.ready() sets the key after this module can be imported.
+ # A zero TTL leaves the refresh interval to BackgroundRefresher alone.
+ return Prompts(posthoganalytics, capture_errors=True, default_cache_ttl_seconds=0)
+
+
+def get_app_prompt(prompt_name: str, *, version: int | None = None) -> PromptResult | None:
+ """The `production` version, or `version` when given. None without a personal API key."""
+ # Without a key (tests, local dev, self-hosted) the SDK still sends the request and gets a 401.
+ if not posthoganalytics.personal_api_key:
+ if version is not None:
+ raise RuntimeError(f"Reading {prompt_name} version {version} needs POSTHOG_PERSONAL_API_KEY")
+ return None
+ label = PROMPT_LABEL if version is None else None
+ return app_prompts().get(prompt_name, with_metadata=True, label=label, version=version)
+
+
+class BackgroundRefresher[T]:
+ # The SDK fetch blocks for up to 10 s on a cache miss and the pickers' budget is 2 s, so a request
+ # reads the last value it has and at most one background fetch replaces it.
+ def __init__(self, prompt_name: str, initial: T, fetch: Callable[[], T]) -> None:
+ self._prompt_name = prompt_name
+ self._fetch = fetch
+ self._value = initial
+ self._lock = threading.Lock()
+ self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix=f"refresh-{prompt_name}")
+ self._refreshed_at = float("-inf")
+ self._refreshing = False
+
+ def current(self) -> T:
+ with self._lock:
+ if not self._refreshing and time.monotonic() - self._refreshed_at >= PROMPT_REFRESH_SECONDS:
+ self._refreshing = True
+ self._executor.submit(self._refresh)
+ return self._value
+
+ def _refresh(self) -> None:
+ value: T | None = None
+ try:
+ value = self._fetch()
+ except Exception:
+ logger.exception("managed_prompt_refresh_failed", prompt_name=self._prompt_name)
+ with self._lock:
+ if value is not None:
+ self._value = value
+ self._refreshed_at = time.monotonic()
+ self._refreshing = False
+
+
+def model_from_config(config: Any, fallback: str = DEFAULT_DECISION_MODEL) -> str:
+ model = config.get("model") if isinstance(config, dict) else None
+ if isinstance(model, str) and 0 < len(model) <= 255 and not any(character.isspace() for character in model):
+ return model
+ return fallback
+
+
+class ManagedDecisionModel:
+ def __init__(self, prompt_name: str, fallback: str = DEFAULT_DECISION_MODEL) -> None:
+ self.prompt_name = prompt_name
+ self.fallback = fallback
+ self._refresher = BackgroundRefresher(prompt_name, fallback, self.fetch)
+
+ def current(self) -> str:
+ return self._refresher.current()
+
+ def fetch(self, *, version: int | None = None) -> str:
+ result = get_app_prompt(self.prompt_name, version=version)
+ if result is None:
+ return self.fallback
+ config = result.config
+ model = model_from_config(config, self.fallback)
+ configured = config.get("model") if isinstance(config, dict) else None
+ if configured is not None and model == self.fallback and configured != self.fallback:
+ logger.warning("managed_decision_model_invalid", prompt_name=self.prompt_name)
+ return model
diff --git a/posthog/llm/test_managed_decision_model.py b/posthog/llm/test_managed_decision_model.py
new file mode 100644
index 000000000000..2b18ea32f045
--- /dev/null
+++ b/posthog/llm/test_managed_decision_model.py
@@ -0,0 +1,115 @@
+import threading
+from concurrent.futures import Future
+
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from posthoganalytics.ai.prompts import PromptResult
+
+from posthog.llm import managed_decision_model
+from posthog.llm.managed_decision_model import (
+ DEFAULT_DECISION_MODEL,
+ BackgroundRefresher,
+ ManagedDecisionModel,
+ model_from_config,
+)
+
+NEW_MODEL = "posthog/hogference/jeeves-0.1"
+
+
+def managed_result(model: str = NEW_MODEL) -> PromptResult:
+ return PromptResult(
+ source="api", prompt="Emoji search", name="emoji-search-suggestions", version=3, config={"model": model}
+ )
+
+
+class TestBackgroundRefresher(SimpleTestCase):
+ def test_a_request_never_waits_for_the_fetch(self) -> None:
+ release = threading.Event()
+ fetches: list[Future] = []
+
+ def slow_fetch() -> str:
+ assert release.wait(timeout=5)
+ return "managed"
+
+ refresher = BackgroundRefresher("test-prompt", "bundled", slow_fetch)
+ submit = refresher._executor.submit
+ with patch.object(refresher._executor, "submit", side_effect=lambda fn: fetches.append(submit(fn))):
+ assert refresher.current() == "bundled"
+ assert refresher.current() == "bundled"
+ release.set()
+ fetches[0].result(timeout=5)
+
+ assert refresher.current() == "managed"
+ assert len(fetches) == 1
+
+ @parameterized.expand(
+ [
+ ("first_fetch_fails", [ConnectionError("unavailable")], "bundled"),
+ ("later_fetch_fails", ["managed", ConnectionError("unavailable")], "managed"),
+ ]
+ )
+ def test_a_failed_fetch_keeps_the_last_value(self, _name: str, fetches: list, expected: str) -> None:
+ results = iter(fetches)
+
+ def fetch() -> str:
+ result = next(results)
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ refresher = BackgroundRefresher("test-prompt", "bundled", fetch)
+ for _ in fetches:
+ refresher._refresh()
+
+ assert refresher.current() == expected
+
+
+class TestManagedDecisionModel(SimpleTestCase):
+ def setUp(self) -> None:
+ managed_decision_model.app_prompts.cache_clear()
+ self.addCleanup(managed_decision_model.app_prompts.cache_clear)
+
+ @parameterized.expand(
+ [
+ ("valid", {"model": NEW_MODEL}, NEW_MODEL),
+ ("missing", {}, DEFAULT_DECISION_MODEL),
+ ("wrong_type", {"model": 1}, DEFAULT_DECISION_MODEL),
+ ("empty", {"model": ""}, DEFAULT_DECISION_MODEL),
+ ("whitespace", {"model": "model\nother"}, DEFAULT_DECISION_MODEL),
+ ]
+ )
+ def test_model_config(self, _name: str, config: dict, expected: str) -> None:
+ assert model_from_config(config) == expected
+
+ @patch("posthog.llm.managed_decision_model.posthoganalytics.personal_api_key", "phx_test")
+ @patch("posthog.llm.managed_decision_model.Prompts")
+ def test_every_refresh_reads_the_posthog_project_through_one_sdk_client(self, prompts_class) -> None:
+ prompts_class.return_value.get.return_value = managed_result()
+ managed = ManagedDecisionModel("emoji-search-suggestions")
+
+ managed._refresher._refresh()
+ managed._refresher._refresh()
+ assert managed.fetch(version=3) == NEW_MODEL
+
+ assert managed.current() == NEW_MODEL
+ prompts_class.assert_called_once_with(
+ managed_decision_model.posthoganalytics, capture_errors=True, default_cache_ttl_seconds=0
+ )
+ get = prompts_class.return_value.get
+ get.assert_any_call("emoji-search-suggestions", with_metadata=True, label="production", version=None)
+ get.assert_any_call("emoji-search-suggestions", with_metadata=True, label=None, version=3)
+
+ @patch("posthog.llm.managed_decision_model.posthoganalytics.personal_api_key", None)
+ @patch("posthog.llm.managed_decision_model.Prompts")
+ def test_without_a_personal_key_the_bundled_model_stays(self, prompts_class) -> None:
+ managed = ManagedDecisionModel("emoji-search-suggestions")
+
+ managed._refresher._refresh()
+
+ assert managed.current() == DEFAULT_DECISION_MODEL
+ with self.assertRaisesRegex(RuntimeError, "version 3 needs POSTHOG_PERSONAL_API_KEY"):
+ managed.fetch(version=3)
+ prompts_class.assert_not_called()
diff --git a/posthog/taxonomic_search_intent/classify.py b/posthog/taxonomic_search_intent/classify.py
index 17caac02fd4c..1bcc564d70e4 100644
--- a/posthog/taxonomic_search_intent/classify.py
+++ b/posthog/taxonomic_search_intent/classify.py
@@ -28,7 +28,6 @@ from .prompt import SearchIntentPrompt, current_search_intent_prompt
logger = structlog.get_logger(__name__)
SEARCH_INTENT_FEATURE_FLAG = "taxonomic-filter-search-intent"
-SEARCH_INTENT_MODEL = "posthog/hogference/jevk5-fp8-0.2"
MIN_QUERY_CHARS = 2
MAX_QUERY_CHARS = 64
# The picker waits for no answer, so a late answer is worth nothing and a short timeout frees the worker.
@@ -237,9 +236,7 @@ def _classify(request: SearchIntentRequest, prompt: SearchIntentPrompt, *, use_c
return _skipped()
state = search_intent_state(model_query, request.active_group_type, request.scene)
- key = _cache_key(
- request.team_id, SEARCH_INTENT_MODEL, state, prompt.instructions, options, prompt.confident_threshold
- )
+ key = _cache_key(request.team_id, prompt.model, state, prompt.instructions, options, prompt.confident_threshold)
if use_cache:
cached = _cached_intent(key)
if cached is not None:
@@ -247,7 +244,7 @@ def _classify(request: SearchIntentRequest, prompt: SearchIntentPrompt, *, use_c
# No TypeSafe fallback: a search is customer text, and TypeSafe is a third party.
client = build_system_one_client(
- model=SEARCH_INTENT_MODEL,
+ model=prompt.model,
ai_product="taxonomic_filter",
distinct_id=team_distinct_id(request.team_id),
timeout=SEARCH_INTENT_TIMEOUT_SECONDS,
diff --git a/posthog/taxonomic_search_intent/event_match.py b/posthog/taxonomic_search_intent/event_match.py
index 4982acf939d3..c3805ea6c643 100644
--- a/posthog/taxonomic_search_intent/event_match.py
+++ b/posthog/taxonomic_search_intent/event_match.py
@@ -19,19 +19,13 @@ from pydantic import TypeAdapter, ValidationError
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.llm.gateway_client import team_distinct_id
+from posthog.llm.managed_decision_model import ManagedDecisionModel
from posthog.llm.system_one import NoulAnswer, NoulQuestion, SystemOneRequestFailed, SystemOneResult
from posthog.llm.system_one_client import GATEWAY_MAX_QUESTIONS, SystemOneClient, build_system_one_client
from posthog.models import EventDefinition
from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP
-from .classify import (
- CACHE_TTL_SECONDS,
- MAX_QUERY_CHARS,
- MIN_QUERY_CHARS,
- SEARCH_INTENT_MODEL,
- SEARCH_INTENT_TIMEOUT_SECONDS,
- redact_values,
-)
+from .classify import CACHE_TTL_SECONDS, MAX_QUERY_CHARS, MIN_QUERY_CHARS, SEARCH_INTENT_TIMEOUT_SECONDS, redact_values
from .contracts import EventMatch, EventMatchRequest
logger = structlog.get_logger(__name__)
@@ -42,6 +36,7 @@ MATCH_THRESHOLD = 0.7
# The picker shows at most this many, after it removes the events it excludes, so the endpoint returns them all.
MAX_MATCHES = 3
CACHE_KEY_PREFIX = "taxonomic_search_intent:event_match:v1"
+EVENT_MATCH_MODEL = ManagedDecisionModel("taxonomic-filter-event-match")
_CACHED_MATCHES = TypeAdapter(list[EventMatch])
@@ -116,13 +111,13 @@ def _ask_chunk(client: SystemOneClient, state: str, names: Sequence[str], team_i
return None
-def _probabilities(team_id: int, query: str) -> _ModelAnswers:
+def _probabilities(team_id: int, query: str, model: str) -> _ModelAnswers:
"""The model's probability for every core event it answered. Raises the System One errors when no request succeeds."""
names = list(CORE_EVENT_CANDIDATES)
# The gateway takes a bounded number of questions per request, so the candidates go out in parallel chunks.
chunks = [names[start : start + GATEWAY_MAX_QUESTIONS] for start in range(0, len(names), GATEWAY_MAX_QUESTIONS)]
client = build_system_one_client(
- model=SEARCH_INTENT_MODEL,
+ model=model,
ai_product="taxonomic_filter",
distinct_id=team_distinct_id(team_id),
timeout=SEARCH_INTENT_TIMEOUT_SECONDS,
@@ -148,14 +143,14 @@ def _probabilities(team_id: int, query: str) -> _ModelAnswers:
return _ModelAnswers(probabilities=probabilities, complete=None not in results)
-def _cache_key(team_id: int, query: str) -> str:
+def _cache_key(team_id: int, query: str, model: str) -> str:
# Keyed per team, so a fast answer cannot tell one team what another team searched.
- digest = hashlib.sha256(f"{SEARCH_INTENT_MODEL}\n{MATCH_THRESHOLD}\n{query}".encode()).hexdigest()
+ digest = hashlib.sha256(f"{model}\n{MATCH_THRESHOLD}\n{query}".encode()).hexdigest()
return f"{CACHE_KEY_PREFIX}:{_CANDIDATES_DIGEST}:{team_id}:{digest}"
def likely_core_events(
- team_id: int, query: str, *, use_cache: bool = True, require_complete: bool = False
+ team_id: int, query: str, *, use_cache: bool = True, require_complete: bool = False, model: str | None = None
) -> list[EventMatch]:
"""Every core event the model finds likely, strongest first, before the check against ingested events.
@@ -165,7 +160,8 @@ def likely_core_events(
model_query = redact_values(query)
if model_query is None:
return []
- key = _cache_key(team_id, model_query)
+ model = model or EVENT_MATCH_MODEL.current()
+ key = _cache_key(team_id, model_query, model)
if use_cache:
cached = cache.get(key)
# The Django cache pickles what it stores, so matches go in as JSON text and come out schema-validated.
@@ -174,7 +170,7 @@ def likely_core_events(
return _CACHED_MATCHES.validate_json(cached)
except ValidationError:
pass
- answers = _probabilities(team_id, model_query)
+ answers = _probabilities(team_id, model_query, model)
if require_complete and not answers.complete:
raise SystemOneRequestFailed("Some event match requests failed")
likely = sorted(
diff --git a/posthog/taxonomic_search_intent/prompt.py b/posthog/taxonomic_search_intent/prompt.py
index 7bd40820b538..6fc0ec5708d5 100644
--- a/posthog/taxonomic_search_intent/prompt.py
+++ b/posthog/taxonomic_search_intent/prompt.py
@@ -1,31 +1,31 @@
"""
-The question and the tab meanings the decision model reads for a filter picker search.
+The question, tab meanings, and model for a filter picker search.
They live in PostHog's own prompt management, as `taxonomic-filter-search-intent` in the PostHog project,
so a new wording ships by moving the `production` label and not by a deploy. The prompt text is the
-question. Its config holds the tab meanings as `options` and the `confident_threshold`. The bundled
+question. Its config holds the tab meanings as `options`, the `confident_threshold`, and `model`. The bundled
copy below is the fallback when the managed prompt is unreachable or malformed; keep it close to the
`production` version so a fallback answer reads the same.
"""
-import time
-import threading
from collections.abc import Mapping
-from concurrent.futures import ThreadPoolExecutor
from typing import Any
import structlog
-import posthoganalytics
-from posthoganalytics.ai.prompts import PromptResult, Prompts
+from posthoganalytics.ai.prompts import PromptResult
from posthog.dataclasses import frozen
+from posthog.llm.managed_decision_model import (
+ DEFAULT_DECISION_MODEL,
+ BackgroundRefresher,
+ get_app_prompt,
+ model_from_config,
+)
from posthog.llm.system_one_client import GATEWAY_MAX_CHOICE_OPTIONS
logger = structlog.get_logger(__name__)
SEARCH_INTENT_PROMPT_NAME = "taxonomic-filter-search-intent"
-SEARCH_INTENT_PROMPT_LABEL = "production"
-PROMPT_REFRESH_SECONDS = 60
@frozen
@@ -35,6 +35,7 @@ class SearchIntentPrompt:
confident_threshold: float
# None for the bundled copy, so analysis can tell a fallback answer from a managed one.
version: int | None
+ model: str = DEFAULT_DECISION_MODEL
BUNDLED_SEARCH_INTENT_PROMPT = SearchIntentPrompt(
@@ -100,57 +101,19 @@ def parse_search_intent_prompt(result: PromptResult) -> SearchIntentPrompt:
options=options if options is not None else bundled.options,
confident_threshold=threshold if threshold is not None else bundled.confident_threshold,
version=result.version,
+ model=model_from_config(config),
)
-def fetch_search_intent_prompt(*, label: str | None = None, version: int | None = None) -> SearchIntentPrompt:
+def fetch_search_intent_prompt(*, version: int | None = None) -> SearchIntentPrompt:
"""Blocks on the network for up to the SDK timeout. Request code reads `current_search_intent_prompt` instead."""
- # Without a key (tests, local dev, self-hosted) the SDK still sends the request and gets a 401.
- if not posthoganalytics.personal_api_key:
+ result = get_app_prompt(SEARCH_INTENT_PROMPT_NAME, version=version)
+ if result is None:
return BUNDLED_SEARCH_INTENT_PROMPT
- # Built per fetch because the key is set in apps.ready(), after this module can be imported.
- prompts = Prompts(posthoganalytics, capture_errors=True)
- result = prompts.get(
- SEARCH_INTENT_PROMPT_NAME,
- with_metadata=True,
- label=label if version is None else None,
- version=version,
- fallback=BUNDLED_SEARCH_INTENT_PROMPT.instructions,
- )
return parse_search_intent_prompt(result)
-class _PromptRefresher:
- # The SDK fetch blocks for up to 10 s on a cache miss and the picker's budget is 2 s, so a request
- # reads the last prompt it has and at most one background fetch replaces it.
- def __init__(self) -> None:
- self._lock = threading.Lock()
- self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="search-intent-prompt")
- self._prompt = BUNDLED_SEARCH_INTENT_PROMPT
- self._refreshed_at = float("-inf")
- self._refreshing = False
-
- def current(self) -> SearchIntentPrompt:
- with self._lock:
- if not self._refreshing and time.monotonic() - self._refreshed_at >= PROMPT_REFRESH_SECONDS:
- self._refreshing = True
- self._executor.submit(self._refresh)
- return self._prompt
-
- def _refresh(self) -> None:
- try:
- prompt = fetch_search_intent_prompt(label=SEARCH_INTENT_PROMPT_LABEL)
- except Exception:
- logger.exception("taxonomic_search_intent_prompt_refresh_failed")
- prompt = None
- with self._lock:
- if prompt is not None and (prompt.version is not None or self._prompt.version is None):
- self._prompt = prompt
- self._refreshed_at = time.monotonic()
- self._refreshing = False
-
-
-_REFRESHER = _PromptRefresher()
+_REFRESHER = BackgroundRefresher(SEARCH_INTENT_PROMPT_NAME, BUNDLED_SEARCH_INTENT_PROMPT, fetch_search_intent_prompt)
def current_search_intent_prompt() -> SearchIntentPrompt:
diff --git a/posthog/taxonomic_search_intent/test_classify.py b/posthog/taxonomic_search_intent/test_classify.py
index 0d7a38f8a3a5..a54f8fd6138a 100644
--- a/posthog/taxonomic_search_intent/test_classify.py
+++ b/posthog/taxonomic_search_intent/test_classify.py
@@ -1,6 +1,4 @@
-import threading
import dataclasses
-from concurrent.futures import Future
from unittest.mock import patch
@@ -16,7 +14,7 @@ from posthog.taxonomic_search_intent.contracts import SearchIntent, SearchIntent
from posthog.taxonomic_search_intent.prompt import (
BUNDLED_SEARCH_INTENT_PROMPT,
SearchIntentPrompt,
- _PromptRefresher,
+ fetch_search_intent_prompt,
parse_search_intent_prompt,
)
@@ -49,6 +47,7 @@ class TestClassifySearchIntent(SimpleTestCase):
build = patch(BUILD_CLIENT).start()
patch(CURRENT_PROMPT, return_value=BUNDLED_SEARCH_INTENT_PROMPT).start()
self.addCleanup(patch.stopall)
+ self.build = build
self.decide = build.return_value.decide
@parameterized.expand(
@@ -180,6 +179,16 @@ class TestClassifySearchIntent(SimpleTestCase):
question = self.decide.call_args.kwargs["questions"]["tab"]
assert (question.instructions, question.criteria) == ("Which tab?", prompt.options)
+ def test_managed_model_is_sent_to_the_gateway_and_separates_cached_answers(self) -> None:
+ self.decide.return_value = _answer("events", 0.9)
+ managed = dataclasses.replace(BUNDLED_SEARCH_INTENT_PROMPT, model="posthog/hogference/jeeves-0.1")
+
+ classify_search_intent(_search("checkout"), prompt=BUNDLED_SEARCH_INTENT_PROMPT)
+ classify_search_intent(_search("checkout"), prompt=managed)
+
+ assert self.decide.call_count == 2
+ assert self.build.call_args.kwargs["model"] == managed.model
+
@parameterized.expand(
[
("same_team_and_prompt", 7, BUNDLED_SEARCH_INTENT_PROMPT, 1),
@@ -249,30 +258,34 @@ class TestSearchIntentPrompt(SimpleTestCase):
instructions="Which tab?", options=options, confident_threshold=threshold, version=4
)
- def test_the_sdk_fallback_is_the_bundled_prompt(self) -> None:
+ def test_the_code_fallback_is_the_bundled_prompt(self) -> None:
result = PromptResult(source="code_fallback", prompt=BUNDLED_SEARCH_INTENT_PROMPT.instructions)
assert parse_search_intent_prompt(result) is BUNDLED_SEARCH_INTENT_PROMPT
- def test_a_request_never_waits_for_the_prompt_fetch(self) -> None:
- managed = dataclasses.replace(BUNDLED_SEARCH_INTENT_PROMPT, instructions="Which tab?", version=3)
- release = threading.Event()
- fetches: list[Future] = []
-
- def slow_fetch(**_kwargs: object) -> SearchIntentPrompt:
- assert release.wait(timeout=5)
- return managed
-
- refresher = _PromptRefresher()
- submit = refresher._executor.submit
- with (
- patch("posthog.taxonomic_search_intent.prompt.fetch_search_intent_prompt", slow_fetch),
- patch.object(refresher._executor, "submit", side_effect=lambda fn: fetches.append(submit(fn))),
- ):
- assert refresher.current() is BUNDLED_SEARCH_INTENT_PROMPT
- assert refresher.current() is BUNDLED_SEARCH_INTENT_PROMPT
- release.set()
- fetches[0].result(timeout=5)
-
- assert refresher.current() == managed
- assert len(fetches) == 1
+ def test_model_config_uses_the_managed_model(self) -> None:
+ model = "posthog/hogference/jeeves-0.1"
+ result = PromptResult(source="api", prompt="Which tab?", name="n", version=4, config={"model": model})
+
+ assert parse_search_intent_prompt(result).model == model
+
+ @patch("posthog.taxonomic_search_intent.prompt.get_app_prompt")
+ def test_fetch_reads_the_managed_prompt(self, read_prompt) -> None:
+ read_prompt.return_value = PromptResult(
+ source="api",
+ prompt="Which tab?",
+ name="taxonomic-filter-search-intent",
+ version=3,
+ config={"model": "posthog/hogference/jeeves-0.1"},
+ )
+
+ prompt = fetch_search_intent_prompt()
+ assert prompt.version == 3
+ assert prompt.model == "posthog/hogference/jeeves-0.1"
+ read_prompt.assert_called_with("taxonomic-filter-search-intent", version=None)
+
+ fetch_search_intent_prompt(version=4)
+ read_prompt.assert_called_with("taxonomic-filter-search-intent", version=4)
+
+ read_prompt.return_value = None
+ assert fetch_search_intent_prompt() is BUNDLED_SEARCH_INTENT_PROMPT
diff --git a/posthog/taxonomic_search_intent/test_event_match.py b/posthog/taxonomic_search_intent/test_event_match.py
index ed69c9530010..d7f279ac5901 100644
--- a/posthog/taxonomic_search_intent/test_event_match.py
+++ b/posthog/taxonomic_search_intent/test_event_match.py
@@ -94,6 +94,19 @@ class TestMatchCoreEvents(BaseTest):
assert sum(asked) == len(CORE_EVENT_CANDIDATES)
assert "Search: browser capture" in client.decide.call_args.kwargs["state"]
+ def test_model_change_recomputes_cached_matches(self) -> None:
+ client = _model_that_believes({"Autocapture": 0.95})
+ models = ["posthog/hogference/jevk5-fp8-0.2", "posthog/hogference/jeeves-0.1"]
+ with (
+ patch(BUILD_CLIENT, return_value=client) as build,
+ patch("posthog.taxonomic_search_intent.event_match.EVENT_MATCH_MODEL.current", side_effect=models),
+ ):
+ match_core_events(self._search("browser capture"))
+ match_core_events(self._search("browser capture"))
+
+ assert build.call_count == 2
+ assert [call.kwargs["model"] for call in build.call_args_list] == models
+
def test_suggests_the_likely_ingested_events_strongest_first(self) -> None:
client = _model_that_believes(
{
diff --git a/products/posthog_ai/evals/taxonomic_filter/eval_event_match.py b/products/posthog_ai/evals/taxonomic_filter/eval_event_match.py
index 254adf90dac3..493605b721a5 100644
--- a/products/posthog_ai/evals/taxonomic_filter/eval_event_match.py
+++ b/products/posthog_ai/evals/taxonomic_filter/eval_event_match.py
@@ -19,16 +19,18 @@ do not change the result. It shows at most `MAX_MATCHES` events, like the picker
No CI job runs this suite. Run it by hand, with AI_GATEWAY_URL and AI_GATEWAY_API_KEY set for the decision
model, and with the harness's own BRAINTRUST_API_KEY and LLM_GATEWAY_ANTHROPIC_API_KEY:
hogli evals eval_event_match
+Set EVENT_MATCH_PROMPT_VERSION to score an unpublished prompt version before moving its production label.
+Fetching a version needs POSTHOG_PERSONAL_API_KEY with read access to the PostHog project, and the suite fails without it.
"""
from __future__ import annotations
+import os
import time
import asyncio
from posthog.llm.system_one_client import system_one_configured
-from posthog.taxonomic_search_intent.classify import SEARCH_INTENT_MODEL
-from posthog.taxonomic_search_intent.event_match import MAX_MATCHES, likely_core_events
+from posthog.taxonomic_search_intent.event_match import EVENT_MATCH_MODEL, MAX_MATCHES, likely_core_events
from products.posthog_ai.eval_harness.config import BaseEvalCase
from products.posthog_ai.eval_harness.harness.context import EvalContext
@@ -70,6 +72,8 @@ async def eval_event_match(ctx: EvalContext) -> None:
raise RuntimeError(
"eval_event_match needs AI_GATEWAY_URL (https) and AI_GATEWAY_API_KEY to reach the decision model"
)
+ version = os.environ.get("EVENT_MATCH_PROMPT_VERSION")
+ model = await asyncio.to_thread(EVENT_MATCH_MODEL.fetch, version=int(version) if version else None)
async def task(case: BaseEvalCase, task_ctx: EvalContext) -> dict:
if task_ctx.demo_data is None:
@@ -84,12 +88,13 @@ async def eval_event_match(ctx: EvalContext) -> None:
case.prompt,
use_cache=False,
require_complete=True,
+ model=model,
)
except Exception as error:
- return {"model": SEARCH_INTENT_MODEL, "suggested": [], "error": f"{type(error).__name__}: {error}"}
+ return {"model": model, "suggested": [], "error": f"{type(error).__name__}: {error}"}
suggested = [match.name for match in likely[:MAX_MATCHES]]
return {
- "model": SEARCH_INTENT_MODEL,
+ "model": model,
"suggested": suggested,
"probabilities": {match.name: match.probability for match in likely[:MAX_MATCHES]},
"latency_ms": round((time.monotonic() - started) * 1000),
diff --git a/products/posthog_ai/evals/taxonomic_filter/eval_search_intent.py b/products/posthog_ai/evals/taxonomic_filter/eval_search_intent.py
index 68143a7b3003..9f78585527d6 100644
--- a/products/posthog_ai/evals/taxonomic_filter/eval_search_intent.py
+++ b/products/posthog_ai/evals/taxonomic_filter/eval_search_intent.py
@@ -27,7 +27,7 @@ decision model, and with the harness's own BRAINTRUST_API_KEY and LLM_GATEWAY_AN
It scores the `production` version of the managed prompt. Set SEARCH_INTENT_PROMPT_VERSION to score
another version. Fetching it needs POSTHOG_PERSONAL_API_KEY with read access to the PostHog project;
-without it the suite scores the bundled copy, and the output reports `prompt_version: None`.
+without it the production run scores the bundled copy, while an explicit version fails clearly.
"""
from __future__ import annotations
@@ -38,9 +38,9 @@ import asyncio
import dataclasses
from posthog.llm.system_one_client import system_one_configured
-from posthog.taxonomic_search_intent.classify import SEARCH_INTENT_MODEL, classify_search_intent
+from posthog.taxonomic_search_intent.classify import classify_search_intent
from posthog.taxonomic_search_intent.contracts import SearchIntentRequest
-from posthog.taxonomic_search_intent.prompt import SEARCH_INTENT_PROMPT_LABEL, fetch_search_intent_prompt
+from posthog.taxonomic_search_intent.prompt import fetch_search_intent_prompt
from products.posthog_ai.eval_harness.config import BaseEvalCase
from products.posthog_ai.eval_harness.harness.context import EvalContext
@@ -323,11 +323,7 @@ async def eval_search_intent(ctx: EvalContext) -> None:
"eval_search_intent needs AI_GATEWAY_URL (https) and AI_GATEWAY_API_KEY to reach the decision model"
)
version = os.environ.get("SEARCH_INTENT_PROMPT_VERSION")
- prompt = await asyncio.to_thread(
- fetch_search_intent_prompt,
- label=None if version else SEARCH_INTENT_PROMPT_LABEL,
- version=int(version) if version else None,
- )
+ prompt = await asyncio.to_thread(fetch_search_intent_prompt, version=int(version) if version else None)
async def task(case: BaseEvalCase, task_ctx: EvalContext) -> dict:
if task_ctx.demo_data is None:
@@ -345,14 +341,14 @@ async def eval_search_intent(ctx: EvalContext) -> None:
intent = await asyncio.to_thread(classify_search_intent, request, use_cache=False, prompt=prompt)
except Exception as error:
return {
- "model": SEARCH_INTENT_MODEL,
+ "model": prompt.model,
"prompt_version": prompt.version,
"intent": None,
"error": f"{type(error).__name__}: {error}",
}
answer = dataclasses.asdict(intent)
return {
- "model": SEARCH_INTENT_MODEL,
+ "model": prompt.model,
"prompt_version": prompt.version,
"intent": answer,
"latency_ms": round((time.monotonic() - started) * 1000),