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(phai): keep large events from dropping (#61427)

Georgiy Tarasovd8b4cdcff567
diff --git a/ee/hogai/core/ai_event_truncation.py b/ee/hogai/core/ai_event_truncation.py
new file mode 100644
index 000000000000..351079b835a7
--- /dev/null
+++ b/ee/hogai/core/ai_event_truncation.py
@@ -0,0 +1,252 @@
+"""Truncate oversized AI analytics events before the PostHog SDK queues them.
+
+The vendored ``posthoganalytics`` Consumer drops any single event larger than 900 KiB
+client-side (``consumer.py`` ``MAX_MSG_SIZE``), before it ever reaches capture. Max AI's
+``$ai_trace``/``$ai_span``/``$ai_generation`` events carry full LangGraph state and model
+context blobs that routinely exceed that, so the whole event — including the data billing
+reads — is silently lost.
+
+``AIEventTruncator`` is wired as the SDK's public ``before_send`` hook (runs on the built
+event dict before the size check). It shrinks the heavy blobs while preserving the fields the
+usage report reads off ``$ai_trace.$ai_output_state`` — each message's ``type`` and its
+``tool_calls`` (``name`` + ``args.kind``) — so billing stays correct. Token-count properties
+live as separate top-level keys and are never touched.
+"""
+
+import json
+from copy import deepcopy
+from typing import Any
+
+import structlog
+from prometheus_client import Counter
+
+logger = structlog.get_logger(__name__)
+
+# Default budgets (tunable per AIEventTruncator instance). Each truncated property is capped at
+# PER_BLOB_BYTE_BUDGET — well under the SDK's 900 KiB per-event drop. A single event carries up to
+# two of the truncated blobs, so two full per-blob budgets would still exceed the drop;
+# COMBINED_EVENT_CEILING trims the present blobs so their combined size clears it with margin for
+# the small non-blob properties.
+PER_BLOB_BYTE_BUDGET = 700 * 1024
+COMBINED_EVENT_CEILING = 850 * 1024
+# Tier 1 caps individual string leaves (message content, tool/SQL output) to this many chars.
+PER_STRING_CAP = 10_000
+# Tier 3 never front-trims the messages list below this many entries.
+MIN_TAIL_MESSAGES = 1
+TRUNCATION_MARKER = "...truncated"
+
+TRUNCATABLE_AI_EVENTS = frozenset({"$ai_trace", "$ai_span", "$ai_generation"})
+# State blobs on $ai_trace/$ai_span, and model input/output on $ai_generation.
+TRUNCATABLE_PROPS = ("$ai_input_state", "$ai_output_state", "$ai_input", "$ai_output_choices")
+# Set on the event when anything was truncated, so it's queryable in PostHog.
+TRUNCATED_FLAG_PROP = "$ai_event_truncated"
+# Short structural fields kept when a message is reduced to its billing-critical shape.
+_KEPT_MESSAGE_FIELDS = ("type", "role", "id", "name", "tool_call_id")
+
+AI_EVENT_TRUNCATED_COUNTER = Counter(
+ "posthog_ai_event_truncated_total",
+ "AI event blobs truncated before capture to stay under the SDK per-event size limit",
+ ["event", "property", "tier"], # $ai_trace|$ai_span|$ai_generation ; property name ; leaf|strip|trim|hard
+)
+
+
+def byte_size(obj: Any) -> int:
+ """Serialized UTF-8 byte size, mirroring how the SDK Consumer measures an event."""
+ try:
+ return len(json.dumps(obj, default=str).encode())
+ except (TypeError, ValueError):
+ # Unserializable here would also fail in the SDK; treat as oversized so it gets truncated.
+ return COMBINED_EVENT_CEILING * 2
+
+
+class AIEventTruncator:
+ """Billing-safe truncation of oversized AI analytics events for the SDK ``before_send`` hook.
+
+ Instances are callable so they can be passed directly as ``before_send``. Budgets are
+ configurable per instance; the defaults match the module-level constants.
+ """
+
+ def __init__(
+ self,
+ *,
+ per_blob_byte_budget: int = PER_BLOB_BYTE_BUDGET,
+ combined_event_ceiling: int = COMBINED_EVENT_CEILING,
+ per_string_cap: int = PER_STRING_CAP,
+ min_tail_messages: int = MIN_TAIL_MESSAGES,
+ ):
+ self.per_blob_byte_budget = per_blob_byte_budget
+ self.combined_event_ceiling = combined_event_ceiling
+ self.per_string_cap = per_string_cap
+ self.min_tail_messages = min_tail_messages
+
+ def __call__(self, msg: Any) -> dict[str, Any]:
+ return self.truncate_event(msg)
+
+ def truncate_event(self, msg: Any) -> dict[str, Any]:
+ """``before_send`` hook: truncate oversized blobs on AI events so they clear the SDK's
+ per-event size drop. No-op for non-AI events and under-budget blobs. Never raises."""
+ try:
+ if not isinstance(msg, dict):
+ return msg
+ event = msg.get("event")
+ if event not in TRUNCATABLE_AI_EVENTS:
+ return msg
+ properties = msg.get("properties")
+ if not isinstance(properties, dict):
+ return msg
+
+ changed_tiers: dict[str, str] = {}
+ for prop in TRUNCATABLE_PROPS:
+ if properties.get(prop) is None:
+ continue
+ new_value, tier = self.truncate_blob(properties[prop])
+ if tier is not None:
+ properties[prop] = new_value
+ changed_tiers[prop] = tier
+
+ present_props = [prop for prop in TRUNCATABLE_PROPS if properties.get(prop) is not None]
+ if present_props:
+ self._enforce_combined_ceiling(properties, present_props, changed_tiers)
+
+ for prop, tier in changed_tiers.items():
+ AI_EVENT_TRUNCATED_COUNTER.labels(event=event, property=prop, tier=tier).inc()
+ if changed_tiers:
+ properties[TRUNCATED_FLAG_PROP] = True
+ return msg
+ except Exception:
+ # Degrade gracefully — the SDK also try/excepts before_send, but never let the hook break capture.
+ logger.exception("truncate_ai_event_failed")
+ return msg
+
+ def truncate_blob(self, value: Any, *, byte_budget: int | None = None) -> tuple[Any, str | None]:
+ """Truncate a single blob to ``byte_budget`` (defaults to the per-blob budget), billing-safe.
+ Never mutates ``value``.
+
+ Returns ``(value_or_truncated_copy, tier)`` where ``tier`` is ``None`` (no-op) or one of
+ ``"leaf"``/``"strip"``/``"trim"``/``"hard"`` for metrics. Handles dicts with a ``messages``
+ list, bare lists of messages (``$ai_input``/``$ai_output_choices``), and other shapes.
+ """
+ budget = self.per_blob_byte_budget if byte_budget is None else byte_budget
+
+ if byte_size(value) <= budget:
+ return value, None
+
+ # Tier 1 — cap long string leaves, keeping all structure.
+ work = self._cap_leaf_strings(deepcopy(value))
+ if byte_size(work) <= budget:
+ return work, "leaf"
+
+ # Tier 2/3 — reduce messages to billing-critical fields, then front-trim if still too large.
+ if isinstance(work, list):
+ stripped = [self._strip_message_to_billing(message) for message in work]
+ if byte_size(stripped) <= budget:
+ return stripped, "strip"
+ return self._front_trim_messages(stripped, budget), "trim"
+
+ holder, key = self._find_messages(work)
+ if holder is not None and key is not None:
+ stripped = [self._strip_message_to_billing(message) for message in holder[key]]
+ # Re-emit under top-level "messages" (where billing reads it), discarding other state keys.
+ if byte_size({"messages": stripped}) <= budget:
+ return {"messages": stripped}, "strip"
+ return {"messages": self._front_trim_messages(stripped, budget)}, "trim"
+
+ # Fallback — no recognizable messages; guarantee the bound.
+ return self._hard_truncate(value, budget), "hard"
+
+ def _enforce_combined_ceiling(
+ self,
+ properties: dict[str, Any],
+ present_props: list[str],
+ changed_tiers: dict[str, str],
+ ) -> None:
+ """Trim the largest present blob so all present blobs together clear the per-event drop."""
+ sizes = {prop: byte_size(properties[prop]) for prop in present_props}
+ if sum(sizes.values()) <= self.combined_event_ceiling:
+ return
+ largest = max(present_props, key=lambda prop: sizes[prop])
+ others = sum(size for prop, size in sizes.items() if prop != largest)
+ new_value, tier = self.truncate_blob(
+ properties[largest], byte_budget=max(0, self.combined_event_ceiling - others)
+ )
+ properties[largest] = new_value
+ if tier is not None:
+ changed_tiers[largest] = tier
+
+ def _cap_leaf_strings(self, obj: Any) -> Any:
+ """Recursively cap long string leaves in-place. Preserves all keys and structure, so short
+ billing fields (``type``, ``tool_calls[].name``, ``args.kind``) survive untouched."""
+ if isinstance(obj, str):
+ return obj[: self.per_string_cap] + TRUNCATION_MARKER if len(obj) > self.per_string_cap else obj
+ if isinstance(obj, dict):
+ for key, value in obj.items():
+ obj[key] = self._cap_leaf_strings(value)
+ return obj
+ if isinstance(obj, list):
+ for index, value in enumerate(obj):
+ obj[index] = self._cap_leaf_strings(value)
+ return obj
+ return obj
+
+ def _front_trim_messages(self, messages: list[Any], byte_budget: int) -> list[Any]:
+ """Drop messages from the FRONT (keep the tail) until under budget. Billing reads only the
+ current turn — the messages after the last human message — which lives at the tail."""
+ trimmed = messages
+ while len(trimmed) > self.min_tail_messages and byte_size(trimmed) > byte_budget:
+ trimmed = trimmed[1:]
+ # Even the minimum tail can blow the budget (e.g. one giant message). Guarantee the bound
+ # with a hard fallback rather than letting an oversized blob through to the SDK drop.
+ if byte_size(trimmed) > byte_budget:
+ return [self._hard_truncate(trimmed, byte_budget)]
+ return trimmed
+
+ @staticmethod
+ def _strip_tool_call(tool_call: Any) -> Any:
+ """Reduce a tool call to what billing reads: ``name`` (+ ``id``) and, only for ``search``,
+ ``args.kind`` (the docs-search exclusion). Other args are dropped — billing never reads them."""
+ if not isinstance(tool_call, dict):
+ return tool_call
+ reduced: dict[str, Any] = {}
+ name = tool_call.get("name")
+ if name is not None:
+ reduced["name"] = name
+ if "id" in tool_call:
+ reduced["id"] = tool_call["id"]
+ if name == "search":
+ args = tool_call.get("args")
+ if isinstance(args, dict) and "kind" in args:
+ reduced["args"] = {"kind": args["kind"]}
+ return reduced
+
+ @classmethod
+ def _strip_message_to_billing(cls, message: Any) -> Any:
+ """Reduce a message to short, billing-critical fields, dropping heavy ``content``."""
+ if not isinstance(message, dict):
+ return message
+ reduced: dict[str, Any] = {field: message[field] for field in _KEPT_MESSAGE_FIELDS if field in message}
+ tool_calls = message.get("tool_calls")
+ if isinstance(tool_calls, list):
+ reduced["tool_calls"] = [cls._strip_tool_call(tc) for tc in tool_calls]
+ return reduced
+
+ @staticmethod
+ def _find_messages(obj: Any) -> tuple[dict[str, Any] | None, str | None]:
+ """Locate a ``messages`` list: top-level first (the real ``$ai_output_state`` shape), then one
+ nested level. Returns the holding dict and key, or ``(None, None)``."""
+ if isinstance(obj, dict):
+ if isinstance(obj.get("messages"), list):
+ return obj, "messages"
+ for value in obj.values():
+ if isinstance(value, dict) and isinstance(value.get("messages"), list):
+ return value, "messages"
+ return None, None
+
+ @staticmethod
+ def _hard_truncate(value: Any, byte_budget: int) -> dict[str, Any]:
+ """Last-resort bound for shapes with no recognizable messages list."""
+ preview_chars = max(0, byte_budget // 2)
+ return {TRUNCATED_FLAG_PROP: True, "preview": json.dumps(value, default=str)[:preview_chars]}
+
+
+# Default instance used as the SDK before_send hook (see runner.init_handler).
+ai_event_truncator = AIEventTruncator()
diff --git a/ee/hogai/core/runner.py b/ee/hogai/core/runner.py
index 4ea5c55a7be6..9be0dbc98729 100644
--- a/ee/hogai/core/runner.py
+++ b/ee/hogai/core/runner.py
@@ -42,6 +42,7 @@ from posthog.utils import get_instance_region
from products.posthog_ai.backend.models.assistant import Conversation
+from ee.hogai.core.ai_event_truncation import ai_event_truncator
from ee.hogai.core.base import BaseAssistantGraph
from ee.hogai.core.stream_processor import AssistantStreamProcessorProtocol
from ee.hogai.tool import ApprovalRequest
@@ -196,15 +197,19 @@ class BaseAgentRunner(ABC):
privacy_mode=is_privacy_mode_enabled(team),
)
+ # flush_at=1 flushes each event immediately so traces deliver before short runs end;
+ # before_send truncates oversized AI blobs so they clear the SDK's per-event size drop.
+ client_kwargs = {"flush_at": 1, "before_send": ai_event_truncator}
+
# Local deployment or hobby
if not is_cloud() and (local_client := posthoganalytics.default_client):
self._callback_handlers.append(init_handler(local_client))
elif region := get_instance_region():
# Add regional client first
- self._callback_handlers.append(init_handler(get_client(region)))
+ self._callback_handlers.append(init_handler(get_client(region, **client_kwargs)))
# If we're in EU, add the US client as well, so we can see US and EU traces
if region == "EU":
- self._callback_handlers.append(init_handler(get_client("US")))
+ self._callback_handlers.append(init_handler(get_client("US", **client_kwargs)))
self._trace_id = trace_id
self._parent_span_id = parent_span_id
diff --git a/ee/hogai/core/test/test_ai_event_truncation.py b/ee/hogai/core/test/test_ai_event_truncation.py
new file mode 100644
index 000000000000..f1494a9af13d
--- /dev/null
+++ b/ee/hogai/core/test/test_ai_event_truncation.py
@@ -0,0 +1,229 @@
+import json
+from typing import Any
+
+from unittest import TestCase
+
+from parameterized import parameterized
+
+from ee.hogai.core.ai_event_truncation import (
+ AI_EVENT_TRUNCATED_COUNTER,
+ COMBINED_EVENT_CEILING,
+ PER_BLOB_BYTE_BUDGET,
+ TRUNCATED_FLAG_PROP,
+ TRUNCATION_MARKER,
+ AIEventTruncator,
+ ai_event_truncator,
+ byte_size,
+)
+
+SDK_EVENT_DROP_BYTES = 900 * 1024
+
+
+def _counter_value(event: str, prop: str, tier: str) -> float:
+ return AI_EVENT_TRUNCATED_COUNTER.labels(event=event, property=prop, tier=tier)._value.get()
+
+
+class TestTruncateBlob(TestCase):
+ def setUp(self):
+ self.truncator = AIEventTruncator()
+
+ def test_under_budget_is_noop_and_returns_same_object(self):
+ state = {"messages": [{"type": "human", "content": "hi"}], "graph_status": ""}
+ result, tier = self.truncator.truncate_blob(state, byte_budget=10_000)
+ self.assertIsNone(tier)
+ self.assertIs(result, state)
+
+ def test_leaf_truncation_caps_long_strings_and_keeps_structure(self):
+ state = {"messages": [{"type": "ai", "content": "x" * 50_000, "id": "abc"}]}
+ result, tier = AIEventTruncator(per_string_cap=200).truncate_blob(state, byte_budget=2_000)
+ self.assertEqual(tier, "leaf")
+ self.assertLessEqual(byte_size(result), 2_000)
+ message = result["messages"][0]
+ self.assertEqual(message["type"], "ai")
+ self.assertEqual(message["id"], "abc")
+ self.assertTrue(message["content"].endswith(TRUNCATION_MARKER))
+
+ def test_strip_drops_content_but_preserves_billing_fields(self):
+ state = {
+ "messages": [
+ {"type": "human", "content": "q" * 60_000},
+ {
+ "type": "ai",
+ "content": "a" * 60_000,
+ "tool_calls": [
+ {"name": "search", "id": "t1", "args": {"kind": "docs", "query": "z" * 60_000}},
+ {"name": "create_insight", "id": "t2", "args": {"spec": "y" * 60_000}},
+ ],
+ },
+ ],
+ "intermediate": "k" * 60_000,
+ }
+ result, tier = self.truncator.truncate_blob(state, byte_budget=2_000)
+ self.assertEqual(tier, "strip")
+ self.assertLessEqual(byte_size(result), 2_000)
+ # Billing reads top-level messages → type, tool_calls.name, and args.kind for search.
+ types = [m["type"] for m in result["messages"]]
+ self.assertEqual(types, ["human", "ai"])
+ tool_calls = result["messages"][1]["tool_calls"]
+ self.assertEqual(tool_calls[0]["name"], "search")
+ self.assertEqual(tool_calls[0]["args"]["kind"], "docs")
+ self.assertEqual(tool_calls[1]["name"], "create_insight")
+ # Non-search args are dropped (billing never reads them); heavy content is gone.
+ self.assertNotIn("args", tool_calls[1])
+ self.assertNotIn("content", result["messages"][1])
+ self.assertNotIn("intermediate", result)
+
+ def test_front_trim_keeps_tail_and_bounds_size(self):
+ messages = [{"type": "tool", "tool_call_id": str(i)} for i in range(2_000)]
+ state = {"messages": messages}
+ result, tier = self.truncator.truncate_blob(state, byte_budget=1_500)
+ self.assertEqual(tier, "trim")
+ self.assertLessEqual(byte_size(result), 1_500)
+ kept = result["messages"]
+ self.assertGreaterEqual(len(kept), 1)
+ self.assertLess(len(kept), 2_000)
+ # The kept messages are a suffix (tail) of the original — billing reads the current turn.
+ self.assertEqual(kept, messages[-len(kept) :])
+
+ def test_bare_list_of_messages_is_truncated(self):
+ choices = [{"role": "assistant", "content": "c" * 60_000, "tool_calls": [{"name": "x", "args": {}}]}]
+ result, tier = AIEventTruncator(per_string_cap=200).truncate_blob(choices, byte_budget=2_000)
+ self.assertEqual(tier, "leaf")
+ self.assertLessEqual(byte_size(result), 2_000)
+ self.assertEqual(result[0]["role"], "assistant")
+
+ def test_bare_list_strip_preserves_role(self):
+ choices = [{"role": "assistant", "content": "c" * 60_000} for _ in range(3)]
+ result, tier = self.truncator.truncate_blob(choices, byte_budget=300)
+ self.assertEqual(tier, "strip")
+ self.assertLessEqual(byte_size(result), 300)
+ self.assertTrue(all(m["role"] == "assistant" for m in result))
+ self.assertTrue(all("content" not in m for m in result))
+
+ def test_nested_messages_are_found_and_flattened(self):
+ state = {"agent": {"messages": [{"type": "ai", "content": "z" * 60_000}]}}
+ result, tier = self.truncator.truncate_blob(state, byte_budget=2_000)
+ self.assertEqual(tier, "strip")
+ # Re-emitted at top-level "messages" where billing reads it.
+ self.assertIn("messages", result)
+ self.assertEqual(result["messages"][0]["type"], "ai")
+
+ def test_scalar_without_messages_hits_hard_fallback(self):
+ result, tier = self.truncator.truncate_blob("s" * 50_000, byte_budget=1_000)
+ self.assertEqual(tier, "hard")
+ self.assertLessEqual(byte_size(result), 1_000)
+ self.assertTrue(result[TRUNCATED_FLAG_PROP])
+
+ def test_dict_without_messages_hits_hard_fallback(self):
+ state = {"blob": "b" * 50_000, "more": "m" * 50_000}
+ result, tier = AIEventTruncator(per_string_cap=40_000).truncate_blob(state, byte_budget=1_000)
+ self.assertEqual(tier, "hard")
+ self.assertLessEqual(byte_size(result), 1_000)
+
+ def test_single_oversized_tail_message_still_bounded(self):
+ # One message whose billing fields alone (thousands of tool_calls) blow the budget.
+ # Strip can't help, front-trim can't drop the only message, so the hard fallback must bound it.
+ huge = [{"type": "ai", "tool_calls": [{"name": "search", "id": str(i)} for i in range(5_000)]}]
+ for value in ({"messages": huge}, list(huge)):
+ result, tier = self.truncator.truncate_blob(value, byte_budget=2_000)
+ self.assertEqual(tier, "trim")
+ self.assertLessEqual(byte_size(result), 2_000)
+ json.dumps(result) # must not raise
+
+ @parameterized.expand(
+ [
+ ("dict_messages", {"messages": [{"type": "ai", "content": "x" * 80_000}]}),
+ ("bare_list", [{"role": "assistant", "content": "x" * 80_000}]),
+ ("scalar", "x" * 80_000),
+ ("nested", {"a": {"messages": [{"type": "tool", "content": "x" * 80_000}]}}),
+ ]
+ )
+ def test_result_is_valid_json_and_within_budget(self, _name, value):
+ result, tier = self.truncator.truncate_blob(value, byte_budget=2_000)
+ self.assertIsNotNone(tier)
+ self.assertLessEqual(byte_size(result), 2_000)
+ json.dumps(result) # must not raise
+
+
+class TestTruncateAiEvent(TestCase):
+ def test_non_ai_event_is_untouched(self):
+ msg = {"event": "$pageview", "properties": {"$ai_input_state": "x" * 2_000_000}}
+ result = ai_event_truncator(msg)
+ self.assertEqual(len(result["properties"]["$ai_input_state"]), 2_000_000)
+ self.assertNotIn(TRUNCATED_FLAG_PROP, result["properties"])
+
+ def test_malformed_input_never_raises(self):
+ self.assertEqual(ai_event_truncator({"event": "$ai_trace"}), {"event": "$ai_trace"})
+ self.assertEqual(
+ ai_event_truncator({"event": "$ai_trace", "properties": None}), {"event": "$ai_trace", "properties": None}
+ )
+
+ @parameterized.expand(
+ [
+ ("$ai_trace", "$ai_output_state"),
+ ("$ai_span", "$ai_input_state"),
+ ("$ai_generation", "$ai_input"),
+ ("$ai_generation", "$ai_output_choices"),
+ ]
+ )
+ def test_oversized_property_is_truncated_under_budget(self, event, prop):
+ before = _counter_value(event, prop, "leaf")
+ msg = {
+ "event": event,
+ "properties": {prop: {"messages": [{"type": "ai", "content": "x" * (PER_BLOB_BYTE_BUDGET + 50_000)}]}},
+ }
+ result = ai_event_truncator(msg)
+ self.assertLessEqual(byte_size(result["properties"][prop]), PER_BLOB_BYTE_BUDGET)
+ self.assertTrue(result["properties"][TRUNCATED_FLAG_PROP])
+ self.assertEqual(_counter_value(event, prop, "leaf"), before + 1)
+
+ def test_combined_ceiling_keeps_event_under_sdk_drop(self):
+ # Two blobs each under the per-blob budget but together over the combined ceiling.
+ def blob() -> dict:
+ return {"messages": [{"type": "ai", "content": "x" * 500} for _ in range(1_300)]}
+
+ msg: dict[str, Any] = {
+ "event": "$ai_trace",
+ "properties": {"$ai_input_state": blob(), "$ai_output_state": blob()},
+ }
+ self.assertGreater(
+ byte_size(msg["properties"]["$ai_input_state"]) + byte_size(msg["properties"]["$ai_output_state"]),
+ COMBINED_EVENT_CEILING,
+ )
+ result = ai_event_truncator(msg)
+ combined = byte_size(result["properties"]["$ai_input_state"]) + byte_size(
+ result["properties"]["$ai_output_state"]
+ )
+ self.assertLessEqual(combined, COMBINED_EVENT_CEILING)
+ self.assertLess(byte_size(result), SDK_EVENT_DROP_BYTES)
+ self.assertTrue(result["properties"][TRUNCATED_FLAG_PROP])
+
+ def test_under_budget_event_is_unchanged(self):
+ msg = {
+ "event": "$ai_generation",
+ "properties": {
+ "$ai_input": [{"role": "user", "content": "hi"}],
+ "$ai_input_tokens": 10,
+ "$ai_total_cost_usd": "0.01",
+ },
+ }
+ result = ai_event_truncator(msg)
+ self.assertEqual(result["properties"]["$ai_input"], [{"role": "user", "content": "hi"}])
+ self.assertNotIn(TRUNCATED_FLAG_PROP, result["properties"])
+
+ def test_token_and_cost_properties_are_never_touched(self):
+ msg = {
+ "event": "$ai_generation",
+ "properties": {
+ "$ai_input": [{"role": "user", "content": "x" * (PER_BLOB_BYTE_BUDGET + 50_000)}],
+ "$ai_input_tokens": 1234,
+ "$ai_output_tokens": 567,
+ "$ai_total_cost_usd": "0.42",
+ "$ai_billable": True,
+ },
+ }
+ result = ai_event_truncator(msg)
+ self.assertEqual(result["properties"]["$ai_input_tokens"], 1234)
+ self.assertEqual(result["properties"]["$ai_output_tokens"], 567)
+ self.assertEqual(result["properties"]["$ai_total_cost_usd"], "0.42")
+ self.assertTrue(result["properties"]["$ai_billable"])
diff --git a/ee/hogai/core/test/test_base_callback_handlers.py b/ee/hogai/core/test/test_base_callback_handlers.py
index 63b539d9c477..27028173d5e1 100644
--- a/ee/hogai/core/test/test_base_callback_handlers.py
+++ b/ee/hogai/core/test/test_base_callback_handlers.py
@@ -9,6 +9,7 @@ from posthoganalytics.ai.langchain.callbacks import CallbackHandler
from products.posthog_ai.backend.models.assistant import Conversation
from ee.hogai.chat_agent.runner import ChatAgentRunner
+from ee.hogai.core.ai_event_truncation import ai_event_truncator
from ee.hogai.core.runner import SubagentCallbackHandler
@@ -66,7 +67,7 @@ class TestBaseAgentRunnerCallbackHandlers(BaseTest):
)
self.assertEqual(len(runner._callback_handlers), 1)
- mock_get_client.assert_called_once_with("US")
+ mock_get_client.assert_called_once_with("US", flush_at=1, before_send=ai_event_truncator)
@patch("ee.hogai.core.runner.is_cloud")
@patch("ee.hogai.core.runner.get_instance_region")
@@ -78,7 +79,7 @@ class TestBaseAgentRunnerCallbackHandlers(BaseTest):
mock_eu_client = Mock()
mock_us_client = Mock()
- def get_client_side_effect(region):
+ def get_client_side_effect(region, **kwargs):
if region == "EU":
return mock_eu_client
elif region == "US":
@@ -95,8 +96,8 @@ class TestBaseAgentRunnerCallbackHandlers(BaseTest):
self.assertEqual(len(runner._callback_handlers), 2)
self.assertEqual(mock_get_client.call_count, 2)
- mock_get_client.assert_any_call("EU")
- mock_get_client.assert_any_call("US")
+ mock_get_client.assert_any_call("EU", flush_at=1, before_send=ai_event_truncator)
+ mock_get_client.assert_any_call("US", flush_at=1, before_send=ai_event_truncator)
@patch("ee.hogai.core.runner.is_cloud")
@patch("ee.hogai.core.runner.get_instance_region")