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(gateway): add AI gateway usage page (#64511)

Richard Solomou0f5816ee395b
diff --git a/frontend/package.json b/frontend/package.json
index 06895d6ff67c..56f051625709 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -69,9 +69,10 @@
"@posthog/hedgehog-mode": "^0.0.52",
"@posthog/hogql-parser": "1.3.72",
"@posthog/hogvm": "workspace:*",
- "@posthog/icons": "^0.36.6",
+ "@posthog/icons": "^0.37.2",
"@posthog/products-access-control": "workspace:*",
"@posthog/products-actions": "workspace:*",
+ "@posthog/products-ai-gateway": "workspace:*",
"@posthog/products-ai-observability": "workspace:*",
"@posthog/products-alerts": "workspace:*",
"@posthog/products-annotations": "workspace:*",
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e63ae2708690..d99226685e4c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4600,6 +4600,14 @@ snapshots:
hash: v1.k794b7964.33000cd287cce76314b2d6a8005a0ed406396a50f43e18656a2ec8d33d33cc2b.rxsuAyw0uMSA4ouh1IhJClwrFxRGgOuKSvA5gpLxKk0
scenes-app-ai-observability-trace--without-content--light:
hash: v1.k794b7964.925af22228dd96b4c1bef5ccd9db87cacdbb8a9d9764f6845dbcf28cd510b73c._WVyYZM7SRur33YhrFxOYMN0NurSDNzWONIuDn5bsMw
+ scenes-app-aigateway--empty--dark:
+ hash: v1.k794b7964.9e5467f2092ba267f9bfb8adcdffe0d3b31cd6554e2cb65319f32602df9edb0c.FUdZ9vdoxd21tqhGoU2u8tvq-qQdlZkhh8jX8YhZs5U
+ scenes-app-aigateway--empty--light:
+ hash: v1.k794b7964.42ff5abd4d63a1a7c26347fcdc4873bd91c15018908d2be8a2e4a78995b37a79.72TfxeANzlgea6StJz9ARJesnyXRS9SBJhYTn9cClzk
+ scenes-app-aigateway--page--dark:
+ hash: v1.k794b7964.9e5467f2092ba267f9bfb8adcdffe0d3b31cd6554e2cb65319f32602df9edb0c.MKNf_pxiMAM_Oc88m0gAsJiwpde3Milvp7tNfGJKaLI
+ scenes-app-aigateway--page--light:
+ hash: v1.k794b7964.c75e47361d88cbc6bccf1080ec6ded4af7989ba6b9e0421e98e5d19e9ee8f70d.vGGS5YUSdED2wefcOe-Fs-UJQx9jzSXaJo6Qwk20vC4
scenes-app-annotations--annotations--dark:
hash: v1.k794b7964.839aa1c77337bde89878542d449c58c1080ddc767ff1c52ba73dc06683d5f797.VhGpyYpvz4Xkk8Kd7Y-_xPXGjLQ7lj_BXLfuTP5KSC4
scenes-app-annotations--annotations--light:
diff --git a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
index 2fad6c5f1c49..35fd9d68d860 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
@@ -30,6 +30,7 @@ import {
IconListCheck,
IconListTree,
IconLive,
+ IconAIGateway,
IconLlmAnalytics,
IconLlmPromptManagement,
IconMegaphone,
@@ -86,6 +87,10 @@ const iconTypes: Record<FileSystemIconType, { icon: JSX.Element; iconColor?: Fil
icon: <IconLlmAnalytics />,
iconColor: ['var(--color-product-llm-analytics-light)'],
},
+ ai_gateway: {
+ icon: <IconAIGateway />,
+ iconColor: ['var(--color-product-ai-gateway-light)', 'var(--color-product-ai-gateway-dark)'],
+ },
product_analytics: {
icon: <IconGraph />,
iconColor: ['var(--color-product-product-analytics-light)'],
diff --git a/frontend/src/lib/lemon-ui/icons/categories.ts b/frontend/src/lib/lemon-ui/icons/categories.ts
index 742fd8ce2ed4..8e946dcb97f5 100644
--- a/frontend/src/lib/lemon-ui/icons/categories.ts
+++ b/frontend/src/lib/lemon-ui/icons/categories.ts
@@ -23,6 +23,7 @@ export const OBJECTS = {
'IconPresent',
'IconMagicWand',
'IconAI',
+ 'IconAIGateway',
'IconMagic',
'IconHelmet',
'IconSpotlight',
@@ -230,6 +231,7 @@ export const ELEMENTS = {
'IconAsterisk',
'IconCircleDashed',
'IconX',
+ 'IconXCircle',
'IconAtSign',
'IconEllipsis',
'IconHide',
diff --git a/frontend/src/products.json b/frontend/src/products.json
index 7bd8d848c51e..326b3506e3e7 100644
--- a/frontend/src/products.json
+++ b/frontend/src/products.json
@@ -1,5 +1,12 @@
{
"products": [
+ {
+ "path": "AI gateway",
+ "category": "AI engineering",
+ "iconType": null,
+ "type": "ai_gateway",
+ "intents": ["ai_gateway"]
+ },
{
"path": "LLM analytics",
"category": "AI engineering",
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 565ebc66ab8e..04c348d54aad 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -55,6 +55,7 @@ export const productScenes: Record<string, () => Promise<any>> = {
Actions: () => import('../../products/actions/frontend/pages/Actions'),
Action: () => import('../../products/actions/frontend/pages/Action'),
NewAction: () => import('../../products/actions/frontend/pages/Action'),
+ AIGateway: () => import('../../products/ai_gateway/frontend/AIGatewayScene'),
AIObservability: () => import('../../products/ai_observability/frontend/AIObservabilityScene'),
AIObservabilityTrace: () => import('../../products/ai_observability/frontend/AIObservabilityTraceScene'),
AIObservabilitySession: () => import('../../products/ai_observability/frontend/AIObservabilitySessionScene'),
@@ -170,6 +171,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/data-management/actions/new': ['NewAction', 'actionNew'],
'/data-management/actions/:id': ['Action', 'action'],
'/data-management/actions/new/': ['NewAction', 'actionNew'],
+ '/ai-gateway': ['AIGateway', 'aiGateway'],
'/ai-observability/dashboard': ['AIObservability', 'aiObservabilityDashboard'],
'/ai-observability/generations': ['AIObservability', 'aiObservabilityGenerations'],
'/ai-observability/reviews': ['AIObservability', 'aiObservabilityReviews'],
@@ -471,6 +473,13 @@ export const productConfiguration: Record<string, any> = {
},
Action: { name: 'Action', projectBased: true, activityScope: 'Action', iconType: 'action' },
NewAction: { name: 'New Action', projectBased: true, activityScope: 'Action', iconType: 'action' },
+ AIGateway: {
+ projectBased: true,
+ name: 'AI gateway',
+ description: 'Every major LLM through one endpoint, billed at cost \u2014 usage tracked per project.',
+ layout: 'app-container',
+ iconType: 'ai_gateway',
+ },
AIObservability: {
projectBased: true,
name: 'AI observability',
@@ -849,6 +858,7 @@ export const productUrls = {
},
action: (id: string | number): string => `/data-management/actions/${id}`,
actions: (): string => '/data-management/actions',
+ aiGateway: (): string => '/ai-gateway',
aiObservabilityDashboard: (): string => '/ai-observability/dashboard',
aiObservabilityGenerations: (): string => '/ai-observability/generations',
aiObservabilityReviews: (): string => '/ai-observability/reviews',
@@ -1574,6 +1584,22 @@ export const getTreeItemsNew = (): FileSystemImport[] => [
/** This const is auto-generated, as is the whole file */
export const getTreeItemsProducts = (): FileSystemImport[] => [
+ {
+ path: 'AI gateway',
+ intents: [ProductKey.AI_GATEWAY],
+ category: ProductItemCategory.AI_ENGINEERING,
+ type: 'ai_gateway',
+ iconType: 'ai_gateway' as FileSystemIconType,
+ iconColor: [
+ 'var(--color-product-ai-gateway-light)',
+ 'var(--color-product-ai-gateway-dark)',
+ ] as FileSystemIconColor,
+ href: urls.aiGateway(),
+ flag: FEATURE_FLAGS.AI_GATEWAY,
+ tags: ['alpha'],
+ sceneKey: 'AIGateway',
+ sceneKeys: ['AIGateway'],
+ },
{
path: 'Business knowledge',
intents: [ProductKey.CONVERSATIONS],
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index fbcde0633618..10d764b3da7b 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -21505,6 +21505,7 @@
"default_icon_type",
"dashboard",
"llm_analytics",
+ "ai_gateway",
"product_analytics",
"revenue_analytics",
"revenue_analytics_metadata",
@@ -30448,6 +30449,7 @@
"ProductKey": {
"enum": [
"actions",
+ "ai_gateway",
"llm_analytics",
"alerts",
"annotations",
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index bc7ecaf9520b..dd07c04ec403 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -3581,6 +3581,7 @@ export type FileSystemIconType =
| 'default_icon_type'
| 'dashboard'
| 'llm_analytics'
+ | 'ai_gateway'
| 'product_analytics'
| 'revenue_analytics'
| 'revenue_analytics_metadata'
@@ -7379,6 +7380,7 @@ export interface UserProductListItem {
// Keep this in alphabetical order if you wanna maintain Rafa's sanity
export enum ProductKey {
ACTIONS = 'actions',
+ AI_GATEWAY = 'ai_gateway',
AI_OBSERVABILITY = 'llm_analytics',
ALERTS = 'alerts',
ANNOTATIONS = 'annotations',
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index 7c9862a543ae..5630a7388ae8 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -12,6 +12,7 @@ export enum Scene {
AdvancedActivityLogs = 'AdvancedActivityLogs',
AgenticAccountMismatch = 'AgenticAccountMismatch',
AgenticAuthorize = 'AgenticAuthorize',
+ AIGateway = 'AIGateway',
Annotations = 'Annotations',
Approval = 'Approval',
AsyncMigrations = 'AsyncMigrations',
diff --git a/frontend/src/styles/base.scss b/frontend/src/styles/base.scss
index de5859f7f5e3..6fb68a12d452 100644
--- a/frontend/src/styles/base.scss
+++ b/frontend/src/styles/base.scss
@@ -335,6 +335,8 @@
--color-product-llm-datasets-light: rgb(124 58 237);
--color-product-llm-evaluations-light: rgb(167 139 250);
--color-product-llm-prompts-light: rgb(196 181 253);
+ --color-product-ai-gateway-light: rgb(99 102 241);
+ --color-product-ai-gateway-dark: rgb(129 140 248);
--color-product-links-light: rgb(143 7 255);
--color-product-tracing-light: rgb(6 182 212);
--color-product-tracing-dark: rgb(34 211 238);
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index d7785e612e49..d2fd29850e10 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4457,6 +4457,8 @@ export interface PreflightStatus {
site_url?: string
instance_preferences?: InstancePreferencesInterface
buffer_conversion_seconds?: number
+ /** Public base URL of the LLM gateway, for per-gateway endpoint examples. Null until configured. */
+ ai_gateway_url?: string | null
object_storage: boolean
public_egress_ip_addresses?: string[]
dev_disable_navigation_hooks?: boolean
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 848f7bc6adae..c76f71ee7bb7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -607,14 +607,17 @@ importers:
specifier: workspace:*
version: link:../common/hogvm/typescript
'@posthog/icons':
- specifier: ^0.36.6
+ specifier: ^0.37.2
'@posthog/products-access-control':
specifier: workspace:*
version: link:../products/access_control
'@posthog/products-actions':
specifier: workspace:*
version: link:../products/actions
+ '@posthog/products-ai-gateway':
+ specifier: workspace:*
+ version: link:../products/ai_gateway
'@posthog/products-ai-observability':
specifier: workspace:*
version: link:../products/ai_observability
@@ -2533,6 +2536,43 @@ importers:
specifier: 6.0.3
version: 6.0.3
+ products/ai_gateway:
+ dependencies:
+ '@posthog/icons':
+ specifier: '*'
+ '@storybook/react':
+ specifier: 'catalog:'
+ '@types/react':
+ specifier: 18.3.27
+ version: 18.3.27
+ clsx:
+ specifier: '*'
+ version: 2.1.1
+ kea:
+ specifier: 'catalog:'
+ version: 4.0.0-pre.5([email protected])
+ kea-forms:
+ specifier: 'catalog:'
+ kea-loaders:
+ specifier: 'catalog:'
+ kea-router:
+ specifier: 'catalog:'
+ posthog-js:
+ specifier: 'catalog:'
+ version: 1.391.6
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
+ devDependencies:
+ kea-test-utils:
+ specifier: 'catalog:'
+
products/ai_observability:
dependencies:
'@posthog/icons':
@@ -9526,6 +9566,12 @@ packages:
react: 18.3.1
react-dom: 18.3.1
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-nVgnFtpctBpMa3quVfHE7XJXVrH4D8wkwwdUM9KdgQa8VX9k+pjXbfu0nvTFFNrqQDlbFjXpr21EYMYOLzCYhw==}
+ peerDependencies:
+ react: 18.3.1
+ react-dom: 18.3.1
+
'@posthog/[email protected]':
resolution: {integrity: sha512-SJaquP2UGsfOx33d7SssxNvUTfDT5VWWBEzWyHvJXaFrHNZd3ZeRrHLzsETXjhJO3ZcsVdoJD+tm27B6Qe5GuQ==}
peerDependencies:
@@ -29769,6 +29815,11 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
+ dependencies:
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+
dependencies:
diff --git a/posthog/api/test/test_preflight.py b/posthog/api/test/test_preflight.py
index 1a01bc164b12..88f2c9c215d2 100644
--- a/posthog/api/test/test_preflight.py
+++ b/posthog/api/test/test_preflight.py
@@ -6,6 +6,7 @@ import pytest
from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_queries
from unittest.mock import patch
+from django.conf import settings
from django.test import override_settings
from django.utils import timezone
@@ -67,6 +68,7 @@ class TestPreflight(APIBaseTest, QueryMatchingTest):
"instance_preferences": {"debug_queries": True, "disable_paid_fs": False},
"object_storage": False,
"buffer_conversion_seconds": 60,
+ "ai_gateway_url": settings.AI_GATEWAY_PUBLIC_URL or None,
# we calculate this here because otherwise it is non-deterministic when running locally
# it can be overridden in tests by passing in options
"openai_available": bool(os.environ.get("OPENAI_API_KEY")),
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 50457d2424ae..ba220c1864ed 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -1817,6 +1817,7 @@ class FileSystemIconType(StrEnum):
DEFAULT_ICON_TYPE = "default_icon_type"
DASHBOARD = "dashboard"
LLM_ANALYTICS = "llm_analytics"
+ AI_GATEWAY = "ai_gateway"
PRODUCT_ANALYTICS = "product_analytics"
REVENUE_ANALYTICS = "revenue_analytics"
REVENUE_ANALYTICS_METADATA = "revenue_analytics_metadata"
@@ -2667,6 +2668,7 @@ class ProductItemCategory(StrEnum):
class ProductKey(StrEnum):
ACTIONS = "actions"
+ AI_GATEWAY = "ai_gateway"
LLM_ANALYTICS = "llm_analytics"
ALERTS = "alerts"
ANNOTATIONS = "annotations"
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index 823cd2596162..96d1828077e8 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -580,6 +580,12 @@ AI_GATEWAY_REDIS_URL = os.getenv("AI_GATEWAY_REDIS_URL", "redis://localhost:6381
TASKS_REDIS_URL = os.getenv("TASKS_REDIS_URL", None)
+# Public base URL of the LLM gateway, surfaced in the app's per-gateway endpoint
+# examples (…/v1/<slug>/messages). Deployment-specific; empty until configured,
+# except in local dev where it defaults to the gateway's local listen addr
+# (AI_GATEWAY_LISTEN_ADDR=:8080 in PostHog/ai-gateway).
+AI_GATEWAY_PUBLIC_URL = os.getenv("AI_GATEWAY_PUBLIC_URL", "http://localhost:8080" if DEBUG else "")
+
# Rust feature flags service URL
# This is used to proxy flag evaluation requests to the Rust feature flags service
FEATURE_FLAGS_SERVICE_URL = os.getenv("FEATURE_FLAGS_SERVICE_URL", "http://localhost:3001")
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index ad64ac03bab4..45f7f5a23b2d 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -39,6 +39,7 @@ PRODUCTS_APPS = [
"products.revenue_analytics.backend.apps.RevenueAnalyticsConfig",
"products.user_interviews.backend.apps.UserInterviewsConfig",
"products.ai_observability.backend.apps.AIObservabilityConfig",
+ "products.ai_gateway.backend.apps.AIGatewayConfig",
"products.llm_analytics.backend.apps.LlmAnalyticsConfig",
"products.skills.backend.apps.SkillsConfig",
"products.endpoints.backend.apps.EndpointsConfig",
diff --git a/posthog/views.py b/posthog/views.py
index 26645d77379d..d52380509bac 100644
--- a/posthog/views.py
+++ b/posthog/views.py
@@ -252,6 +252,7 @@ def preflight_check(request: HttpRequest) -> JsonResponse:
"site_url": settings.SITE_URL,
"instance_preferences": settings.INSTANCE_PREFERENCES,
"buffer_conversion_seconds": settings.BUFFER_CONVERSION_SECONDS,
+ "ai_gateway_url": settings.AI_GATEWAY_PUBLIC_URL or None,
}
return JsonResponse(response)
diff --git a/products/ai_gateway/__init__.py b/products/ai_gateway/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/ai_gateway/backend/__init__.py b/products/ai_gateway/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/ai_gateway/backend/apps.py b/products/ai_gateway/backend/apps.py
new file mode 100644
index 000000000000..17b48460c4db
--- /dev/null
+++ b/products/ai_gateway/backend/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class AIGatewayConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "products.ai_gateway.backend"
+ label = "ai_gateway"
diff --git a/products/ai_gateway/backend/routes.py b/products/ai_gateway/backend/routes.py
new file mode 100644
index 000000000000..1167b7c3addc
--- /dev/null
+++ b/products/ai_gateway/backend/routes.py
@@ -0,0 +1,7 @@
+from posthog.api.routing import RouterRegistry
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ # AI gateway has no per-team management resource: a project secret key with the
+ # llm_gateway:read scope reaches the gateway directly, and usage is read from events.
+ pass
diff --git a/products/ai_gateway/backend/test/__init__.py b/products/ai_gateway/backend/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/ai_gateway/backend/test/test_apps.py b/products/ai_gateway/backend/test/test_apps.py
new file mode 100644
index 000000000000..8930b5593670
--- /dev/null
+++ b/products/ai_gateway/backend/test/test_apps.py
@@ -0,0 +1,6 @@
+from django.apps import apps
+
+
+def test_ai_gateway_app_is_registered() -> None:
+ config = apps.get_app_config("ai_gateway")
+ assert config.name == "products.ai_gateway.backend"
diff --git a/products/ai_gateway/frontend/AIGateway.stories.tsx b/products/ai_gateway/frontend/AIGateway.stories.tsx
new file mode 100644
index 000000000000..1d0c7c88cde8
--- /dev/null
+++ b/products/ai_gateway/frontend/AIGateway.stories.tsx
@@ -0,0 +1,66 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { App } from 'scenes/App'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator } from '~/mocks/browser'
+
+// The scene fires two HogQL queries (by-model breakdown, spend-by-day) at the same
+// endpoint, so branch the mock on the query body to return the right shape for each.
+const queryDecorator = (hasData: boolean): ReturnType<typeof mswDecorator> =>
+ mswDecorator({
+ post: {
+ 'api/environments/:team_id/query/': async ({ request }) => {
+ const body = (await request.json()) as { query?: { query?: string } }
+ const hogql = String(body?.query?.query ?? '')
+ if (hogql.includes('GROUP BY model')) {
+ return [
+ 200,
+ {
+ results: hasData
+ ? [
+ ['gpt-5-mini', 96, 60000, 41000, 9.1],
+ ['claude-sonnet-4.6', 32, 20000, 14000, 3.24],
+ ]
+ : [],
+ columns: ['model', 'requests', 'input_tokens', 'output_tokens', 'cost_usd'],
+ },
+ ]
+ }
+ return [
+ 200,
+ {
+ results: hasData
+ ? [
+ ['2024-07-01 00:00:00', 4.2],
+ ['2024-07-05 00:00:00', 8.14],
+ ]
+ : [],
+ columns: ['day', 'cost_usd'],
+ },
+ ]
+ },
+ },
+ })
+
+const meta: Meta = {
+ component: App,
+ title: 'Scenes-App/AIGateway',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2024-07-09',
+ pageUrl: urls.aiGateway(),
+ featureFlags: [FEATURE_FLAGS.AI_GATEWAY],
+ },
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+// Team with usage: metrics, spend trend, and per-model breakdown populated.
+export const Page: Story = { decorators: [queryDecorator(true)] }
+
+// Team that hasn't used the gateway yet: the same dashboard, all zeroed out.
+export const Empty: Story = { decorators: [queryDecorator(false)] }
diff --git a/products/ai_gateway/frontend/AIGatewayScene.tsx b/products/ai_gateway/frontend/AIGatewayScene.tsx
new file mode 100644
index 000000000000..8c781f6815ef
--- /dev/null
+++ b/products/ai_gateway/frontend/AIGatewayScene.tsx
@@ -0,0 +1,248 @@
+import clsx from 'clsx'
+import { useActions, useValues } from 'kea'
+import { ComponentType } from 'react'
+
+import { LemonSegmentedButton, LemonTabs } from '@posthog/lemon-ui'
+
+import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
+import { RobotHog } from 'lib/components/hedgehogs'
+import { NotFound } from 'lib/components/NotFound'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { Link } from 'lib/lemon-ui/Link'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { AnthropicLogo } from 'scenes/onboarding/legacy/sdks/logos/AnthropicLogo'
+import { OpenAILogo } from 'scenes/onboarding/legacy/sdks/logos/OpenAILogo'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneSection } from '~/layout/scenes/components/SceneSection'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { ProductKey } from '~/queries/schema/schema-general'
+
+import { aiGatewayLogic, EndpointProvider, EndpointTab } from './aiGatewayLogic'
+import { GatewayBalanceCard, GatewayTopUpModal } from './GatewayTopUp'
+import { ModelBreakdownTable, SpendChart, UsageMetrics } from './gatewayUsage'
+
+const AI_GATEWAY_DESCRIPTION =
+ 'One endpoint for every major LLM, billed at cost — no markup on tokens. Point your app at the gateway and ' +
+ 'PostHog tracks its usage, cost, and spend for you. Any project secret key with the llm_gateway:read scope ' +
+ 'can call it, and you can add or rotate keys anytime with no downtime.'
+
+export const scene: SceneExport = {
+ component: AIGatewayScene,
+ logic: aiGatewayLogic,
+ productKey: ProductKey.AI_GATEWAY,
+}
+
+export function AIGatewayScene(): JSX.Element {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { usage, spendChart, spendSeriesLoading, modelUsage, modelUsageLoading, hasUsage } = useValues(aiGatewayLogic)
+
+ if (!featureFlags[FEATURE_FLAGS.AI_GATEWAY]) {
+ return <NotFound object="page" />
+ }
+
+ // Until the model breakdown resolves we can't tell a brand-new team from an active one, so keep showing
+ // the dashboard (with skeletons) and only fall back to the intro once we know there's genuinely no usage.
+ const isEmpty = !modelUsageLoading && !hasUsage
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name="AI gateway"
+ description="Every major LLM through one endpoint, billed at cost."
+ resourceType={{ type: 'ai_gateway' }}
+ />
+ {isEmpty ? (
+ <GatewayIntro />
+ ) : (
+ <>
+ <SceneSection title="Usage" description="Last 30 days" titleSize="sm">
+ <div className="flex gap-2 flex-wrap">
+ <UsageMetrics usage={usage} loading={modelUsageLoading} />
+ <GatewayBalanceCard />
+ </div>
+ <SpendChart data={spendChart.data} labels={spendChart.labels} loading={spendSeriesLoading} />
+ </SceneSection>
+ <SceneSection
+ title="By model"
+ description="Spend and tokens per model, last 30 days"
+ titleSize="sm"
+ >
+ <ModelBreakdownTable rows={modelUsage} loading={modelUsageLoading} />
+ </SceneSection>
+ </>
+ )}
+ <SceneSection
+ title="Connect your app"
+ titleSize="sm"
+ description={
+ <>
+ Every request is tracked in <Link to={urls.aiObservabilityDashboard()}>AI observability</Link>{' '}
+ with no SDK instrumentation needed. Already sending generations through a PostHog LLM SDK?
+ Switch back to the official provider packages so each one is counted once.
+ </>
+ }
+ >
+ <GatewayEndpoint />
+ </SceneSection>
+ {!isEmpty && <GatewayTopUpModal />}
+ </SceneContent>
+ )
+}
+
+// Shown until a team sends its first request, where the zeroed-out dashboard would otherwise read as broken.
+function GatewayIntro(): JSX.Element {
+ return (
+ <div className="border-2 border-dashed border-primary w-full p-6 rounded flex items-center gap-6">
+ <RobotHog className="w-24 hidden md:block shrink-0" />
+ <div className="flex-shrink">
+ <h3 className="m-0">No gateway usage yet</h3>
+ <p className="ml-0 mt-1 mb-0 text-secondary">{AI_GATEWAY_DESCRIPTION}</p>
+ </div>
+ </div>
+ )
+}
+
+function GatewayEndpoint(): JSX.Element {
+ const { preflight } = useValues(preflightLogic)
+ const { endpointTab, endpointProvider } = useValues(aiGatewayLogic)
+ const { setEndpointTab, setEndpointProvider } = useActions(aiGatewayLogic)
+
+ if (!preflight?.ai_gateway_url) {
+ return (
+ <p className="text-secondary m-0">
+ Set <code>AI_GATEWAY_PUBLIC_URL</code> to show the gateway's endpoint and code examples.
+ </p>
+ )
+ }
+
+ const gatewayBase = preflight.ai_gateway_url.replace(/\/$/, '')
+ const key = '<your phs_… project secret key with the llm_gateway:read scope>'
+
+ // provider → language → snippet. The OpenAI SDK appends "chat/completions" to base + "/v1";
+ // the Anthropic SDK appends "/v1/messages" to the gateway base.
+ const snippets: Record<EndpointProvider, Record<EndpointTab, { language: Language; code: string }>> = {
+ openai: {
+ typescript: {
+ language: Language.TypeScript,
+ code: `import OpenAI from 'openai'
+
+const client = new OpenAI({
+ baseURL: '${gatewayBase}/v1',
+ apiKey: '${key}',
+})
+const response = await client.chat.completions.create({
+ model: 'gpt-5-mini',
+ messages: [{ role: 'user', content: 'Hello' }],
+})`,
+ },
+ python: {
+ language: Language.Python,
+ code: `from openai import OpenAI
+
+client = OpenAI(
+ base_url="${gatewayBase}/v1",
+ api_key="${key}",
+)
+client.chat.completions.create(
+ model="gpt-5-mini",
+ messages=[{"role": "user", "content": "Hello"}],
+)`,
+ },
+ curl: {
+ language: Language.Bash,
+ code: `curl ${gatewayBase}/v1/chat/completions \\
+ -H "Authorization: Bearer $POSTHOG_PROJECT_SECRET_KEY" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "model": "gpt-5-mini",
+ "messages": [{"role": "user", "content": "Hello"}]
+ }'`,
+ },
+ },
+ anthropic: {
+ typescript: {
+ language: Language.TypeScript,
+ code: `import Anthropic from '@anthropic-ai/sdk'
+
+const client = new Anthropic({
+ baseURL: '${gatewayBase}',
+ authToken: '${key}', // sets the Bearer header
+})
+const message = await client.messages.create({
+ model: 'claude-sonnet-4.6',
+ max_tokens: 512,
+ messages: [{ role: 'user', content: 'Hello' }],
+})`,
+ },
+ python: {
+ language: Language.Python,
+ code: `from anthropic import Anthropic
+
+client = Anthropic(
+ base_url="${gatewayBase}",
+ auth_token="${key}", # sets the Bearer header
+)
+client.messages.create(
+ model="claude-sonnet-4.6",
+ max_tokens=512,
+ messages=[{"role": "user", "content": "Hello"}],
+)`,
+ },
+ curl: {
+ language: Language.Bash,
+ code: `curl ${gatewayBase}/v1/messages \\
+ -H "Authorization: Bearer $POSTHOG_PROJECT_SECRET_KEY" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "model": "claude-sonnet-4.6",
+ "max_tokens": 512,
+ "messages": [{"role": "user", "content": "Hello"}]
+ }'`,
+ },
+ },
+ }
+
+ const languages: { key: EndpointTab; label: string }[] = [
+ { key: 'typescript', label: 'TypeScript' },
+ { key: 'python', label: 'Python' },
+ { key: 'curl', label: 'cURL' },
+ ]
+
+ // The logos are white in dark mode, but the selected segment has a light
+ // background — force the selected one's mark dark so it stays visible.
+ const providerIcon = (provider: EndpointProvider, Logo: ComponentType): JSX.Element => (
+ <span className={clsx('flex [&>svg]:size-4', endpointProvider === provider && '[&_path]:dark:fill-black')}>
+ <Logo />
+ </span>
+ )
+
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonSegmentedButton
+ size="small"
+ value={endpointProvider}
+ onChange={setEndpointProvider}
+ options={[
+ { value: 'openai', label: 'OpenAI', icon: providerIcon('openai', OpenAILogo) },
+ { value: 'anthropic', label: 'Anthropic', icon: providerIcon('anthropic', AnthropicLogo) },
+ ]}
+ />
+ <LemonTabs
+ activeKey={endpointTab}
+ onChange={setEndpointTab}
+ tabs={languages.map(({ key: langKey, label }) => {
+ const snippet = snippets[endpointProvider][langKey]
+ return {
+ key: langKey,
+ label,
+ content: <CodeSnippet language={snippet.language}>{snippet.code}</CodeSnippet>,
+ }
+ })}
+ />
+ </div>
+ )
+}
diff --git a/products/ai_gateway/frontend/GatewayTopUp.tsx b/products/ai_gateway/frontend/GatewayTopUp.tsx
new file mode 100644
index 000000000000..00227706e5f5
--- /dev/null
+++ b/products/ai_gateway/frontend/GatewayTopUp.tsx
@@ -0,0 +1,80 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonInput, LemonModal, LemonTag } from '@posthog/lemon-ui'
+
+import { humanFriendlyCurrency } from 'lib/utils/numbers'
+
+import { aiGatewayLogic } from './aiGatewayLogic'
+
+const TOP_UP_PRESETS_USD = [25, 50, 100, 250]
+
+// The gateway has no balance endpoint yet (products/ai_gateway/backend/routes.py is an empty
+// stub), so the balance is shown as a Preview placeholder until that lands.
+export function GatewayBalanceCard(): JSX.Element {
+ const { openTopUpModal } = useActions(aiGatewayLogic)
+
+ return (
+ <div className="border rounded p-4 min-w-48 flex-1 flex items-center justify-between gap-4">
+ <div>
+ <div className="text-secondary text-xs uppercase flex items-center gap-1.5">
+ Balance
+ <LemonTag type="warning">Preview</LemonTag>
+ </div>
+ <div className="text-2xl font-semibold">—</div>
+ </div>
+ <LemonButton type="primary" onClick={openTopUpModal}>
+ Top up
+ </LemonButton>
+ </div>
+ )
+}
+
+export function GatewayTopUpModal(): JSX.Element {
+ const { isTopUpModalOpen, topUpAmountUsd } = useValues(aiGatewayLogic)
+ const { closeTopUpModal, setTopUpAmount, confirmTopUp } = useActions(aiGatewayLogic)
+
+ return (
+ <LemonModal
+ isOpen={isTopUpModalOpen}
+ onClose={closeTopUpModal}
+ title="Top up balance"
+ description="Add funds to cover gateway usage — you're billed at cost, no markup on tokens."
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={closeTopUpModal}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={confirmTopUp}
+ disabledReason={topUpAmountUsd <= 0 ? 'Enter an amount' : undefined}
+ >
+ Top up {humanFriendlyCurrency(topUpAmountUsd)}
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="flex flex-col gap-3 max-w-md">
+ <LemonBanner type="info">Preview only — billing isn't wired up yet.</LemonBanner>
+ <div className="flex gap-2 flex-wrap">
+ {TOP_UP_PRESETS_USD.map((amount) => (
+ <LemonButton
+ key={amount}
+ type={topUpAmountUsd === amount ? 'primary' : 'secondary'}
+ onClick={() => setTopUpAmount(amount)}
+ >
+ {humanFriendlyCurrency(amount, 0)}
+ </LemonButton>
+ ))}
+ </div>
+ <LemonInput
+ type="number"
+ value={topUpAmountUsd}
+ onChange={(value) => setTopUpAmount(value ?? 0)}
+ prefix={<span className="text-secondary">$</span>}
+ min={0}
+ />
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/ai_gateway/frontend/aiGatewayLogic.test.ts b/products/ai_gateway/frontend/aiGatewayLogic.test.ts
new file mode 100644
index 000000000000..0beddf6db508
--- /dev/null
+++ b/products/ai_gateway/frontend/aiGatewayLogic.test.ts
@@ -0,0 +1,58 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { aiGatewayLogic } from './aiGatewayLogic'
+import { fetchGatewayUsageByModel } from './gatewayUsage'
+
+jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({ lemonToast: { info: jest.fn(), error: jest.fn() } }))
+
+jest.mock('./gatewayUsage', () => ({
+ fetchGatewaySpendByDay: jest.fn().mockResolvedValue([{ day: '2024-07-01', costUsd: 1.5 }]),
+ fetchGatewayUsageByModel: jest
+ .fn()
+ .mockResolvedValue([{ model: 'gpt-5-mini', requests: 12, inputTokens: 100, outputTokens: 200, costUsd: 3.5 }]),
+ buildSpendChartData: jest.fn().mockReturnValue({ data: [], labels: [] }),
+}))
+
+describe('aiGatewayLogic', () => {
+ let logic: ReturnType<typeof aiGatewayLogic.build>
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ initKeaTests()
+ logic = aiGatewayLogic()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ it('loads spend series and model usage on mount, deriving usage totals from the breakdown', async () => {
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadSpendSeriesSuccess', 'loadModelUsageSuccess'])
+ expect(logic.values.usage).toEqual({ requests: 12, inputTokens: 100, outputTokens: 200, costUsd: 3.5 })
+ expect(logic.values.modelUsage).toEqual([
+ { model: 'gpt-5-mini', requests: 12, inputTokens: 100, outputTokens: 200, costUsd: 3.5 },
+ ])
+ expect(logic.values.hasUsage).toBe(true)
+ })
+
+ it('reports no usage for a team that has never called the gateway', async () => {
+ jest.mocked(fetchGatewayUsageByModel).mockResolvedValueOnce([])
+
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadModelUsageSuccess'])
+ expect(logic.values.hasUsage).toBe(false)
+ })
+
+ it('confirming a top up closes the modal', async () => {
+ logic.mount()
+ await expectLogic(logic, () => {
+ logic.actions.setTopUpAmount(100)
+ logic.actions.openTopUpModal()
+ }).toMatchValues({ isTopUpModalOpen: true, topUpAmountUsd: 100 })
+
+ await expectLogic(logic, () => logic.actions.confirmTopUp()).toMatchValues({ isTopUpModalOpen: false })
+ })
+})
diff --git a/products/ai_gateway/frontend/aiGatewayLogic.ts b/products/ai_gateway/frontend/aiGatewayLogic.ts
new file mode 100644
index 000000000000..5f28ad031c67
--- /dev/null
+++ b/products/ai_gateway/frontend/aiGatewayLogic.ts
@@ -0,0 +1,87 @@
+import { actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { humanFriendlyCurrency } from 'lib/utils/numbers'
+import { teamLogic } from 'scenes/teamLogic'
+
+import type { aiGatewayLogicType } from './aiGatewayLogicType'
+import {
+ buildSpendChartData,
+ fetchGatewaySpendByDay,
+ fetchGatewayUsageByModel,
+ GatewayModelUsage,
+ GatewaySpendPoint,
+ GatewayUsage,
+} from './gatewayUsage'
+
+export type EndpointTab = 'typescript' | 'python' | 'curl'
+export type EndpointProvider = 'openai' | 'anthropic'
+
+export const aiGatewayLogic = kea<aiGatewayLogicType>([
+ path(['products', 'ai_gateway', 'frontend', 'aiGatewayLogic']),
+ actions({
+ setEndpointTab: (tab: EndpointTab) => ({ tab }),
+ setEndpointProvider: (provider: EndpointProvider) => ({ provider }),
+ openTopUpModal: true,
+ closeTopUpModal: true,
+ setTopUpAmount: (amountUsd: number) => ({ amountUsd }),
+ confirmTopUp: true,
+ }),
+ reducers({
+ endpointTab: ['typescript' as EndpointTab, { setEndpointTab: (_, { tab }) => tab }],
+ endpointProvider: ['openai' as EndpointProvider, { setEndpointProvider: (_, { provider }) => provider }],
+ isTopUpModalOpen: [false, { openTopUpModal: () => true, closeTopUpModal: () => false }],
+ topUpAmountUsd: [25, { setTopUpAmount: (_, { amountUsd }) => amountUsd }],
+ }),
+ loaders(() => ({
+ spendSeries: [
+ [] as GatewaySpendPoint[],
+ {
+ loadSpendSeries: async () => await fetchGatewaySpendByDay(),
+ },
+ ],
+ modelUsage: [
+ [] as GatewayModelUsage[],
+ {
+ loadModelUsage: async () => await fetchGatewayUsageByModel(),
+ },
+ ],
+ })),
+ selectors({
+ usage: [
+ (s) => [s.modelUsage],
+ (modelUsage): GatewayUsage =>
+ modelUsage.reduce(
+ (acc, model) => ({
+ requests: acc.requests + model.requests,
+ inputTokens: acc.inputTokens + model.inputTokens,
+ outputTokens: acc.outputTokens + model.outputTokens,
+ costUsd: acc.costUsd + model.costUsd,
+ }),
+ { requests: 0, inputTokens: 0, outputTokens: 0, costUsd: 0 }
+ ),
+ ],
+ spendChart: [
+ (s) => [s.spendSeries, teamLogic.selectors.timezone],
+ (spendSeries, timezone): { data: number[]; labels: string[] } => buildSpendChartData(spendSeries, timezone),
+ ],
+ hasUsage: [(s) => [s.modelUsage], (modelUsage): boolean => modelUsage.length > 0],
+ }),
+ listeners(({ values, actions }) => ({
+ confirmTopUp: () => {
+ lemonToast.info(`Top up of ${humanFriendlyCurrency(values.topUpAmountUsd)} is mocked for now.`)
+ actions.closeTopUpModal()
+ },
+ loadSpendSeriesFailure: ({ error }) => {
+ lemonToast.error(`Couldn't load gateway spend: ${error}`)
+ },
+ loadModelUsageFailure: ({ error }) => {
+ lemonToast.error(`Couldn't load gateway usage: ${error}`)
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadSpendSeries()
+ actions.loadModelUsage()
+ }),
+])
diff --git a/products/ai_gateway/frontend/gatewayUsage.tsx b/products/ai_gateway/frontend/gatewayUsage.tsx
new file mode 100644
index 000000000000..341d780bdf91
--- /dev/null
+++ b/products/ai_gateway/frontend/gatewayUsage.tsx
@@ -0,0 +1,196 @@
+import { LemonSkeleton, LemonTable } from '@posthog/lemon-ui'
+
+import api from 'lib/api'
+import { Sparkline } from 'lib/components/Sparkline'
+import { dayjs, dayjsNowInTimezone } from 'lib/dayjs'
+import { humanFriendlyCurrency, humanFriendlyNumber } from 'lib/utils/numbers'
+
+import { HogQLQuery, NodeKind } from '~/queries/schema/schema-general'
+
+const USAGE_WINDOW_DAYS = 30
+
+// Gateway usage is read from $ai_generation events the gateway stamps with $ai_gateway = true,
+// which separates them from SDK-emitted LLM events that share the $ai_generation event name.
+// The events table is team-scoped and api.query resolves the team from the request context.
+const GATEWAY_EVENTS_WHERE = `event = '$ai_generation' AND properties.$ai_gateway = true AND timestamp >= now() - INTERVAL ${USAGE_WINDOW_DAYS} DAY`
+
+export interface GatewayUsage {
+ requests: number
+ inputTokens: number
+ outputTokens: number
+ costUsd: number
+}
+
+export interface GatewaySpendPoint {
+ day: string
+ costUsd: number
+}
+
+export interface GatewayModelUsage {
+ model: string
+ requests: number
+ inputTokens: number
+ outputTokens: number
+ costUsd: number
+}
+
+export async function fetchGatewaySpendByDay(): Promise<GatewaySpendPoint[]> {
+ const query: HogQLQuery = {
+ kind: NodeKind.HogQLQuery,
+ query: `
+ SELECT
+ toStartOfDay(timestamp) AS day,
+ round(sum(toFloat(properties.$ai_total_cost_usd)), 4) AS cost_usd
+ FROM events
+ WHERE ${GATEWAY_EVENTS_WHERE}
+ GROUP BY day
+ ORDER BY day
+ `,
+ }
+ const response = await api.query(query)
+ return (response.results ?? []).map((row: unknown[]) => ({
+ day: String(row[0]),
+ costUsd: Number(row[1]) || 0,
+ }))
+}
+
+export async function fetchGatewayUsageByModel(): Promise<GatewayModelUsage[]> {
+ const query: HogQLQuery = {
+ kind: NodeKind.HogQLQuery,
+ query: `
+ SELECT
+ properties.$ai_model AS model,
+ count() AS requests,
+ sum(toFloat(properties.$ai_input_tokens)) AS input_tokens,
+ sum(toFloat(properties.$ai_output_tokens)) AS output_tokens,
+ round(sum(toFloat(properties.$ai_total_cost_usd)), 4) AS cost_usd
+ FROM events
+ WHERE ${GATEWAY_EVENTS_WHERE}
+ GROUP BY model
+ ORDER BY cost_usd DESC
+ LIMIT 100
+ `,
+ }
+ const response = await api.query(query)
+ return (response.results ?? []).map((row: unknown[]) => ({
+ model: row[0] ? String(row[0]) : 'unknown',
+ requests: Number(row[1]) || 0,
+ inputTokens: Number(row[2]) || 0,
+ outputTokens: Number(row[3]) || 0,
+ costUsd: Number(row[4]) || 0,
+ }))
+}
+
+// Pad the raw per-day spend into a contiguous 30-day series so the chart has no gaps for idle days.
+export function buildSpendChartData(
+ points: GatewaySpendPoint[],
+ timezone: string
+): { data: number[]; labels: string[] } {
+ const byDay = new Map(points.map((point) => [dayjs(point.day).format('YYYY-MM-DD'), point.costUsd]))
+ const start = dayjsNowInTimezone(timezone)
+ .startOf('day')
+ .subtract(USAGE_WINDOW_DAYS - 1, 'day')
+ const data: number[] = []
+ const labels: string[] = []
+ for (let i = 0; i < USAGE_WINDOW_DAYS; i++) {
+ const day = start.add(i, 'day')
+ data.push(byDay.get(day.format('YYYY-MM-DD')) ?? 0)
+ labels.push(day.format('MMM D'))
+ }
+ return { data, labels }
+}
+
+function MetricTile({ label, value, loading }: { label: string; value: string | null; loading: boolean }): JSX.Element {
+ return (
+ <div className="border rounded p-4 min-w-32 flex-1">
+ <div className="text-secondary text-xs uppercase">{label}</div>
+ {loading || value === null ? (
+ <LemonSkeleton className="h-7 w-16 mt-1" />
+ ) : (
+ <div className="text-2xl font-semibold">{value}</div>
+ )}
+ </div>
+ )
+}
+
+export function UsageMetrics({ usage, loading }: { usage: GatewayUsage | null; loading: boolean }): JSX.Element {
+ return (
+ <>
+ <MetricTile label="Spend" value={usage ? humanFriendlyCurrency(usage.costUsd) : null} loading={loading} />
+ <MetricTile label="Requests" value={usage ? humanFriendlyNumber(usage.requests) : null} loading={loading} />
+ <MetricTile
+ label="Input tokens"
+ value={usage ? humanFriendlyNumber(usage.inputTokens) : null}
+ loading={loading}
+ />
+ <MetricTile
+ label="Output tokens"
+ value={usage ? humanFriendlyNumber(usage.outputTokens) : null}
+ loading={loading}
+ />
+ </>
+ )
+}
+
+export function SpendChart({
+ data,
+ labels,
+ loading,
+}: {
+ data: number[]
+ labels: string[]
+ loading: boolean
+}): JSX.Element {
+ const hasSpend = data.some((value) => value > 0)
+ return (
+ <div className="flex flex-col gap-1">
+ <span className="text-secondary text-xs uppercase">Spend per day</span>
+ {!loading && !hasSpend ? (
+ <div className="h-16 flex items-center text-secondary text-sm">No spend in the last 30 days yet</div>
+ ) : (
+ <Sparkline
+ className="h-16"
+ type="bar"
+ data={data}
+ labels={labels}
+ color="success"
+ loading={loading}
+ renderTooltipValue={(value) => humanFriendlyCurrency(value, 4)}
+ />
+ )}
+ </div>
+ )
+}
+
+export function ModelBreakdownTable({ rows, loading }: { rows: GatewayModelUsage[]; loading: boolean }): JSX.Element {
+ return (
+ <LemonTable
+ dataSource={rows}
+ loading={loading}
+ rowKey="model"
+ size="small"
+ columns={[
+ { title: 'Model', dataIndex: 'model' },
+ {
+ title: 'Requests',
+ dataIndex: 'requests',
+ render: (_, row) => humanFriendlyNumber(row.requests),
+ sorter: (a, b) => a.requests - b.requests,
+ },
+ {
+ title: 'Tokens',
+ key: 'tokens',
+ render: (_, row) => humanFriendlyNumber(row.inputTokens + row.outputTokens),
+ sorter: (a, b) => a.inputTokens + a.outputTokens - (b.inputTokens + b.outputTokens),
+ },
+ {
+ title: 'Spend',
+ dataIndex: 'costUsd',
+ render: (_, row) => humanFriendlyCurrency(row.costUsd, 4),
+ sorter: (a, b) => a.costUsd - b.costUsd,
+ },
+ ]}
+ emptyState="No gateway usage in the last 30 days yet"
+ />
+ )
+}
diff --git a/products/ai_gateway/manifest.tsx b/products/ai_gateway/manifest.tsx
new file mode 100644
index 000000000000..16cadbc477db
--- /dev/null
+++ b/products/ai_gateway/manifest.tsx
@@ -0,0 +1,45 @@
+import { FEATURE_FLAGS } from 'lib/constants'
+import { urls } from 'scenes/urls'
+
+import { FileSystemIconType, ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'
+import { FileSystemIconColor, ProductManifest } from '~/types'
+
+export const manifest: ProductManifest = {
+ name: 'AI gateway',
+ scenes: {
+ AIGateway: {
+ import: () => import('./frontend/AIGatewayScene'),
+ projectBased: true,
+ name: 'AI gateway',
+ description: 'Every major LLM through one endpoint, billed at cost — usage tracked per project.',
+ layout: 'app-container',
+ iconType: 'ai_gateway',
+ },
+ },
+ routes: {
+ '/ai-gateway': ['AIGateway', 'aiGateway'],
+ },
+ redirects: {},
+ urls: {
+ aiGateway: (): string => '/ai-gateway',
+ },
+ fileSystemTypes: {},
+ treeItemsNew: [],
+ treeItemsProducts: [
+ {
+ path: 'AI gateway',
+ intents: [ProductKey.AI_GATEWAY],
+ category: ProductItemCategory.AI_ENGINEERING,
+ type: 'ai_gateway',
+ iconType: 'ai_gateway' as FileSystemIconType,
+ iconColor: [
+ 'var(--color-product-ai-gateway-light)',
+ 'var(--color-product-ai-gateway-dark)',
+ ] as FileSystemIconColor,
+ href: urls.aiGateway(),
+ flag: FEATURE_FLAGS.AI_GATEWAY,
+ tags: ['alpha'],
+ sceneKey: 'AIGateway',
+ },
+ ],
+}
diff --git a/products/ai_gateway/package.json b/products/ai_gateway/package.json
new file mode 100644
index 000000000000..ee59b0ae23b5
--- /dev/null
+++ b/products/ai_gateway/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "@posthog/products-ai-gateway",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/test -v --tb=short"
+ },
+ "dependencies": {
+ "kea": "catalog:",
+ "kea-forms": "catalog:",
+ "kea-loaders": "catalog:",
+ "kea-router": "catalog:",
+ "posthog-js": "catalog:"
+ },
+ "devDependencies": {
+ "kea-test-utils": "catalog:"
+ },
+ "peerDependencies": {
+ "@posthog/icons": "*",
+ "@storybook/react": "catalog:",
+ "@types/react": "*",
+ "clsx": "*",
+ "react": "*"
+ }
+}
diff --git a/products/ai_gateway/product.yaml b/products/ai_gateway/product.yaml
new file mode 100644
index 000000000000..8524a95c4977
--- /dev/null
+++ b/products/ai_gateway/product.yaml
@@ -0,0 +1,3 @@
+name: AI gateway
+owners:
+ - team-ai-gateway
diff --git a/products/ai_gateway/tsconfig.json b/products/ai_gateway/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/ai_gateway/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/tach.toml b/tach.toml
index dd2268ebe2d8..2a774a8189d7 100644
--- a/tach.toml
+++ b/tach.toml
@@ -136,6 +136,11 @@ depends_on = [
]
layer = "modules"
+[[modules]]
+path = "products.ai_gateway"
+depends_on = ["posthog"]
+layer = "modules"
+
[[modules]]
path = "products.alerts"
depends_on = [