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(admin): view and top up a team's AI gateway wallet (#63901)

Richard Solomou530e4bacee93
diff --git a/posthog/admin/admins/team_admin.py b/posthog/admin/admins/team_admin.py
index 101e9eae34db..d146bdd53355 100644
--- a/posthog/admin/admins/team_admin.py
+++ b/posthog/admin/admins/team_admin.py
@@ -3,9 +3,11 @@ import csv
import json
import uuid
import asyncio
+import hashlib
import tempfile
import dataclasses
from datetime import datetime, timedelta
+from decimal import Decimal, InvalidOperation
from urllib import parse
from django.conf import settings
@@ -32,6 +34,7 @@ from posthog.admin.inlines.team_experiments_config_inline import TeamExperiments
from posthog.admin.inlines.team_marketing_analytics_config_inline import TeamMarketingAnalyticsConfigInline
from posthog.admin.inlines.user_product_list_inline import UserProductListInline
from posthog.cloud_utils import is_cloud
+from posthog.llm.gateway_internal_client import AIGatewayInternalError, AIGatewayNotConfigured, add_credit, get_wallet
from posthog.models import Team
from posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, log_activity
from posthog.models.remote_config import RemoteConfig
@@ -55,6 +58,9 @@ from products.replay.backend.models.exported_recording import ExportedRecording
logger = get_logger()
+# Upper bound on a single admin AI gateway top-up, to catch fat-fingered amounts.
+MAX_CREDIT_USD = Decimal("1000000")
+
@dataclasses.dataclass(frozen=True)
class ReplayActivityContext(ActivityContextBase):
@@ -134,6 +140,7 @@ class TeamAdmin(admin.ModelAdmin):
"api_token_display",
"admit_state",
"ai_gateway_actions",
+ "ai_gateway_wallet",
"policy_cache_blob",
]
@@ -262,6 +269,7 @@ class TeamAdmin(admin.ModelAdmin):
"llm_gateway_overspend_allowance_usd",
"admit_state",
"ai_gateway_actions",
+ "ai_gateway_wallet",
"policy_cache_blob",
],
"description": mark_safe(
@@ -474,6 +482,81 @@ class TeamAdmin(admin.ModelAdmin):
self._refresh_ai_gateway_policy_cache(team)
return redirect(reverse("admin:posthog_team_change", args=[object_id]))
+ def add_ai_gateway_credit_view(self, request, object_id):
+ team = Team.objects.get(pk=object_id)
+ if not self.has_change_permission(request, team):
+ raise PermissionDenied
+
+ credit_url = reverse("admin:posthog_team_add_ai_gateway_credit", args=[object_id])
+
+ if request.method == "GET":
+ context = {
+ **self.admin_site.each_context(request),
+ "team": team,
+ "title": f"Add AI gateway credit - {team.name}",
+ # Per-render nonce; combined with amount + reason on submit to form the
+ # idempotency key, so a double-submit dedupes but a back-edit-resubmit
+ # of a different amount is treated as a new top-up.
+ "form_nonce": str(uuid.uuid4()),
+ }
+ return render(request, "admin/posthog/team/add_ai_gateway_credit_form.html", context)
+
+ amount_raw = request.POST.get("amount_usd", "").strip()
+ reason = request.POST.get("reason", "").strip()
+ form_nonce = request.POST.get("form_nonce", "").strip() or str(uuid.uuid4())
+
+ if not reason:
+ messages.error(request, "Reason is required")
+ return redirect(credit_url)
+ try:
+ amount = Decimal(amount_raw)
+ except InvalidOperation:
+ messages.error(request, "Amount must be a valid decimal")
+ return redirect(credit_url)
+ # is_finite() rejects NaN/sNaN/±Inf before `amount <= 0`, which raises on NaN.
+ if not amount.is_finite() or amount <= 0:
+ messages.error(request, "Amount must be a positive number")
+ return redirect(credit_url)
+ if amount > MAX_CREDIT_USD:
+ messages.error(request, f"Amount exceeds the ${MAX_CREDIT_USD:,} per-top-up limit")
+ return redirect(credit_url)
+
+ # Bind the key to the amount + reason so editing the amount after a submit
+ # produces a new key instead of replaying the prior top-up.
+ idempotency_key = hashlib.sha256(f"{form_nonce}:{amount}:{reason}".encode()).hexdigest()
+ try:
+ result = add_credit(team.id, str(amount), reason, idempotency_key)
+ except AIGatewayInternalError as exc:
+ logger.warning(
+ "admin_add_ai_gateway_credit_failed",
+ team_id=team.id,
+ amount_usd=amount_raw,
+ error=str(exc),
+ triggered_by=request.user.email,
+ )
+ messages.error(request, f"Failed to add credit: {exc}")
+ return redirect(credit_url)
+
+ logger.info(
+ "admin_add_ai_gateway_credit",
+ team_id=team.id,
+ amount_usd=str(amount),
+ entry_id=result.entry_id,
+ duplicate=result.duplicate,
+ triggered_by=request.user.email,
+ )
+ if result.duplicate:
+ messages.info(
+ request,
+ f"Idempotent replay — no new credit. Team '{team.name}' balance: ${result.balance_usd}.",
+ )
+ else:
+ messages.success(
+ request,
+ f"Added ${result.amount_usd} to team '{team.name}'. New balance: ${result.balance_usd}.",
+ )
+ return redirect(reverse("admin:posthog_team_change", args=[object_id]))
+
@admin.display(description="Actions")
def ai_gateway_actions(self, team: Team):
if not team.pk:
@@ -510,6 +593,42 @@ class TeamAdmin(admin.ModelAdmin):
)
return format_html("<em>Not enrolled</em>")
+ @admin.display(description="Wallet (AI gateway credits)")
+ def ai_gateway_wallet(self, team: Team):
+ if not team.pk:
+ return "-"
+ # The balance read is a blocking call to the gateway, so defer it behind a
+ # link (mirrors remote_config_cache_actions) instead of fetching on every
+ # team page render.
+ # nosemgrep: python.django.security.audit.avoid-mark-safe.avoid-mark-safe (admin-only, renders trusted template)
+ return mark_safe(
+ render_to_string(
+ "admin/posthog/team/ai_gateway_wallet_actions.html",
+ {
+ "wallet_url": reverse("admin:posthog_team_ai_gateway_wallet", args=[team.pk]),
+ "add_credit_url": reverse("admin:posthog_team_add_ai_gateway_credit", args=[team.pk]),
+ },
+ )
+ )
+
+ def ai_gateway_wallet_view(self, request, object_id):
+ team = Team.objects.get(pk=object_id)
+ if not self.has_view_permission(request, team):
+ raise PermissionDenied
+ context = {
+ **self.admin_site.each_context(request),
+ "team": team,
+ "title": f"AI gateway wallet - {team.name}",
+ "add_credit_url": reverse("admin:posthog_team_add_ai_gateway_credit", args=[team.pk]),
+ }
+ try:
+ context["wallet"] = get_wallet(team.id)
+ except AIGatewayNotConfigured:
+ context["error"] = "ai-gateway internal API not configured in this region"
+ except AIGatewayInternalError as exc:
+ context["error"] = f"wallet unavailable: {exc}"
+ return render(request, "admin/posthog/team/ai_gateway_wallet_page.html", context)
+
@admin.display(description="Policy cache blob (what the gateway sees)")
def policy_cache_blob(self, team: Team):
if not team.pk:
@@ -602,6 +721,16 @@ class TeamAdmin(admin.ModelAdmin):
self.admin_site.admin_view(self.clear_ai_gateway_revoke_view),
name="posthog_team_clear_ai_gateway_revoke",
),
+ path(
+ "<path:object_id>/add-ai-gateway-credit/",
+ self.admin_site.admin_view(self.add_ai_gateway_credit_view),
+ name="posthog_team_add_ai_gateway_credit",
+ ),
+ path(
+ "<path:object_id>/ai-gateway-wallet/",
+ self.admin_site.admin_view(self.ai_gateway_wallet_view),
+ name="posthog_team_ai_gateway_wallet",
+ ),
]
return custom_urls + urls
diff --git a/posthog/admin/inlines/team_inline.py b/posthog/admin/inlines/team_inline.py
index a660d6fe502b..34fc30334035 100644
--- a/posthog/admin/inlines/team_inline.py
+++ b/posthog/admin/inlines/team_inline.py
@@ -49,6 +49,7 @@ class TeamInline(TabularInlinePaginated):
"api_token_display",
"admit_state",
"ai_gateway_actions",
+ "ai_gateway_wallet",
"policy_cache_blob",
)
] + ["displayed_name"]
diff --git a/posthog/admin/test_team_admin.py b/posthog/admin/test_team_admin.py
index fb032c628740..1139f6d6fcc4 100644
--- a/posthog/admin/test_team_admin.py
+++ b/posthog/admin/test_team_admin.py
@@ -1,3 +1,4 @@
+import hashlib
from datetime import timedelta
from decimal import Decimal
@@ -13,6 +14,13 @@ from django.test import RequestFactory
from parameterized import parameterized
from posthog.admin.admins.team_admin import TeamAdmin
+from posthog.llm.gateway_internal_client import (
+ AIGatewayInternalError,
+ AIGatewayNotConfigured,
+ CreditResult,
+ LedgerEntry,
+ Wallet,
+)
from posthog.models.team.team import Team
@@ -312,6 +320,168 @@ class TestTeamAdminLLMGateway(BaseTest):
assert "&lt;script&gt;" in rendered
+class TestTeamAdminAIGatewayWallet(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save()
+ self.factory = RequestFactory()
+ self.admin = TeamAdmin(Team, AdminSite())
+ self.credit_url = f"/admin/posthog/team/{self.team.pk}/add-ai-gateway-credit/"
+ self.team_change_url = f"/admin/posthog/team/{self.team.pk}/change/"
+
+ reverse_patcher = patch(
+ "posthog.admin.admins.team_admin.reverse",
+ side_effect=lambda name, args=None, kwargs=None: (
+ self.team_change_url if name == "admin:posthog_team_change" else self.credit_url
+ ),
+ )
+ reverse_patcher.start()
+ self.addCleanup(reverse_patcher.stop)
+
+ def _post(self, data: dict):
+ request = self.factory.post("/", data)
+ request.user = self.user
+ _attach_messages(request)
+ return request
+
+ def _get(self):
+ request = self.factory.get("/")
+ request.user = self.user
+ _attach_messages(request)
+ return request
+
+ def test_wallet_field_renders_actions_without_fetching(self) -> None:
+ with patch("posthog.admin.admins.team_admin.get_wallet") as mock_get_wallet:
+ rendered = str(self.admin.ai_gateway_wallet(self.team))
+ mock_get_wallet.assert_not_called()
+ assert "View wallet" in rendered
+ assert "Add credit" in rendered
+
+ def test_wallet_view_not_configured_degrades_gracefully(self) -> None:
+ with patch("posthog.admin.admins.team_admin.get_wallet", side_effect=AIGatewayNotConfigured()):
+ with patch("posthog.admin.admins.team_admin.render") as mock_render:
+ self.admin.ai_gateway_wallet_view(self._get(), str(self.team.pk))
+ assert "not configured" in mock_render.call_args.args[2]["error"]
+
+ def test_wallet_view_unavailable_degrades_gracefully(self) -> None:
+ with patch("posthog.admin.admins.team_admin.get_wallet", side_effect=AIGatewayInternalError("boom")):
+ with patch("posthog.admin.admins.team_admin.render") as mock_render:
+ self.admin.ai_gateway_wallet_view(self._get(), str(self.team.pk))
+ error = mock_render.call_args.args[2]["error"]
+ assert "wallet unavailable" in error
+ assert "boom" in error
+
+ def test_wallet_view_renders_balance(self) -> None:
+ wallet = Wallet(
+ team_id=self.team.id,
+ known=True,
+ has_ledger=True,
+ balance="9.500000",
+ recent=[LedgerEntry("2026-06-01", "topup", "funding", "prepaid", "10.000000", "ref-1")],
+ )
+ with patch("posthog.admin.admins.team_admin.get_wallet", return_value=wallet):
+ with patch("posthog.admin.admins.team_admin.render") as mock_render:
+ self.admin.ai_gateway_wallet_view(self._get(), str(self.team.pk))
+ assert mock_render.call_args.args[2]["wallet"].balance == "9.500000"
+
+ def test_wallet_view_requires_view_permission(self) -> None:
+ with patch.object(self.admin, "has_view_permission", return_value=False):
+ with self.assertRaises(PermissionDenied):
+ self.admin.ai_gateway_wallet_view(self._get(), str(self.team.pk))
+
+ def test_add_credit_get_renders_form_with_nonce(self) -> None:
+ with patch("posthog.admin.admins.team_admin.render") as mock_render:
+ self.admin.add_ai_gateway_credit_view(self._get(), str(self.team.pk))
+ template = mock_render.call_args.args[1]
+ context = mock_render.call_args.args[2]
+ assert template == "admin/posthog/team/add_ai_gateway_credit_form.html"
+ assert context["form_nonce"]
+
+ def test_add_credit_post_valid_calls_client_and_redirects_to_change(self) -> None:
+ request = self._post({"amount_usd": "25.00", "reason": "topup", "form_nonce": "nonce-1"})
+ result = CreditResult(
+ team_id=self.team.id, entry_id="e1", amount_usd="25.000000", balance_usd="35.000000", duplicate=False
+ )
+ with patch("posthog.admin.admins.team_admin.add_credit", return_value=result) as mock_add:
+ response = self.admin.add_ai_gateway_credit_view(request, str(self.team.pk))
+ assert response.status_code == 302
+ assert response["Location"] == self.team_change_url
+ expected_key = hashlib.sha256(b"nonce-1:25.00:topup").hexdigest()
+ assert mock_add.call_args.args == (self.team.id, "25.00", "topup", expected_key)
+
+ def test_add_credit_key_changes_when_amount_changes(self) -> None:
+ # Same form nonce, different amount → different key, so a back-edit-resubmit
+ # applies the new amount instead of replaying the old top-up.
+ result = CreditResult(team_id=self.team.id, entry_id="e1", amount_usd="0", balance_usd="0", duplicate=False)
+ with patch("posthog.admin.admins.team_admin.add_credit", return_value=result) as mock_add:
+ for amount in ("10", "20"):
+ request = self._post({"amount_usd": amount, "reason": "x", "form_nonce": "same-nonce"})
+ self.admin.add_ai_gateway_credit_view(request, str(self.team.pk))
+ assert mock_add.call_args_list[0].args[3] != mock_add.call_args_list[1].args[3]
+
+ def test_add_credit_key_stable_for_same_inputs(self) -> None:
+ result = CreditResult(team_id=self.team.id, entry_id="e1", amount_usd="0", balance_usd="0", duplicate=False)
+ with patch("posthog.admin.admins.team_admin.add_credit", return_value=result) as mock_add:
+ for _ in range(2):
+ request = self._post({"amount_usd": "10", "reason": "x", "form_nonce": "same-nonce"})
+ self.admin.add_ai_gateway_credit_view(request, str(self.team.pk))
+ assert mock_add.call_args_list[0].args[3] == mock_add.call_args_list[1].args[3]
+
+ def test_add_credit_post_generates_key_when_nonce_absent(self) -> None:
+ request = self._post({"amount_usd": "5", "reason": "topup"})
+ result = CreditResult(team_id=self.team.id, entry_id="e1", amount_usd="5", balance_usd="5", duplicate=False)
+ with patch("posthog.admin.admins.team_admin.add_credit", return_value=result) as mock_add:
+ self.admin.add_ai_gateway_credit_view(request, str(self.team.pk))
+ assert mock_add.call_args.args[3] # idempotency key was generated
+
+ @parameterized.expand(
+ [
+ ("invalid_amount", {"amount_usd": "abc", "reason": "x"}),
+ ("zero_amount", {"amount_usd": "0", "reason": "x"}),
+ ("negative_amount", {"amount_usd": "-5", "reason": "x"}),
+ ("nan_amount", {"amount_usd": "NaN", "reason": "x"}),
+ ("infinity_amount", {"amount_usd": "Infinity", "reason": "x"}),
+ ("huge_amount", {"amount_usd": "1e999", "reason": "x"}),
+ ("over_cap_amount", {"amount_usd": "1000001", "reason": "x"}),
+ ("missing_reason", {"amount_usd": "5", "reason": " "}),
+ ]
+ )
+ def test_add_credit_post_rejected_inputs_redirect_to_form_without_calling_client(
+ self, _name: str, data: dict
+ ) -> None:
+ request = self._post(data)
+ with patch("posthog.admin.admins.team_admin.add_credit") as mock_add:
+ response = self.admin.add_ai_gateway_credit_view(request, str(self.team.pk))
+ assert response.status_code == 302
+ assert response["Location"] == self.credit_url
+ mock_add.assert_not_called()
+
+ def test_add_credit_post_gateway_error_logs_and_redirects_to_form(self) -> None:
+ request = self._post({"amount_usd": "5", "reason": "x"})
+ with patch("posthog.admin.admins.team_admin.add_credit", side_effect=AIGatewayInternalError("nope")):
+ with patch("posthog.admin.admins.team_admin.logger") as mock_logger:
+ response = self.admin.add_ai_gateway_credit_view(request, str(self.team.pk))
+ assert response.status_code == 302
+ assert response["Location"] == self.credit_url
+ mock_logger.warning.assert_called_once()
+ assert mock_logger.warning.call_args.args[0] == "admin_add_ai_gateway_credit_failed"
+
+ def test_add_credit_duplicate_redirects_to_change(self) -> None:
+ request = self._post({"amount_usd": "5", "reason": "x"})
+ result = CreditResult(team_id=self.team.id, entry_id="e1", amount_usd="5", balance_usd="5", duplicate=True)
+ with patch("posthog.admin.admins.team_admin.add_credit", return_value=result):
+ response = self.admin.add_ai_gateway_credit_view(request, str(self.team.pk))
+ assert response.status_code == 302
+ assert response["Location"] == self.team_change_url
+
+ def test_add_credit_requires_change_permission(self) -> None:
+ request = self._post({"amount_usd": "5", "reason": "x"})
+ with patch.object(self.admin, "has_change_permission", return_value=False):
+ with self.assertRaises(PermissionDenied):
+ self.admin.add_ai_gateway_credit_view(request, str(self.team.pk))
+
+
class TestTeamAdminFormOverspendAllowance(BaseTest):
def _form(self, value, instance=None):
instance = instance or self.team
diff --git a/posthog/llm/gateway_internal_client.py b/posthog/llm/gateway_internal_client.py
new file mode 100644
index 000000000000..ab4b32e7e0d8
--- /dev/null
+++ b/posthog/llm/gateway_internal_client.py
@@ -0,0 +1,143 @@
+import dataclasses
+from typing import Any
+
+from django.conf import settings
+
+import httpx
+
+INTERNAL_API_TIMEOUT_SECONDS = 5.0
+IDEMPOTENCY_KEY_HEADER = "Idempotency-Key"
+
+
+class AIGatewayInternalError(Exception):
+ """An ai-gateway internal admin API call failed."""
+
+
+class AIGatewayNotConfigured(AIGatewayInternalError):
+ """AI_GATEWAY_INTERNAL_URL / AI_GATEWAY_INTERNAL_TOKEN are not set."""
+
+
[email protected](frozen=True)
+class LedgerEntry:
+ when: str
+ kind: str
+ source: str
+ destination: str
+ amount: str
+ reference: str
+
+
[email protected](frozen=True)
+class Wallet:
+ team_id: int
+ # known=False is a real team with no gateway account yet; has_ledger=False
+ # is a deploy without the ledger backend wired (e.g. dev) — balance is None
+ # in both cases.
+ known: bool
+ has_ledger: bool
+ balance: str | None
+ recent: list[LedgerEntry]
+
+
[email protected](frozen=True)
+class CreditResult:
+ team_id: int
+ entry_id: str
+ amount_usd: str
+ balance_usd: str
+ duplicate: bool
+
+
+def _config() -> tuple[str, str]:
+ url = (settings.AI_GATEWAY_INTERNAL_URL or "").rstrip("/")
+ token = settings.AI_GATEWAY_INTERNAL_TOKEN or ""
+ if not url or not token:
+ raise AIGatewayNotConfigured("AI_GATEWAY_INTERNAL_URL and AI_GATEWAY_INTERNAL_TOKEN must be set")
+ return url, token
+
+
+def _auth_headers(token: str, extra: dict[str, str] | None = None) -> dict[str, str]:
+ headers = {"Authorization": f"Bearer {token}"}
+ if extra:
+ headers.update(extra)
+ return headers
+
+
+def get_wallet(team_id: int) -> Wallet:
+ url, token = _config()
+ try:
+ # trust_env=False keeps the in-cluster call off the egress proxy.
+ response = httpx.get(
+ f"{url}/internal/admin/api/teams/{team_id}",
+ headers=_auth_headers(token),
+ timeout=INTERNAL_API_TIMEOUT_SECONDS,
+ trust_env=False,
+ )
+ response.raise_for_status()
+ data = response.json()
+ except (httpx.HTTPError, ValueError) as exc:
+ raise AIGatewayInternalError(f"wallet read failed: {exc}") from exc
+
+ wallet = data.get("wallet") or {}
+ recent = [
+ LedgerEntry(
+ when=row.get("when", ""),
+ kind=row.get("kind", ""),
+ source=row.get("source", ""),
+ destination=row.get("destination", ""),
+ amount=row.get("amount", ""),
+ reference=row.get("reference", ""),
+ )
+ for row in data.get("recent") or []
+ ]
+ return Wallet(
+ team_id=int(data.get("team_id", team_id)),
+ known=bool(data.get("known", False)),
+ has_ledger=bool(wallet.get("has_ledger", False)),
+ balance=wallet.get("balance"),
+ recent=recent,
+ )
+
+
+def add_credit(team_id: int, amount_usd: str, reason: str, idempotency_key: str) -> CreditResult:
+ url, token = _config()
+ try:
+ response = httpx.post(
+ f"{url}/internal/accounts/{team_id}/credits",
+ headers=_auth_headers(token, {IDEMPOTENCY_KEY_HEADER: idempotency_key}),
+ json={"amount_usd": amount_usd, "reason": reason},
+ timeout=INTERNAL_API_TIMEOUT_SECONDS,
+ trust_env=False,
+ )
+ except httpx.HTTPError as exc:
+ raise AIGatewayInternalError(f"credit request failed: {exc}") from exc
+
+ if response.status_code >= 400:
+ raise AIGatewayInternalError(_error_detail(response))
+
+ try:
+ data = response.json()
+ except ValueError as exc:
+ raise AIGatewayInternalError(f"credit response was not valid JSON: {exc}") from exc
+ # A 2xx with a partial body would otherwise coerce to empty strings and surface
+ # as "Added $ … New balance: $." in the admin. balance_usd may legitimately be
+ # "0", so presence-check it rather than truthiness.
+ if not data.get("entry_id") or data.get("balance_usd") is None:
+ raise AIGatewayInternalError("credit response missing required fields (entry_id/balance_usd)")
+ return CreditResult(
+ team_id=int(data.get("team_id", team_id)),
+ entry_id=data.get("entry_id", ""),
+ amount_usd=data.get("amount_usd", ""),
+ balance_usd=data.get("balance_usd", ""),
+ duplicate=bool(data.get("duplicate", False)),
+ )
+
+
+def _error_detail(response: httpx.Response) -> str:
+ try:
+ body: Any = response.json()
+ except ValueError:
+ return f"HTTP {response.status_code}"
+ if isinstance(body, dict):
+ return str(body.get("error") or body.get("message") or body)
+ return f"HTTP {response.status_code}"
diff --git a/posthog/llm/test_gateway_internal_client.py b/posthog/llm/test_gateway_internal_client.py
new file mode 100644
index 000000000000..e6c3357c2684
--- /dev/null
+++ b/posthog/llm/test_gateway_internal_client.py
@@ -0,0 +1,170 @@
+import pytest
+from unittest.mock import patch
+
+import httpx
+
+from posthog.llm.gateway_internal_client import (
+ IDEMPOTENCY_KEY_HEADER,
+ AIGatewayInternalError,
+ AIGatewayNotConfigured,
+ add_credit,
+ get_wallet,
+)
+
+
+def _response(status: int, payload: dict | None = None) -> httpx.Response:
+ return httpx.Response(status, json=payload or {}, request=httpx.Request("GET", "http://gw"))
+
+
+def _configured(mock_settings) -> None:
+ mock_settings.AI_GATEWAY_INTERNAL_URL = "http://gw"
+ mock_settings.AI_GATEWAY_INTERNAL_TOKEN = "tok"
+
+
+class TestGetWallet:
+ @patch("posthog.llm.gateway_internal_client.settings")
+ def test_parses_known_team_with_ledger_and_recent(self, mock_settings):
+ _configured(mock_settings)
+ payload = {
+ "team_id": 42,
+ "known": True,
+ "wallet": {"has_ledger": True, "balance": "9.500000"},
+ "recent": [
+ {
+ "when": "2026-06-01T00:00:00Z",
+ "kind": "topup",
+ "source": "funding",
+ "destination": "prepaid",
+ "amount": "10.000000",
+ "reference": "admin-topup:42:abc",
+ }
+ ],
+ }
+ with patch("posthog.llm.gateway_internal_client.httpx.get", return_value=_response(200, payload)) as mock_get:
+ wallet = get_wallet(42)
+
+ url = mock_get.call_args.args[0]
+ assert url == "http://gw/internal/admin/api/teams/42"
+ assert mock_get.call_args.kwargs["headers"]["Authorization"] == "Bearer tok"
+ assert wallet.team_id == 42
+ assert wallet.known is True
+ assert wallet.has_ledger is True
+ assert wallet.balance == "9.500000"
+ assert len(wallet.recent) == 1
+ assert wallet.recent[0].kind == "topup"
+ assert wallet.recent[0].amount == "10.000000"
+
+ @patch("posthog.llm.gateway_internal_client.settings")
+ def test_no_ledger_backend(self, mock_settings):
+ _configured(mock_settings)
+ payload = {"team_id": 42, "known": False, "wallet": {"has_ledger": False}}
+ with patch("posthog.llm.gateway_internal_client.httpx.get", return_value=_response(200, payload)):
+ wallet = get_wallet(42)
+ assert wallet.has_ledger is False
+ assert wallet.balance is None
+ assert wallet.recent == []
+
+ @patch("posthog.llm.gateway_internal_client.settings")
+ def test_unknown_team(self, mock_settings):
+ _configured(mock_settings)
+ payload = {"team_id": 42, "known": False, "wallet": {"has_ledger": True}}
+ with patch("posthog.llm.gateway_internal_client.httpx.get", return_value=_response(200, payload)):
+ wallet = get_wallet(42)
+ assert wallet.has_ledger is True
+ assert wallet.known is False
+ assert wallet.balance is None
+
+ @patch("posthog.llm.gateway_internal_client.settings")
+ def test_raises_on_http_error(self, mock_settings):
+ _configured(mock_settings)
+ with patch("posthog.llm.gateway_internal_client.httpx.get", return_value=_response(500)):
+ with pytest.raises(AIGatewayInternalError, match="wallet read failed"):
+ get_wallet(42)
+
+ @patch("posthog.llm.gateway_internal_client.settings")
+ def test_raises_on_non_json_success_body(self, mock_settings):
+ _configured(mock_settings)
+ non_json = httpx.Response(200, text="<html>not json</html>", request=httpx.Request("GET", "http://gw"))
+ with patch("posthog.llm.gateway_internal_client.httpx.get", return_value=non_json):
+ with pytest.raises(AIGatewayInternalError, match="wallet read failed"):
+ get_wallet(42)
+
+
+class TestAddCredit:
+ @patch("posthog.llm.gateway_internal_client.settings")
+ def test_posts_body_and_idempotency_header(self, mock_settings):
+ _configured(mock_settings)
+ payload = {
+ "team_id": 42,
+ "entry_id": "entry-1",
+ "amount_usd": "25.000000",
+ "balance_usd": "35.000000",
+ "duplicate": False,
+ }
+ with patch("posthog.llm.gateway_internal_client.httpx.post", return_value=_response(200, payload)) as mock_post:
+ result = add_credit(42, "25.00", "topping up", "key-123")
+
+ url = mock_post.call_args.args[0]
+ assert url == "http://gw/internal/accounts/42/credits"
+ assert mock_post.call_args.kwargs["json"] == {"amount_usd": "25.00", "reason": "topping up"}
+ assert mock_post.call_args.kwargs["headers"][IDEMPOTENCY_KEY_HEADER] == "key-123"
+ assert mock_post.call_args.kwargs["headers"]["Authorization"] == "Bearer tok"
+ assert result.entry_id == "entry-1"
+ assert result.balance_usd == "35.000000"
+ assert result.duplicate is False
+
+ @patch("posthog.llm.gateway_internal_client.settings")
+ def test_duplicate_replay(self, mock_settings):
+ _configured(mock_settings)
+ payload = {"team_id": 42, "entry_id": "entry-1", "amount_usd": "25", "balance_usd": "35", "duplicate": True}
+ with patch("posthog.llm.gateway_internal_client.httpx.post", return_value=_response(200, payload)):
+ result = add_credit(42, "25", "again", "key-123")
+ assert result.duplicate is True
+
+ @patch("posthog.llm.gateway_internal_client.settings")
+ def test_raises_with_error_detail_on_4xx(self, mock_settings):
+ _configured(mock_settings)
+ body = {"error": "amount_usd: must be positive"}
+ with patch("posthog.llm.gateway_internal_client.httpx.post", return_value=_response(400, body)):
+ with pytest.raises(AIGatewayInternalError, match="amount_usd: must be positive"):
+ add_credit(42, "-1", "bad", "key-123")
+
+ @patch("posthog.llm.gateway_internal_client.settings")
+ def test_raises_on_non_json_success_body(self, mock_settings):
+ _configured(mock_settings)
+ non_json = httpx.Response(200, text="<html>not json</html>", request=httpx.Request("POST", "http://gw"))
+ with patch("posthog.llm.gateway_internal_client.httpx.post", return_value=non_json):
+ with pytest.raises(AIGatewayInternalError, match="not valid JSON"):
+ add_credit(42, "10", "x", "key-123")
+
+ @patch("posthog.llm.gateway_internal_client.settings")
+ def test_raises_on_success_body_missing_required_fields(self, mock_settings):
+ _configured(mock_settings)
+ with patch("posthog.llm.gateway_internal_client.httpx.post", return_value=_response(200, {"team_id": 42})):
+ with pytest.raises(AIGatewayInternalError, match="missing required fields"):
+ add_credit(42, "10", "x", "key-123")
+
+ @patch("posthog.llm.gateway_internal_client.settings")
+ def test_accepts_zero_balance(self, mock_settings):
+ _configured(mock_settings)
+ body = {"team_id": 42, "entry_id": "e1", "amount_usd": "10", "balance_usd": "0", "duplicate": False}
+ with patch("posthog.llm.gateway_internal_client.httpx.post", return_value=_response(200, body)):
+ result = add_credit(42, "10", "x", "key-123")
+ assert result.balance_usd == "0"
+
+
+class TestNotConfigured:
+ @pytest.mark.parametrize("url,token", [("", "tok"), ("http://gw", ""), ("", "")])
+ @patch("posthog.llm.gateway_internal_client.settings")
+ def test_get_wallet_raises_when_unconfigured(self, mock_settings, url, token):
+ mock_settings.AI_GATEWAY_INTERNAL_URL = url
+ mock_settings.AI_GATEWAY_INTERNAL_TOKEN = token
+ with pytest.raises(AIGatewayNotConfigured):
+ get_wallet(42)
+
+ @patch("posthog.llm.gateway_internal_client.settings")
+ def test_add_credit_raises_when_unconfigured(self, mock_settings):
+ mock_settings.AI_GATEWAY_INTERNAL_URL = ""
+ mock_settings.AI_GATEWAY_INTERNAL_TOKEN = ""
+ with pytest.raises(AIGatewayNotConfigured):
+ add_credit(42, "10", "x", "key")
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index d11fa48aee5e..2d0d80d9190a 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -898,6 +898,11 @@ TOOLBAR_OAUTH_SCOPES = [
ELEMENT_STATS_DEFAULT_LIMIT = get_from_env("ELEMENT_STATS_DEFAULT_LIMIT", 50_000, type_cast=int)
+# AI gateway internal admin API (wallet read + credit top-up from Django admin).
+# Server-side shared secret; never expose the token to the browser.
+AI_GATEWAY_INTERNAL_URL = get_from_env("AI_GATEWAY_INTERNAL_URL", "")
+AI_GATEWAY_INTERNAL_TOKEN = get_from_env("AI_GATEWAY_INTERNAL_TOKEN", "")
+
# Sharing configuration settings
SHARING_TOKEN_GRACE_PERIOD_SECONDS = 60 * 5 # 5 minutes
diff --git a/posthog/templates/admin/posthog/team/add_ai_gateway_credit_form.html b/posthog/templates/admin/posthog/team/add_ai_gateway_credit_form.html
new file mode 100644
index 000000000000..a4baef910e4c
--- /dev/null
+++ b/posthog/templates/admin/posthog/team/add_ai_gateway_credit_form.html
@@ -0,0 +1,23 @@
+{% extends "admin/base_site.html" %}
+{% load i18n %}
+
+{% block content %}
+<p>Add prepaid credit to <strong>{{ team.name }}</strong>'s AI gateway wallet. This appends a top-up entry to the gateway ledger and increases the team's spendable balance immediately.</p>
+
+<form method="post" onsubmit="this.querySelector('input[type=submit]').disabled = true;">
+ {% csrf_token %}
+ <input type="hidden" name="form_nonce" value="{{ form_nonce }}" />
+ <div style="margin: 20px 0;">
+ <label for="amount_usd" style="display: block; margin-bottom: 5px; font-weight: bold;">Amount (USD):</label>
+ <input type="text" id="amount_usd" name="amount_usd" placeholder="e.g. 25.00" style="width: 200px; padding: 8px;" required />
+ </div>
+ <div style="margin: 20px 0;">
+ <label for="reason" style="display: block; margin-bottom: 5px; font-weight: bold;">Reason:</label>
+ <input type="text" id="reason" name="reason" style="width: 400px; padding: 8px;" required />
+ </div>
+ <div style="margin-top: 20px;">
+ <input type="submit" class="default" value="Add credit" style="padding: 10px 20px;" />
+ <a href="{% url 'admin:posthog_team_change' team.pk %}" style="margin-left: 10px;">Cancel</a>
+ </div>
+</form>
+{% endblock %}
diff --git a/posthog/templates/admin/posthog/team/ai_gateway_wallet.html b/posthog/templates/admin/posthog/team/ai_gateway_wallet.html
new file mode 100644
index 000000000000..e0eac41f99cc
--- /dev/null
+++ b/posthog/templates/admin/posthog/team/ai_gateway_wallet.html
@@ -0,0 +1,34 @@
+<div style="margin: 10px 0;">
+ {% if not wallet.has_ledger %}
+ <em>Ledger backend not wired in this region — no wallet to show.</em>
+ {% else %}
+ {% if wallet.known %}
+ <p style="margin: 0 0 8px;"><strong>Balance: ${{ wallet.balance }}</strong></p>
+ {% else %}
+ <p style="margin: 0 0 8px;"><em>No gateway account yet — balance is $0.00 until the first credit or spend.</em></p>
+ {% endif %}
+ <a class="button" href="{{ add_credit_url }}">Add credit</a>
+ {% if wallet.recent %}
+ <table style="margin-top: 12px; border-collapse: collapse;">
+ <thead>
+ <tr>
+ <th style="text-align: left; padding: 2px 12px 2px 0;">When</th>
+ <th style="text-align: left; padding: 2px 12px 2px 0;">Kind</th>
+ <th style="text-align: right; padding: 2px 12px 2px 0;">Amount</th>
+ <th style="text-align: left; padding: 2px 0;">Reference</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for entry in wallet.recent %}
+ <tr>
+ <td style="padding: 2px 12px 2px 0;">{{ entry.when }}</td>
+ <td style="padding: 2px 12px 2px 0;">{{ entry.kind }}</td>
+ <td style="padding: 2px 12px 2px 0; text-align: right;">{{ entry.amount }}</td>
+ <td style="padding: 2px 0;">{{ entry.reference }}</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ {% endif %}
+ {% endif %}
+</div>
diff --git a/posthog/templates/admin/posthog/team/ai_gateway_wallet_actions.html b/posthog/templates/admin/posthog/team/ai_gateway_wallet_actions.html
new file mode 100644
index 000000000000..3c495cc2fe2e
--- /dev/null
+++ b/posthog/templates/admin/posthog/team/ai_gateway_wallet_actions.html
@@ -0,0 +1,4 @@
+<div style="margin: 10px 0;">
+ <a class="button" href="{{ wallet_url }}" target="_blank" style="margin-right: 10px;">View wallet (balance + recent ledger)</a>
+ <a class="button" href="{{ add_credit_url }}">Add credit</a>
+</div>
diff --git a/posthog/templates/admin/posthog/team/ai_gateway_wallet_page.html b/posthog/templates/admin/posthog/team/ai_gateway_wallet_page.html
new file mode 100644
index 000000000000..26d3fa4f124b
--- /dev/null
+++ b/posthog/templates/admin/posthog/team/ai_gateway_wallet_page.html
@@ -0,0 +1,11 @@
+{% extends "admin/base_site.html" %}
+
+{% block content %}
+<h2>AI gateway wallet — {{ team.name }}</h2>
+{% if error %}
+ <p><em>({{ error }})</em></p>
+{% else %}
+ {% include "admin/posthog/team/ai_gateway_wallet.html" %}
+{% endif %}
+<p style="margin-top: 16px;"><a href="{% url 'admin:posthog_team_change' team.pk %}">← Back to team</a></p>
+{% endblock %}