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(llma): restrict personal spend product to posthog_code (#59906)

Paul D'Ambraf726ddbbeeeb
diff --git a/products/llm_analytics/backend/api/personal_spend.py b/products/llm_analytics/backend/api/personal_spend.py
index 91eb130a4499..c4cf2647d547 100644
--- a/products/llm_analytics/backend/api/personal_spend.py
+++ b/products/llm_analytics/backend/api/personal_spend.py
@@ -3,12 +3,11 @@ Personal LLM spend analysis endpoint.
Surfaces the requesting user's own LLM spend across PostHog products (last N
days) by running a fixed set of HogQL queries against PostHog's internal cloud
-analytics team. Optionally filter to a single `ai_product` (e.g. `posthog_code`,
-`background_agents`) — when omitted, results aggregate across every product
-captured by LLM analytics for that user.
+analytics team. Scoped to a single `ai_product` via the required `product`
+query param; see `SUPPORTED_PRODUCTS` for the currently accepted values.
Endpoint:
-- GET /api/llm_analytics/@me/spend/?date_from=-30d&date_to=&product=<key>&limit=50&refresh=false
+- GET /api/llm_analytics/@me/spend/?product=<ai_product>&date_from=-30d&date_to=&limit=50&refresh=false
"""
from __future__ import annotations
@@ -45,6 +44,8 @@ logger = structlog.get_logger(__name__)
MAX_PRODUCT_KEY_LENGTH = 64
MAX_DATE_STRING_LENGTH = 32
+SUPPORTED_PRODUCTS = frozenset({"posthog_code"})
+
DEFAULT_DATE_FROM = "-30d"
MAX_WINDOW_DAYS = 90
_RELATIVE_DATE_RE = re.compile(r"^-?\d+[hdwmqyHDWMQY](Start|End)?$")
@@ -62,10 +63,9 @@ def _internal_team_id() -> int:
return settings.LLM_ANALYTICS_INTERNAL_TEAM_ID
-def _cache_key(email: str, date_from: str, date_to: str | None, product: str | None, limit: int) -> str:
- product_slot = product or "_all"
+def _cache_key(email: str, date_from: str, date_to: str | None, product: str, limit: int) -> str:
to_slot = date_to or "_now"
- return f"personal_spend:{email}:{date_from}:{to_slot}:{product_slot}:{limit}"
+ return f"personal_spend:{email}:{date_from}:{to_slot}:{product}:{limit}"
def _parse_date_param(value: str, field: str, now: datetime.datetime) -> datetime.datetime:
@@ -118,15 +118,13 @@ class _SpendQueryParamsSerializer(serializers.Serializer):
help_text=("End of the spend window. Accepts the same formats as `date_from`. Defaults to `now` when omitted."),
)
product = serializers.CharField(
- required=False,
- allow_null=True,
+ required=True,
+ allow_null=False,
allow_blank=False,
max_length=MAX_PRODUCT_KEY_LENGTH,
- default=None,
help_text=(
- "Optional `ai_product` key to scope the tool / model / trace breakdowns to a single product "
- "(e.g. `posthog_code`, `background_agents`). When omitted, those breakdowns aggregate across "
- "every product captured for the user."
+ "Required `ai_product` key to scope the tool / model / trace breakdowns to a single product. "
+ f"Only the following products are currently supported: {', '.join(sorted(SUPPORTED_PRODUCTS))}."
),
)
limit = serializers.IntegerField(
@@ -146,6 +144,14 @@ class _SpendQueryParamsSerializer(serializers.Serializer):
help_text="If true, bypass the result cache and re-run the underlying queries against ClickHouse.",
)
+ def validate_product(self, value: str) -> str:
+ if value not in SUPPORTED_PRODUCTS:
+ logger.warning("personal_spend.product_rejected", product=value)
+ raise serializers.ValidationError(
+ f"product `{value}` is not supported. Supported products: {', '.join(sorted(SUPPORTED_PRODUCTS))}."
+ )
+ return value
+
class _ProductBreakdownRowSerializer(serializers.Serializer):
product = serializers.CharField(
@@ -218,8 +224,7 @@ class _SummarySerializer(serializers.Serializer):
)
date_to = serializers.DateTimeField(help_text="Exclusive UTC end of the spend window resolved from the request.")
product = serializers.CharField(
- allow_null=True,
- help_text="The `ai_product` filter applied to tool / model / trace breakdowns. Null when unfiltered.",
+ help_text="The `ai_product` filter applied to tool / model / trace breakdowns — echoes the request `product`.",
)
total_cost_usd = serializers.FloatField(
help_text="Total LLM cost in USD across every `ai_product` for the user — independent of the `product` filter."
@@ -229,8 +234,8 @@ class _SummarySerializer(serializers.Serializer):
)
scoped_cost_usd = serializers.FloatField(
help_text=(
- "Total cost in USD for the product filter (or all products when unfiltered). Matches the cost summed "
- "across `by_tool` / `by_model` for the scoped slice."
+ "Total cost in USD for the product filter. Matches the cost summed across `by_tool` / `by_model` "
+ "for the scoped slice."
),
)
scoped_event_count = serializers.IntegerField(
@@ -337,13 +342,8 @@ def _ai_product_eq(value: str) -> ast.Expr:
)
-def _true() -> ast.Expr:
- """Identity filter used when no product scoping is requested."""
- return ast.Constant(value=True)
-
-
-def _product_filter(product: str | None) -> ast.Expr:
- return _ai_product_eq(product) if product else _true()
+def _product_filter(product: str) -> ast.Expr:
+ return _ai_product_eq(product)
def _truncate(rows: list[dict[str, Any]], limit: int) -> dict[str, Any]:
@@ -352,7 +352,7 @@ def _truncate(rows: list[dict[str, Any]], limit: int) -> dict[str, Any]:
def _fetch_summary(
- team: Team, email: str, from_dt: datetime.datetime, to_dt: datetime.datetime, product: str | None
+ team: Team, email: str, from_dt: datetime.datetime, to_dt: datetime.datetime, product: str
) -> dict[str, Any]:
query = parse_select(
"""
@@ -431,7 +431,7 @@ def _fetch_by_tool(
email: str,
from_dt: datetime.datetime,
to_dt: datetime.datetime,
- product: str | None,
+ product: str,
limit: int,
) -> dict[str, Any]:
# `$ai_tools_called` stores a comma-separated list of all tools called within a
@@ -483,7 +483,7 @@ def _fetch_by_model(
email: str,
from_dt: datetime.datetime,
to_dt: datetime.datetime,
- product: str | None,
+ product: str,
limit: int,
) -> dict[str, Any]:
query = parse_select(
@@ -550,12 +550,12 @@ class PersonalSpendViewSet(viewsets.ViewSet):
and the HogQL printer uses `pmat_email` on the main cluster's `person`
when registered -- so this path should be comparable to what the
satellite would have served. The endpoint is cached for 5 minutes per
- user (see `CACHE_TIMEOUT_SECONDS`). Optionally filter tool /
- model / trace breakdowns to a single
- `ai_product` via the `product` query param; `by_product` always returns
- the full cross-product breakdown. The endpoint is only registered on US
- Cloud + dev/test envs; hobby / self-hosted deploys never see this URL;
- EU deploys receive a 302 to the US URL.
+ user (see `CACHE_TIMEOUT_SECONDS`). The `product` query param is required
+ and scopes tool / model / trace breakdowns to a single `ai_product`; see
+ `SUPPORTED_PRODUCTS` for the currently accepted values. `by_product` always
+ returns the full cross-product breakdown. The endpoint is only registered
+ on US Cloud + dev/test envs; hobby / self-hosted deploys never see this
+ URL; EU deploys receive a 302 to the US URL.
"""
authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
@@ -592,10 +592,11 @@ class PersonalSpendViewSet(viewsets.ViewSet):
description=(
"Return a structured personal LLM spend analysis for the requesting user. Pass "
"`date_from` / `date_to` (absolute like `2026-04-23` or relative like `-7d`) to bound "
- "the window — defaults to the last 30 days, max 90 days. Pass `product=<ai_product>` "
- "to scope the tool / model / trace breakdowns to a single product (e.g. `posthog_code`); "
- "omit it for an aggregate view. `by_product` is always returned for cross-product "
- "visibility. Use `refresh=true` to bypass the 5-minute response cache."
+ "the window — defaults to the last 30 days, max 90 days. The `product=<ai_product>` "
+ "query param is required and scopes the tool / model / trace breakdowns to a single "
+ f"product; supported values: {', '.join(sorted(SUPPORTED_PRODUCTS))}. `by_product` is "
+ "always returned for cross-product visibility. Use `refresh=true` to bypass the "
+ "5-minute response cache."
),
tags=["LLM Analytics"],
)
diff --git a/products/llm_analytics/backend/api/test/__snapshots__/test_personal_spend.ambr b/products/llm_analytics/backend/api/test/__snapshots__/test_personal_spend.ambr
index 4a4b0640938b..574f4bbe18a5 100644
--- a/products/llm_analytics/backend/api/test/__snapshots__/test_personal_spend.ambr
+++ b/products/llm_analytics/backend/api/test/__snapshots__/test_personal_spend.ambr
@@ -2,8 +2,8 @@
# name: TestPersonalSpendQueries.test_empty_result_when_no_events
'''
/* user_id:0 request:_snapshot_@me_spend_ */
- SELECT countIf(1) AS scoped_event_count,
- round(sumIf(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64'), 1), 6) AS scoped_cost_usd,
+ SELECT countIf(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_product'), ''), 'null'), '^"|"$', ''), 'posthog_code'), 0)) AS scoped_event_count,
+ round(sumIf(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_product'), ''), 'null'), '^"|"$', ''), 'posthog_code'), 0)), 6) AS scoped_cost_usd,
count() AS event_count,
round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS total_cost_usd
FROM events
@@ -62,7 +62,7 @@
WHERE equals(person.team_id, 99999)
GROUP BY person.id
HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
- WHERE and(equals(events.team_id, 99999), equals(events.event, '$ai_generation'), ifNull(equals(events__person.properties___email, '[email protected]'), 0), and(greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC'))))
+ WHERE and(equals(events.team_id, 99999), equals(events.event, '$ai_generation'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_product'), ''), 'null'), '^"|"$', ''), 'posthog_code'), 0), ifNull(equals(events__person.properties___email, '[email protected]'), 0), and(greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC'))))
GROUP BY tool
ORDER BY cost_usd DESC
LIMIT 51 SETTINGS readonly=2,
@@ -142,7 +142,7 @@
WHERE equals(person.team_id, 99999)
GROUP BY person.id
HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
- WHERE and(equals(events.team_id, 99999), in(events.event, tuple('$ai_generation', '$ai_embedding')), ifNull(equals(events__person.properties___email, '[email protected]'), 0), and(greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC'))))
+ WHERE and(equals(events.team_id, 99999), in(events.event, tuple('$ai_generation', '$ai_embedding')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_product'), ''), 'null'), '^"|"$', ''), 'posthog_code'), 0), ifNull(equals(events__person.properties___email, '[email protected]'), 0), and(greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC'))))
GROUP BY model
ORDER BY cost_usd DESC
LIMIT 51 SETTINGS readonly=2,
diff --git a/products/llm_analytics/backend/api/test/test_personal_spend.py b/products/llm_analytics/backend/api/test/test_personal_spend.py
index e2f8fd2f2657..52c47e5eb0dc 100644
--- a/products/llm_analytics/backend/api/test/test_personal_spend.py
+++ b/products/llm_analytics/backend/api/test/test_personal_spend.py
@@ -27,6 +27,9 @@ from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
ENDPOINT = "/api/llm_analytics/@me/spend/"
+# `product` is required server-side; spell that out once for every happy-path test.
+PRODUCT_QS = "product=posthog_code"
+ENDPOINT_OK = f"{ENDPOINT}?{PRODUCT_QS}"
def _by_product(rows: list[dict], product: str | None) -> dict | None:
@@ -109,26 +112,47 @@ class TestPersonalSpendValidation(APIBaseTest):
]
)
def test_date_from_param_validation(self, _label: str, date_from: str, expected: int) -> None:
- response = self.client.get(f"{ENDPOINT}?date_from={date_from}")
+ response = self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&date_from={date_from}")
assert response.status_code == expected
- def test_date_params_optional_default_to_last_30_days(self) -> None:
- response = self.client.get(ENDPOINT)
+ def test_date_params_default_to_last_30_days(self) -> None:
+ response = self.client.get(ENDPOINT_OK)
assert response.status_code == status.HTTP_200_OK
summary = response.json()["summary"]
- assert summary["product"] is None
+ assert summary["product"] == "posthog_code"
# date_from / date_to are returned as ISO strings.
assert summary["date_from"] is not None
assert summary["date_to"] is not None
def test_date_to_before_date_from_rejected(self) -> None:
- response = self.client.get(f"{ENDPOINT}?date_from=-7d&date_to=-30d")
+ response = self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&date_from=-7d&date_to=-30d")
assert response.status_code == status.HTTP_400_BAD_REQUEST
def test_product_too_long_rejected(self) -> None:
response = self.client.get(f"{ENDPOINT}?product={'x' * 100}")
assert response.status_code == status.HTTP_400_BAD_REQUEST
+ def test_product_param_required(self) -> None:
+ response = self.client.get(ENDPOINT)
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ body = response.json()
+ assert body["attr"] == "product"
+ assert body["code"] == "required"
+
+ @parameterized.expand(
+ [
+ ("supported_posthog_code", "posthog_code", status.HTTP_200_OK),
+ ("unsupported_background_agents", "background_agents", status.HTTP_400_BAD_REQUEST),
+ ("unsupported_arbitrary", "wibble", status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ def test_product_param_restricted_to_supported_products(self, _label: str, product: str, expected: int) -> None:
+ response = self.client.get(f"{ENDPOINT}?product={product}")
+ assert response.status_code == expected
+ if expected == status.HTTP_400_BAD_REQUEST:
+ body = response.json()
+ assert "is not supported" in str(body)
+
@parameterized.expand(
[
("zero", "0", status.HTTP_400_BAD_REQUEST),
@@ -140,7 +164,7 @@ class TestPersonalSpendValidation(APIBaseTest):
]
)
def test_limit_param_validation(self, _label: str, limit: str, expected: int) -> None:
- response = self.client.get(f"{ENDPOINT}?limit={limit}")
+ response = self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&limit={limit}")
assert response.status_code == expected
@@ -191,7 +215,7 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_empty_result_when_no_events(self) -> None:
- response = self.client.get(ENDPOINT)
+ response = self.client.get(ENDPOINT_OK)
assert response.status_code == status.HTTP_200_OK
body = response.json()
assert body["summary"]["total_cost_usd"] == 0
@@ -203,25 +227,29 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):
assert body["by_model"] == {"items": [], "truncated": False}
assert body["top_traces"] == {"items": [], "truncated": False}
- def test_unfiltered_summary_aggregates_across_products(self) -> None:
+ def test_summary_reports_cross_product_totals_alongside_scoped(self) -> None:
self._create_generation(ai_product="posthog_code", cost=2.0)
self._create_generation(ai_product="background_agents", cost=1.0)
self._create_generation(ai_product="posthog_code", cost=0.5, event_name="$ai_embedding")
flush_persons_and_events()
- response = self.client.get(ENDPOINT)
+ response = self.client.get(ENDPOINT_OK)
body = response.json()
summary = body["summary"]
- assert summary["product"] is None
+ assert summary["product"] == "posthog_code"
+ # `event_count` / `total_cost_usd` stay cross-product even with the product filter.
assert summary["event_count"] == 3
assert summary["total_cost_usd"] == 3.5
- # Without a product filter, scoped totals match the cross-product totals.
- assert summary["scoped_event_count"] == 3
- assert summary["scoped_cost_usd"] == 3.5
- # by_product carries each slice for the caller to pick out.
+ # `scoped_*` is filtered to posthog_code only.
+ assert summary["scoped_event_count"] == 2
+ assert summary["scoped_cost_usd"] == 2.5
+ # by_product is always cross-product regardless of the filter.
code_row = _by_product(body["by_product"]["items"], "posthog_code")
assert code_row is not None
assert code_row["cost_usd"] == 2.5
+ bg_row = _by_product(body["by_product"]["items"], "background_agents")
+ assert bg_row is not None
+ assert bg_row["cost_usd"] == 1.0
assert body["by_product"]["truncated"] is False
def test_product_filter_scopes_summary_and_breakdowns(self) -> None:
@@ -283,7 +311,7 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):
self._create_generation(trace_id="expensive", cost=5.0)
flush_persons_and_events()
- response = self.client.get(ENDPOINT)
+ response = self.client.get(ENDPOINT_OK)
assert response.json()["top_traces"] == {"items": [], "truncated": False}
def test_other_users_spend_is_not_visible(self) -> None:
@@ -304,13 +332,13 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):
self._create_generation(cost=1.0)
flush_persons_and_events()
- response = self.client.get(ENDPOINT)
+ response = self.client.get(ENDPOINT_OK)
assert response.json()["summary"]["total_cost_usd"] == 1.0
def test_date_window_passes_through_to_query_layer(self) -> None:
with patch("products.llm_analytics.backend.api.personal_spend.execute_hogql_query") as mock_exec:
mock_exec.return_value.results = []
- response = self.client.get(f"{ENDPOINT}?date_from=-7d")
+ response = self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&date_from=-7d")
assert response.status_code == status.HTTP_200_OK
# 4 fetchers run once (summary, by_product, by_tool, by_model). top_traces is
@@ -320,51 +348,45 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):
def test_second_call_serves_from_cache(self) -> None:
with patch("products.llm_analytics.backend.api.personal_spend.execute_hogql_query") as mock_exec:
mock_exec.return_value.results = []
- self.client.get(ENDPOINT)
+ self.client.get(ENDPOINT_OK)
first = mock_exec.call_count
- self.client.get(ENDPOINT)
+ self.client.get(ENDPOINT_OK)
assert mock_exec.call_count == first
def test_refresh_bypasses_cache(self) -> None:
with patch("products.llm_analytics.backend.api.personal_spend.execute_hogql_query") as mock_exec:
mock_exec.return_value.results = []
- self.client.get(ENDPOINT)
+ self.client.get(ENDPOINT_OK)
first = mock_exec.call_count
- self.client.get(f"{ENDPOINT}?refresh=true")
+ self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&refresh=true")
assert mock_exec.call_count == first * 2
def test_cache_key_includes_date_from(self) -> None:
with patch("products.llm_analytics.backend.api.personal_spend.execute_hogql_query") as mock_exec:
mock_exec.return_value.results = []
- self.client.get(f"{ENDPOINT}?date_from=-7d")
- first = mock_exec.call_count
- self.client.get(f"{ENDPOINT}?date_from=-30d")
- assert mock_exec.call_count == first * 2
-
- def test_cache_key_includes_product(self) -> None:
- with patch("products.llm_analytics.backend.api.personal_spend.execute_hogql_query") as mock_exec:
- mock_exec.return_value.results = []
- self.client.get(ENDPOINT)
+ self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&date_from=-7d")
first = mock_exec.call_count
- self.client.get(f"{ENDPOINT}?product=posthog_code")
+ self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&date_from=-30d")
assert mock_exec.call_count == first * 2
def test_cache_key_includes_limit(self) -> None:
with patch("products.llm_analytics.backend.api.personal_spend.execute_hogql_query") as mock_exec:
mock_exec.return_value.results = []
- self.client.get(f"{ENDPOINT}?limit=10")
+ self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&limit=10")
first = mock_exec.call_count
- self.client.get(f"{ENDPOINT}?limit=50")
+ self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&limit=50")
assert mock_exec.call_count == first * 2
def test_by_product_truncated_when_more_than_limit_products(self) -> None:
# Three products, ask for limit=2 → top 2 returned, truncated=True.
+ # by_product is cross-product even when filtered, so the additional
+ # ai_products still show up.
self._create_generation(ai_product="a", cost=3.0)
self._create_generation(ai_product="b", cost=2.0)
self._create_generation(ai_product="c", cost=1.0)
flush_persons_and_events()
- response = self.client.get(f"{ENDPOINT}?limit=2")
+ response = self.client.get(f"{ENDPOINT}?{PRODUCT_QS}&limit=2")
by_product = response.json()["by_product"]
assert len(by_product["items"]) == 2
assert by_product["truncated"] is True
@@ -445,7 +467,7 @@ class TestPersonalSpendNonSessionAuth(APIBaseTest):
)
def test_personal_api_key_scope_matrix(self, _label: str, scopes: list[str], expected: int) -> None:
token = self._make_pat(scopes)
- response = self.client.get(ENDPOINT, headers={"authorization": f"Bearer {token}"})
+ response = self.client.get(ENDPOINT_OK, headers={"authorization": f"Bearer {token}"})
assert response.status_code == expected, response.content
@parameterized.expand(
@@ -458,5 +480,5 @@ class TestPersonalSpendNonSessionAuth(APIBaseTest):
)
def test_oauth_token_scope_matrix(self, _label: str, scope: str, expected: int) -> None:
token = self._make_oauth_token(scope)
- response = self.client.get(ENDPOINT, headers={"authorization": f"Bearer {token}"})
+ response = self.client.get(ENDPOINT_OK, headers={"authorization": f"Bearer {token}"})
assert response.status_code == expected, response.content
diff --git a/products/llm_analytics/frontend/generated/api.schemas.ts b/products/llm_analytics/frontend/generated/api.schemas.ts
index b3a768f7359d..a96ecdfdb82f 100644
--- a/products/llm_analytics/frontend/generated/api.schemas.ts
+++ b/products/llm_analytics/frontend/generated/api.schemas.ts
@@ -2247,16 +2247,13 @@ export interface _SummaryApi {
date_from: string
/** Exclusive UTC end of the spend window resolved from the request. */
date_to: string
- /**
- * The `ai_product` filter applied to tool / model / trace breakdowns. Null when unfiltered.
- * @nullable
- */
- product: string | null
+ /** The `ai_product` filter applied to tool / model / trace breakdowns — echoes the request `product`. */
+ product: string
/** Total LLM cost in USD across every `ai_product` for the user — independent of the `product` filter. */
total_cost_usd: number
/** Total $ai_generation + $ai_embedding events captured across every product. */
event_count: number
- /** Total cost in USD for the product filter (or all products when unfiltered). Matches the cost summed across `by_tool` / `by_model` for the scoped slice. */
+ /** Total cost in USD for the product filter. Matches the cost summed across `by_tool` / `by_model` for the scoped slice. */
scoped_cost_usd: number
/** Total $ai_generation + $ai_embedding events for the scoped slice. */
scoped_event_count: number
@@ -2955,11 +2952,11 @@ export type LlmAnalyticsPersonalSpendListParams = {
*/
limit?: number
/**
- * Optional `ai_product` key to scope the tool / model / trace breakdowns to a single product (e.g. `posthog_code`, `background_agents`). When omitted, those breakdowns aggregate across every product captured for the user.
+ * Required `ai_product` key to scope the tool / model / trace breakdowns to a single product. Only the following products are currently supported: posthog_code.
+ * @minLength 1
* @maxLength 64
- * @nullable
*/
- product?: string | null
+ product: string
/**
* If true, bypass the result cache and re-run the underlying queries against ClickHouse.
*/
diff --git a/products/llm_analytics/frontend/generated/api.ts b/products/llm_analytics/frontend/generated/api.ts
index d288e0598529..dc9f2a9b7be3 100644
--- a/products/llm_analytics/frontend/generated/api.ts
+++ b/products/llm_analytics/frontend/generated/api.ts
@@ -2033,7 +2033,7 @@ export const taggersTestHogCreate = async (
})
}
-export const getLlmAnalyticsPersonalSpendListUrl = (params?: LlmAnalyticsPersonalSpendListParams) => {
+export const getLlmAnalyticsPersonalSpendListUrl = (params: LlmAnalyticsPersonalSpendListParams) => {
const normalizedParams = new URLSearchParams()
Object.entries(params || {}).forEach(([key, value]) => {
@@ -2050,10 +2050,10 @@ export const getLlmAnalyticsPersonalSpendListUrl = (params?: LlmAnalyticsPersona
}
/**
- * Return a structured personal LLM spend analysis for the requesting user. Pass `date_from` / `date_to` (absolute like `2026-04-23` or relative like `-7d`) to bound the window — defaults to the last 30 days, max 90 days. Pass `product=<ai_product>` to scope the tool / model / trace breakdowns to a single product (e.g. `posthog_code`); omit it for an aggregate view. `by_product` is always returned for cross-product visibility. Use `refresh=true` to bypass the 5-minute response cache.
+ * Return a structured personal LLM spend analysis for the requesting user. Pass `date_from` / `date_to` (absolute like `2026-04-23` or relative like `-7d`) to bound the window — defaults to the last 30 days, max 90 days. The `product=<ai_product>` query param is required and scopes the tool / model / trace breakdowns to a single product; supported values: posthog_code. `by_product` is always returned for cross-product visibility. Use `refresh=true` to bypass the 5-minute response cache.
*/
export const llmAnalyticsPersonalSpendList = async (
- params?: LlmAnalyticsPersonalSpendListParams,
+ params: LlmAnalyticsPersonalSpendListParams,
options?: RequestInit
): Promise<PersonalSpendAnalysisResponseApi[]> => {
return apiMutator<PersonalSpendAnalysisResponseApi[]>(getLlmAnalyticsPersonalSpendListUrl(params), {
diff --git a/products/llm_analytics/mcp/tools.yaml b/products/llm_analytics/mcp/tools.yaml
index a027a6b813fa..2e635a975159 100644
--- a/products/llm_analytics/mcp/tools.yaml
+++ b/products/llm_analytics/mcp/tools.yaml
@@ -414,10 +414,10 @@ tools:
title: Get my LLM spend analysis
description: >
Retrieve the current user's personal LLM spend analysis across PostHog products over the last N days
- (default 30, max 90). Returns a summary plus breakdowns by product, tool, model, and top traces. Pass
- `product` (e.g. `posthog_code`, `background_agents`) to scope the tool / model / trace breakdowns to a
- single product; `by_product` always returns the cross-product view. Pass `refresh=true` to bypass the
- 5-minute cache.
+ (default 30, max 90). Returns a summary plus breakdowns by product, tool, model, and top traces. The
+ `product` query param is required and scopes the tool / model / trace breakdowns to a single product;
+ currently only `posthog_code` is supported. `by_product` always returns the cross-product view. Pass
+ `refresh=true` to bypass the 5-minute cache.
llma-prompt-archive:
operation: llm_prompts_name_archive_create
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 93969862de0c..fb3fed168b92 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2937,7 +2937,7 @@
}
},
"llma-personal-spend": {
- "description": "Retrieve the current user's personal LLM spend analysis across PostHog products over the last N days (default 30, max 90). Returns a summary plus breakdowns by product, tool, model, and top traces. Pass `product` (e.g. `posthog_code`, `background_agents`) to scope the tool / model / trace breakdowns to a single product; `by_product` always returns the cross-product view. Pass `refresh=true` to bypass the 5-minute cache.",
+ "description": "Retrieve the current user's personal LLM spend analysis across PostHog products over the last N days (default 30, max 90). Returns a summary plus breakdowns by product, tool, model, and top traces. The `product` query param is required and scopes the tool / model / trace breakdowns to a single product; currently only `posthog_code` is supported. `by_product` always returns the cross-product view. Pass `refresh=true` to bypass the 5-minute cache.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Get my LLM spend analysis",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 28a9592466a8..9b3d57d4a983 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3250,7 +3250,7 @@
}
},
"llma-personal-spend": {
- "description": "Retrieve the current user's personal LLM spend analysis across PostHog products over the last N days (default 30, max 90). Returns a summary plus breakdowns by product, tool, model, and top traces. Pass `product` (e.g. `posthog_code`, `background_agents`) to scope the tool / model / trace breakdowns to a single product; `by_product` always returns the cross-product view. Pass `refresh=true` to bypass the 5-minute cache.",
+ "description": "Retrieve the current user's personal LLM spend analysis across PostHog products over the last N days (default 30, max 90). Returns a summary plus breakdowns by product, tool, model, and top traces. The `product` query param is required and scopes the tool / model / trace breakdowns to a single product; currently only `posthog_code` is supported. `by_product` always returns the cross-product view. Pass `refresh=true` to bypass the 5-minute cache.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Get my LLM spend analysis",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f71e6f74f712..ea1355e16882 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -31733,16 +31733,13 @@ export namespace Schemas {
date_from: string;
/** Exclusive UTC end of the spend window resolved from the request. */
date_to: string;
- /**
- * The `ai_product` filter applied to tool / model / trace breakdowns. Null when unfiltered.
- * @nullable
- */
- product: string | null;
+ /** The `ai_product` filter applied to tool / model / trace breakdowns — echoes the request `product`. */
+ product: string;
/** Total LLM cost in USD across every `ai_product` for the user — independent of the `product` filter. */
total_cost_usd: number;
/** Total $ai_generation + $ai_embedding events captured across every product. */
event_count: number;
- /** Total cost in USD for the product filter (or all products when unfiltered). Matches the cost summed across `by_tool` / `by_model` for the scoped slice. */
+ /** Total cost in USD for the product filter. Matches the cost summed across `by_tool` / `by_model` for the scoped slice. */
scoped_cost_usd: number;
/** Total $ai_generation + $ai_embedding events for the scoped slice. */
scoped_event_count: number;
@@ -41729,11 +41726,11 @@ export namespace Schemas {
*/
limit?: number;
/**
- * Optional `ai_product` key to scope the tool / model / trace breakdowns to a single product (e.g. `posthog_code`, `background_agents`). When omitted, those breakdowns aggregate across every product captured for the user.
+ * Required `ai_product` key to scope the tool / model / trace breakdowns to a single product. Only the following products are currently supported: posthog_code.
+ * @minLength 1
* @maxLength 64
- * @nullable
*/
- product?: string | null;
+ product: string;
/**
* If true, bypass the result cache and re-run the underlying queries against ClickHouse.
*/
diff --git a/services/mcp/src/generated/llm_analytics/api.ts b/services/mcp/src/generated/llm_analytics/api.ts
index 0b2672e9f79b..02c77567df2c 100644
--- a/services/mcp/src/generated/llm_analytics/api.ts
+++ b/services/mcp/src/generated/llm_analytics/api.ts
@@ -1986,7 +1986,7 @@ export const TaggersTestHogCreateBody = /* @__PURE__ */ zod.object({
})
/**
- * Return a structured personal LLM spend analysis for the requesting user. Pass `date_from` / `date_to` (absolute like `2026-04-23` or relative like `-7d`) to bound the window — defaults to the last 30 days, max 90 days. Pass `product=<ai_product>` to scope the tool / model / trace breakdowns to a single product (e.g. `posthog_code`); omit it for an aggregate view. `by_product` is always returned for cross-product visibility. Use `refresh=true` to bypass the 5-minute response cache.
+ * Return a structured personal LLM spend analysis for the requesting user. Pass `date_from` / `date_to` (absolute like `2026-04-23` or relative like `-7d`) to bound the window — defaults to the last 30 days, max 90 days. The `product=<ai_product>` query param is required and scopes the tool / model / trace breakdowns to a single product; supported values: posthog_code. `by_product` is always returned for cross-product visibility. Use `refresh=true` to bypass the 5-minute response cache.
*/
export const llmAnalyticsPersonalSpendListQueryDateFromDefault = `-30d`
export const llmAnalyticsPersonalSpendListQueryDateFromMax = 32
@@ -2024,10 +2024,10 @@ export const LlmAnalyticsPersonalSpendListQueryParams = /* @__PURE__ */ zod.obje
),
product: zod
.string()
+ .min(1)
.max(llmAnalyticsPersonalSpendListQueryProductMax)
- .nullish()
.describe(
- 'Optional `ai_product` key to scope the tool / model / trace breakdowns to a single product (e.g. `posthog_code`, `background_agents`). When omitted, those breakdowns aggregate across every product captured for the user.'
+ 'Required `ai_product` key to scope the tool / model / trace breakdowns to a single product. Only the following products are currently supported: posthog_code.'
),
refresh: zod
.boolean()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-personal-spend.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-personal-spend.json
index e4195e9eb399..1af547772fbd 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-personal-spend.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-personal-spend.json
@@ -28,16 +28,10 @@
"type": "number"
},
"product": {
- "anyOf": [
- {
- "maxLength": 64,
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "description": "Optional `ai_product` key to scope the tool / model / trace breakdowns to a single product (e.g. `posthog_code`, `background_agents`). When omitted, those breakdowns aggregate across every product captured for the user."
+ "description": "Required `ai_product` key to scope the tool / model / trace breakdowns to a single product. Only the following products are currently supported: posthog_code.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
},
"refresh": {
"default": false,
@@ -45,5 +39,6 @@
"type": "boolean"
}
},
+ "required": ["product"],
"type": "object"
}