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(signals): Lazy-load tiktoken encoding to avoid import-time crash (#58641)

Michael Matloka99a51243786d
diff --git a/ee/hogai/llm_traces_summaries/tools/stringify_trace.py b/ee/hogai/llm_traces_summaries/tools/stringify_trace.py
index e5edd545069f..31d74b13f1b6 100644
--- a/ee/hogai/llm_traces_summaries/tools/stringify_trace.py
+++ b/ee/hogai/llm_traces_summaries/tools/stringify_trace.py
@@ -1,10 +1,10 @@
from typing import Any
-import tiktoken
import structlog
from posthog.schema import LLMTrace
+from posthog.helpers.tiktoken_encoding import LLM_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model
from posthog.models.team.team import Team
logger = structlog.get_logger(__name__)
@@ -13,7 +13,7 @@ logger = structlog.get_logger(__name__)
class LLMTracesSummarizerStringifier:
def __init__(self, team: Team):
self._team = team
- self._token_encoder = tiktoken.encoding_for_model("gpt-4o")
+ self._token_encoder = get_tiktoken_encoding_for_model(LLM_TOKEN_COUNT_PROXY_MODEL)
self._stringified_trace_max_tokens = 5000
def stringify_traces(self, traces_chunk: list[LLMTrace]) -> dict[str, str]:
diff --git a/ee/hogai/session_summaries/utils.py b/ee/hogai/session_summaries/utils.py
index be232de1b068..94b094fd3219 100644
--- a/ee/hogai/session_summaries/utils.py
+++ b/ee/hogai/session_summaries/utils.py
@@ -4,10 +4,11 @@ from urllib.parse import urlparse
from django.template import Context, Engine
-import tiktoken
import structlog
from tiktoken.model import MODEL_TO_ENCODING
+from posthog.helpers.tiktoken_encoding import LLM_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model
+
from ee.hogai.session_summaries.constants import MAX_SESSION_IDS_COMBINED_LOGGING_LENGTH
logger = structlog.get_logger(__name__)
@@ -154,9 +155,9 @@ def estimate_tokens_from_strings(strings: list[str], model: str) -> int:
if not strings:
return 0
if model not in MODEL_TO_ENCODING:
- # If the model aren't supported yet - default to o3 as it should be similar to other thinking models
- model = "o3"
- encoding = tiktoken.encoding_for_model(model)
+ # Unknown model name: use the standard LLM token counter (o200k / gpt-4o family).
+ model = LLM_TOKEN_COUNT_PROXY_MODEL
+ encoding = get_tiktoken_encoding_for_model(model)
total_tokens = 0
for string in strings:
if string:
diff --git a/posthog/demo/matrix/matrix.py b/posthog/demo/matrix/matrix.py
index 49462dac4c0b..5e39d28bb5e6 100644
--- a/posthog/demo/matrix/matrix.py
+++ b/posthog/demo/matrix/matrix.py
@@ -13,6 +13,7 @@ import mimesis.random
from posthog.constants import GROUP_TYPES_LIMIT
from posthog.demo.matrix.randomization import PropertiesProvider
+from posthog.helpers.tiktoken_encoding import LLM_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model
from posthog.models import Team, User
from posthog.models.feature_flag.feature_flag import FeatureFlag
from posthog.models.utils import UUIDT, uuid7
@@ -256,7 +257,7 @@ class Matrix(ABC):
self.distinct_id_to_person = {}
self.clusters = [self.CLUSTER_CLASS(index=i, matrix=self) for i in range(n_clusters)]
self.server_client = SimServerClient(self)
- self.gpt_4o_encoding = tiktoken.encoding_for_model("gpt-4o")
+ self.gpt_4o_encoding = get_tiktoken_encoding_for_model(LLM_TOKEN_COUNT_PROXY_MODEL)
self.is_complete = None
@property
diff --git a/posthog/helpers/tiktoken_encoding.py b/posthog/helpers/tiktoken_encoding.py
new file mode 100644
index 000000000000..4bb7d7e9b1fd
--- /dev/null
+++ b/posthog/helpers/tiktoken_encoding.py
@@ -0,0 +1,27 @@
+"""Lazy cached access to tiktoken encodings.
+
+Tiktoken may download and verify encoding blobs on first use. Centralizing
+access avoids duplicate lazy-load logic and keeps import-time failures from
+transient hash mismatches out of unrelated modules.
+
+Use two proxy model names only:
+- LLM-facing token counts → ``gpt-4o`` (``o200k_base`` in tiktoken).
+- Embedding-facing token counts → ``text-embedding-3-small`` (``cl100k_base``).
+"""
+
+from __future__ import annotations
+
+import functools
+
+import tiktoken
+
+# OpenAI chat / completion-style counting (o200k_base).
+LLM_TOKEN_COUNT_PROXY_MODEL = "gpt-4o"
+
+# text-embedding-3-* API counting (cl100k_base).
+TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL = "text-embedding-3-small"
+
+
+def get_tiktoken_encoding_for_model(model: str) -> tiktoken.Encoding:
+ return tiktoken.encoding_for_model(model)
diff --git a/products/posthog_ai/backend/models.py b/products/posthog_ai/backend/models.py
index 2feb182842a3..ee075af38955 100644
--- a/products/posthog_ai/backend/models.py
+++ b/products/posthog_ai/backend/models.py
@@ -2,8 +2,7 @@ from typing import TYPE_CHECKING
from django.db import models
-import tiktoken
-
+from posthog.helpers.tiktoken_encoding import TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model
from posthog.models.utils import UUIDModel
if TYPE_CHECKING:
@@ -36,7 +35,7 @@ class AgentMemory(UUIDModel):
]
def embed(self, model_name: str) -> "ProduceResult":
- enc = tiktoken.get_encoding("cl100k_base")
+ enc = get_tiktoken_encoding_for_model(TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL)
token_count = len(enc.encode(self.contents))
if token_count > EMBEDDING_MODEL_TOKEN_LIMIT:
raise ValueError(
diff --git a/products/signals/backend/api.py b/products/signals/backend/api.py
index 9dbd3233e6d1..638a4f3c3a21 100644
--- a/products/signals/backend/api.py
+++ b/products/signals/backend/api.py
@@ -5,7 +5,6 @@ from typing import get_args
from django.conf import settings
import pydantic
-import tiktoken
import structlog
import temporalio
import posthoganalytics
@@ -13,6 +12,7 @@ import posthoganalytics
from posthog.schema import SignalInput
from posthog.event_usage import groups
+from posthog.helpers.tiktoken_encoding import LLM_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model
from posthog.models import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.client import async_connect
@@ -25,7 +25,6 @@ from products.signals.backend.temporal.types import BufferSignalsInput, EmitSign
logger = structlog.get_logger(__name__)
MAX_SIGNAL_DESCRIPTION_TOKENS = 8000
-_tiktoken_encoding = tiktoken.get_encoding("cl100k_base")
def _get_field_values(field: pydantic.fields.FieldInfo) -> tuple[str, ...]:
@@ -99,7 +98,7 @@ async def emit_signal(
if not is_enabled:
return
- token_count = len(_tiktoken_encoding.encode(description))
+ token_count = len(get_tiktoken_encoding_for_model(LLM_TOKEN_COUNT_PROXY_MODEL).encode(description))
if token_count > MAX_SIGNAL_DESCRIPTION_TOKENS:
raise ValueError(
f"Signal description exceeds {MAX_SIGNAL_DESCRIPTION_TOKENS} tokens ({token_count} tokens). "
diff --git a/products/signals/backend/temporal/llm.py b/products/signals/backend/temporal/llm.py
index 4b29a1e4e8c8..f8c6bcd39c80 100644
--- a/products/signals/backend/temporal/llm.py
+++ b/products/signals/backend/temporal/llm.py
@@ -4,12 +4,13 @@ from typing import Optional, TypeVar
from django.conf import settings
-import tiktoken
import structlog
import posthoganalytics
from anthropic.types import MessageParam
from posthoganalytics.ai.anthropic import AsyncAnthropic
+from posthog.helpers.tiktoken_encoding import TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model
+
logger = structlog.get_logger(__name__)
MATCHING_MODEL = os.getenv("SIGNAL_MATCHING_LLM_MODEL", "claude-sonnet-4-5")
@@ -50,7 +51,7 @@ def get_async_anthropic_client() -> AsyncAnthropic:
def truncate_query_to_token_limit(query: str, max_tokens: int = MAX_QUERY_TOKENS) -> str:
"""Truncate a query string to fit within token limit for embedding."""
try:
- enc = tiktoken.get_encoding("cl100k_base")
+ enc = get_tiktoken_encoding_for_model(TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL)
tokens = enc.encode(query)
if len(tokens) <= max_tokens:
return query