🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(telemetry): report AI gateway request counts from self-hosted instances (#19433)
Tobias Wochinger7e5c843908b3
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 471b695d84..6d1968b779 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -30,6 +30,7 @@ import {} from "../clickhouse/client";import { recordDistribution } from "../instrumentation";import { logger } from "../logger";+import { AI_GATEWAY_SERVICE_NAME } from "../../features/ai-gateway/constants";import { compileClickhouseQuery } from "../query-ast/compile";import { getClickhouseKysely } from "../query-ast/dialect";import type { ClickHouseDatabase } from "../query-ast/schema";@@ -1503,7 +1504,9 @@ export const getLastTraceTimestampsByProjects = async (* Trace and observation counts per project for events_core rows created in* `[start, end)`. Ingestion-API traces carry a synthetic `t-<traceId>` root* row, which counts towards the trace but not as an observation. A trace with- * rows created in several intervals counts once in each.+ * rows created in several intervals counts once in each. The AI gateway writes+ * one generation per request, so `gatewayRequests` counts its rows; ingestion+ * keeps the gateway service name only on gateway-authenticated uploads.*/export const getTracingCountsByProjectInCreationIntervalFromEventsTable =async ({@@ -1521,7 +1524,8 @@ export const getTracingCountsByProjectInCreationIntervalFromEventsTable =SELECTproject_id,uniq(trace_id) as traces,- countIf(span_id != concat('t-', trace_id)) as observations+ countIf(span_id != concat('t-', trace_id)) as observations,+ countIf(service_name = {gatewayServiceName: String}) as gateway_requestsFROM events_coreWHERE created_at >= {start: DateTime64(3)}AND created_at < {end: DateTime64(3)}@@ -1534,11 +1538,13 @@ export const getTracingCountsByProjectInCreationIntervalFromEventsTable =project_id: string;traces: string;observations: string;+ gateway_requests: string;}>({query,params: {start: convertDateToClickhouseDateTime(start),end: convertDateToClickhouseDateTime(end),+ gatewayServiceName: AI_GATEWAY_SERVICE_NAME,...(projectIds ? { projectIds } : {}),},clickhouseConfigs: {@@ -1551,6 +1557,7 @@ export const getTracingCountsByProjectInCreationIntervalFromEventsTable =projectId: row.project_id,traces: Number(row.traces),observations: Number(row.observations),+ gatewayRequests: Number(row.gateway_requests),}));};diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.tsindex 03a85c3034..78507dc952 100644--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts@@ -41,6 +41,7 @@ import { prisma } from "@langfuse/shared/src/db";import { randomUUID } from "crypto";import { env } from "@/src/env.mjs";import {+ AI_GATEWAY_SERVICE_NAME,LangfuseNotFoundError,type EventsTableFilterState,type FilterCondition,@@ -6001,7 +6002,7 @@ describe("Clickhouse Events Repository Test", () => {});describe("tracing counts by project on the events table", () => {- it("counts traces and observations created in the interval, excluding synthetic trace rows", async () => {+ it("counts traces, observations and gateway requests created in the interval, excluding synthetic trace rows", async () => {const projectA = randomUUID();const projectB = randomUUID();const legacyTraceId = randomUUID();@@ -6046,6 +6047,23 @@ describe("tracing counts by project on the events table", () => {}),event({ project_id: projectA, trace_id: randomUUID(), created_at: end }),event({ project_id: projectB, trace_id: randomUUID() }),+ // AI gateway generations carry the gateway service; outside the window they don't count.+ event({+ project_id: projectB,+ trace_id: randomUUID(),+ service_name: AI_GATEWAY_SERVICE_NAME,+ }),+ event({+ project_id: projectB,+ trace_id: randomUUID(),+ service_name: AI_GATEWAY_SERVICE_NAME,+ }),+ event({+ project_id: projectB,+ trace_id: randomUUID(),+ service_name: AI_GATEWAY_SERVICE_NAME,+ created_at: end,+ }),]);const counts =@@ -6059,8 +6077,8 @@ describe("tracing counts by project on the events table", () => {counts.sort((a, b) => a.projectId.localeCompare(b.projectId)),).toEqual([- { projectId: projectA, traces: 3, observations: 5 },- { projectId: projectB, traces: 1, observations: 1 },+ { projectId: projectA, traces: 3, observations: 5, gatewayRequests: 0 },+ { projectId: projectB, traces: 3, observations: 3, gatewayRequests: 2 },].sort((a, b) => a.projectId.localeCompare(b.projectId)),);});diff --git a/web/src/features/ai-gateway/server/availability.servertest.ts b/web/src/features/ai-gateway/server/availability.servertest.tsindex 60685c1d46..16bb6d9d0d 100644--- a/web/src/features/ai-gateway/server/availability.servertest.ts+++ b/web/src/features/ai-gateway/server/availability.servertest.ts@@ -115,6 +115,39 @@ describe("self-hosted deployments", () => {);});+describe("v4 write mode", () => {+ // Development otherwise enables every organization regardless of flags.+ it.each([deployedSelfHosted, { nodeEnv: "development" }] as const)(+ "turns the gateway off in legacy write mode for %o",+ (environment) => {+ const legacy = {+ ...environment,+ enabledForAllOrganizations: "true",+ writeMode: "legacy",+ } as const;++ expect(isGatewayEnabledForOrganization("org-1", ["org-1"], legacy)).toBe(+ false,+ );+ expect(() =>+ requireGatewayEnabledForOrganization("org-1", ["org-1"], legacy),+ ).toThrow(ForbiddenError);+ },+ );++ it.each(["dual", "events_only"] as const)(+ "keeps the gateway on in %s write mode",+ (writeMode) => {+ expect(+ isGatewayEnabledForOrganization("org-1", [], {+ ...deployedSelfHosted,+ writeMode,+ }),+ ).toBe(true);+ },+ );+});+describe("Langfuse Cloud matches the previous availability rule", () => {// The rule before LANGFUSE_AI_GATEWAY_DEPLOYED existed, when// LANGFUSE_AI_GATEWAY_ENABLED defaulted to "false".diff --git a/web/src/features/ai-gateway/server/availability.ts b/web/src/features/ai-gateway/server/availability.tsindex 2206ecf3b0..79d949841a 100644--- a/web/src/features/ai-gateway/server/availability.ts+++ b/web/src/features/ai-gateway/server/availability.ts@@ -8,6 +8,7 @@ type GatewayAvailabilityEnvironment = {previewPrUrl?: string;deployed?: "true" | "false";enabledForAllOrganizations?: "true" | "false";+ writeMode?: (typeof env)["LANGFUSE_MIGRATION_V4_WRITE_MODE"];};const getGatewayAvailabilityEnvironment =@@ -17,6 +18,7 @@ const getGatewayAvailabilityEnvironment =previewPrUrl: env.NEXT_PUBLIC_PREVIEW_PR_URL,deployed: env.LANGFUSE_AI_GATEWAY_DEPLOYED,enabledForAllOrganizations: env.LANGFUSE_AI_GATEWAY_ENABLED,+ writeMode: env.LANGFUSE_MIGRATION_V4_WRITE_MODE,});const isDevelopmentOrPreview = (environment: GatewayAvailabilityEnvironment) =>@@ -48,12 +50,17 @@ const isEnabledForAllOrganizations = (? !environment.cloudRegion: environment.enabledForAllOrganizations === "true";+/**+ * Gateway generations are only attributed to their gateway API key and service+ * in the v4 events table, which the `legacy` write mode never writes.+ */export const isGatewayEnabledForOrganization = (organizationId: string,allowedOrganizationIds = env.LANGFUSE_AI_GATEWAY_ORGANIZATION_ID_ALLOWLIST ??[],environment = getGatewayAvailabilityEnvironment(),): boolean =>+ environment.writeMode !== "legacy" &&isGatewayDeployed(environment) &&(isEnabledForAllOrganizations(environment) ||isDevelopmentOrPreview(environment) ||diff --git a/web/src/features/telemetry/index.ts b/web/src/features/telemetry/index.tsindex c425f95663..f1b7f1afc5 100644--- a/web/src/features/telemetry/index.ts+++ b/web/src/features/telemetry/index.ts@@ -161,9 +161,12 @@ async function jobScheduler(): Promise<}/**- * Counts traces and observations created in `[start, end)` from the tables the- * worker writes: under `events_only` the legacy traces/observations tables are- * empty, so the events table is the only source.+ * Counts traces, observations and AI gateway requests created in `[start, end)`+ * from the tables the worker writes: under `events_only` the legacy+ * traces/observations tables are empty, so the events table is the only+ * source. Gateway requests are reported only there: legacy tables do not mark+ * gateway rows, and in `dual` mode a second full events scan would cost too+ * much for that one number.*/async function countTracing({ start, end }: { start: Date; end: Date }) {if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "events_only") {@@ -178,6 +181,10 @@ async function countTracing({ start, end }: { start: Date; end: Date }) {(acc, curr) => acc + curr.observations,0,),+ countGatewayRequests: counts.reduce(+ (acc, curr) => acc + curr.gatewayRequests,+ 0,+ ),};}@@ -188,6 +195,7 @@ async function countTracing({ start, end }: { start: Date; end: Date }) {return {countTraces: traces.reduce((acc, curr) => acc + curr.count, 0),countObservations: observations.reduce((acc, curr) => acc + curr.count, 0),+ countGatewayRequests: undefined,};}@@ -209,11 +217,12 @@ async function posthogTelemetry({},});- // Count traces and observations- const { countTraces, countObservations } = await countTracing({- start: startTimeframe ?? new Date(0),- end: endTimeframe,- });+ // Count traces, observations and AI gateway requests+ const { countTraces, countObservations, countGatewayRequests } =+ await countTracing({+ start: startTimeframe ?? new Date(0),+ end: endTimeframe,+ });// Count scoresconst countScoresClickhouse =@@ -304,6 +313,7 @@ async function posthogTelemetry({datasetRuns: countDatasetRuns,datasetRunItems: countDatasetRunItems,assistantRuns: countAssistantRuns,+ gatewayRequests: countGatewayRequests,startTimeframe: startTimeframe?.toISOString(),endTimeframe: endTimeframe.toISOString(),eeLicenseKey: env.LANGFUSE_EE_LICENSE_KEY,