🪢 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(agent): Add rate-limits (#14175)
Ben Bachem429399ae38b0
diff --git a/packages/shared/src/interfaces/rate-limits.ts b/packages/shared/src/interfaces/rate-limits.tsindex b0cc338e53..d47a20ddf5 100644--- a/packages/shared/src/interfaces/rate-limits.ts+++ b/packages/shared/src/interfaces/rate-limits.ts@@ -12,6 +12,7 @@ export const RateLimitResource = z.enum(["datasets","trace-delete","score-delete",+ "in-app-agent-run",]);// result of the rate limit check.diff --git a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.tsindex db1c9fba09..750e3917c5 100644--- a/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-api-route-auth.servertest.ts@@ -1,15 +1,65 @@import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";+import { env } from "@/src/env.mjs";import { prisma } from "@langfuse/shared/src/db";import {createAndAddApiKeysToDb,createBasicAuthHeader,createOrgProjectAndApiKey,} from "@langfuse/shared/src/server";+import type { Session } from "next-auth";import type { NextApiRequest, NextApiResponse } from "next";import { createMocks } from "node-mocks-http";+import { beforeEach, vi } from "vitest";import { z } from "zod";+const authMocks = vi.hoisted(() => ({+ getServerSession: vi.fn(),+ getAuthOptions: vi.fn().mockResolvedValue({}),+}));++const entitlementMocks = vi.hoisted(() => ({+ hasEntitlement: vi.fn(() => true),+}));++const rateLimitMocks = vi.hoisted(() => ({+ rateLimitRequest: vi.fn(),+}));++vi.mock("next-auth", () => ({+ getServerSession: authMocks.getServerSession,+}));++vi.mock("@/src/server/auth", () => ({+ getAuthOptions: authMocks.getAuthOptions,+}));++vi.mock("@/src/features/entitlements/server/hasEntitlement", () => ({+ hasEntitlement: entitlementMocks.hasEntitlement,+}));++vi.mock("@/src/features/public-api/server/RateLimitService", () => ({+ RateLimitService: {+ getInstance: () => ({+ rateLimitRequest: rateLimitMocks.rateLimitRequest,+ }),+ },+ createHttpHeaderFromRateLimit: () => ({+ "Retry-After": 60,+ "X-RateLimit-Limit": 2,+ "X-RateLimit-Remaining": 0,+ "X-RateLimit-Reset": "soon",+ }),+}));+describe("in-app agent public API route auth", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ rateLimitMocks.rateLimitRequest.mockResolvedValue({+ isRateLimited: () => false,+ res: undefined,+ });+ });+async function createInAppAgentAuthHeader() {const { projectId } = await createOrgProjectAndApiKey();const apiKey = await createAndAddApiKeysToDb({@@ -71,4 +121,211 @@ describe("in-app agent public API route auth", () => {expect(res.statusCode).toBe(200);expect(res._getJSONData()).toEqual({ ok: true });});++ it("returns 429 when an in-app agent run exceeds the rate limit", async () => {+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ const originalBedrockModel = env.LANGFUSE_AWS_BEDROCK_MODEL;++ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "DEV";+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = "test-model";++ const { org, project } = await createOrgProjectAndApiKey();++ try {+ await prisma.organization.update({+ where: { id: org.id },+ data: { aiFeaturesEnabled: true },+ });+ const session = createInAppAgentSession({+ orgId: org.id,+ projectId: project.id,+ });+ authMocks.getServerSession.mockResolvedValue(session);+ rateLimitMocks.rateLimitRequest.mockResolvedValue({+ isRateLimited: () => true,+ res: {+ resource: "in-app-agent-run",+ scope: {+ orgId: org.id,+ plan: "cloud:team",+ projectId: project.id,+ accessLevel: "project",+ rateLimitOverrides: [],+ apiKeyId: "in-app-agent-session",+ publicKey: "in-app-agent-session",+ isIngestionSuspended: false,+ },+ points: 2,+ remainingPoints: 0,+ msBeforeNext: 60_000,+ consumedPoints: 2,+ isFirstInDuration: false,+ },+ });++ const { default: handler } =+ await import("@/src/ee/features/in-app-agent/server/handler");+ const response = await handler(+ new Request("http://localhost/api/in-app-agent", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ threadId: "conversation-1",+ runId: "client-run-1",+ messages: [{ id: "message-1", role: "user", content: "hello" }],+ tools: [],+ context: [],+ state: {+ type: "newConversation",+ projectId: project.id,+ },+ forwardedProps: {},+ }),+ }),+ );++ expect(response.status).toBe(429);+ await expect(response.json()).resolves.toEqual({+ error: "Rate limit exceeded",+ });+ expect(response.headers.get("Retry-After")).toBe("60");+ expect(rateLimitMocks.rateLimitRequest).toHaveBeenCalledWith(+ expect.objectContaining({+ orgId: org.id,+ projectId: project.id,+ }),+ "in-app-agent-run",+ );+ } finally {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = originalBedrockModel;+ }+ });++ it("rate-limits instance admins who are not project members", async () => {+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ const originalBedrockModel = env.LANGFUSE_AWS_BEDROCK_MODEL;++ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "DEV";+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = "test-model";++ const { org, project } = await createOrgProjectAndApiKey();++ try {+ await prisma.organization.update({+ where: { id: org.id },+ data: { aiFeaturesEnabled: true, cloudConfig: { plan: "Team" } },+ });+ const session = createInAppAgentSession({+ orgId: org.id,+ projectId: project.id,+ admin: true,+ includeProjectMembership: false,+ });+ authMocks.getServerSession.mockResolvedValue(session);+ rateLimitMocks.rateLimitRequest.mockResolvedValue({+ isRateLimited: () => true,+ res: {+ resource: "in-app-agent-run",+ scope: {+ orgId: org.id,+ plan: "cloud:team",+ projectId: project.id,+ accessLevel: "project",+ rateLimitOverrides: [],+ apiKeyId: "in-app-agent-session",+ publicKey: "in-app-agent-session",+ isIngestionSuspended: false,+ },+ points: 2,+ remainingPoints: 0,+ msBeforeNext: 60_000,+ consumedPoints: 2,+ isFirstInDuration: false,+ },+ });++ const { default: handler } =+ await import("@/src/ee/features/in-app-agent/server/handler");+ const response = await handler(+ new Request("http://localhost/api/in-app-agent", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ threadId: "conversation-1",+ runId: "client-run-1",+ messages: [{ id: "message-1", role: "user", content: "hello" }],+ tools: [],+ context: [],+ state: {+ type: "newConversation",+ projectId: project.id,+ },+ forwardedProps: {},+ }),+ }),+ );++ expect(response.status).toBe(429);+ expect(rateLimitMocks.rateLimitRequest).toHaveBeenCalledWith(+ expect.objectContaining({+ orgId: org.id,+ projectId: project.id,+ plan: "cloud:team",+ }),+ "in-app-agent-run",+ );+ } finally {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;+ (env as any).LANGFUSE_AWS_BEDROCK_MODEL = originalBedrockModel;+ }+ });});++function createInAppAgentSession(params: {+ orgId: string;+ projectId: string;+ admin?: boolean;+ includeProjectMembership?: boolean;+}): Session {+ const includeProjectMembership = params.includeProjectMembership ?? true;++ return {+ expires: new Date(Date.now() + 60_000).toISOString(),+ environment: { enableExperimentalFeatures: false },+ user: {+ id: "user-1",+ name: "Test User",+ email: "[email protected]",+ image: null,+ admin: params.admin ?? false,+ featureFlags: { inAppAgent: true },+ organizations: includeProjectMembership+ ? [+ {+ id: params.orgId,+ name: "Test Org",+ plan: "cloud:team",+ role: "OWNER",+ metadata: {},+ aiFeaturesEnabled: true,+ aiTelemetryEnabled: false,+ cloudConfig: { plan: "Team" },+ projects: [+ {+ id: params.projectId,+ name: "Test Project",+ role: "ADMIN",+ retentionDays: 30,+ hasTraces: false,+ deletedAt: null,+ metadata: {},+ createdAt: new Date().toISOString(),+ },+ ],+ },+ ]+ : [],+ },+ } as Session;+}diff --git a/web/src/ee/features/in-app-agent/server/handler.ts b/web/src/ee/features/in-app-agent/server/handler.tsindex d581d2c706..75b021e659 100644--- a/web/src/ee/features/in-app-agent/server/handler.ts+++ b/web/src/ee/features/in-app-agent/server/handler.ts@@ -1,4 +1,5 @@import { EventType } from "@ag-ui/core";+import { type Session } from "next-auth";import { getServerSession } from "next-auth";import { env } from "@/src/env.mjs";@@ -25,16 +26,27 @@ import {} from "@/src/ee/features/in-app-agent/server/persistence";import { getAuthOptions } from "@/src/server/auth";import { hasEntitlement } from "@/src/features/entitlements/server/hasEntitlement";+import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server/getPlan";+import {+ createHttpHeaderFromRateLimit,+ RateLimitService,+} from "@/src/features/public-api/server/RateLimitService";import { isProjectMemberOrAdmin } from "@/src/server/utils/checkProjectMembershipOrAdmin";import { assertUnreachable } from "@/src/utils/types";import {BaseError,ForbiddenError,InvalidRequestError,+ type RateLimitResult,UnauthorizedError,+ CloudConfigSchema,} from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import {+ logger,+ redis,+ type ApiAccessScope,+} from "@langfuse/shared/src/server";import {createAndAddApiKeysToDb,deleteApiKeyFromDb,@@ -143,6 +155,8 @@ export default async function handler(request: Request) {select: {organization: {select: {+ id: true,+ cloudConfig: true,aiFeaturesEnabled: true,aiTelemetryEnabled: true,},@@ -170,6 +184,22 @@ export default async function handler(request: Request) {);}+ // TODO: Add an additional user-level cap once the rate-limit service supports non-org keys.+ const rateLimitScope = getInAppAgentRateLimitScope(+ auth.user,+ projectId,+ project.organization,+ );++ const rateLimitResponse = await rateLimitInAppAgentRequest(+ rateLimitScope,+ "in-app-agent-run",+ );++ if (rateLimitResponse) {+ return rateLimitResponse;+ }+const conversation = await ensureOwnedConversation({prisma,projectId,@@ -351,6 +381,84 @@ export default async function handler(request: Request) {}}+type SessionUser = NonNullable<Session["user"]>;++function getInAppAgentRateLimitScope(+ user: SessionUser,+ projectId: string,+ projectOrganization: {+ id: string;+ cloudConfig: unknown;+ },+): ApiAccessScope {+ const organization = user.organizations.find((org) =>+ org.projects.some((project) => project.id === projectId),+ );++ if (!organization) {+ if (user.admin === true) {+ const cloudConfig = projectOrganization.cloudConfig+ ? CloudConfigSchema.parse(projectOrganization.cloudConfig)+ : undefined;++ return {+ orgId: projectOrganization.id,+ plan: getOrganizationPlanServerSide(cloudConfig),+ projectId,+ accessLevel: "project",+ rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],+ apiKeyId: "in-app-agent-session",+ publicKey: "in-app-agent-session",+ isIngestionSuspended: false,+ };+ }++ throw new ForbiddenError("User is not a member of this project");+ }++ return {+ orgId: organization.id,+ plan: organization.plan,+ projectId,+ accessLevel: "project",+ rateLimitOverrides: organization.cloudConfig?.rateLimitOverrides ?? [],+ apiKeyId: "in-app-agent-session",+ publicKey: "in-app-agent-session",+ isIngestionSuspended: false,+ };+}++async function rateLimitInAppAgentRequest(+ scope: ApiAccessScope,+ resource: Parameters<RateLimitService["rateLimitRequest"]>[1],+): Promise<Response | undefined> {+ const rateLimit = await RateLimitService.getInstance().rateLimitRequest(+ scope,+ resource,+ );++ if (!rateLimit.isRateLimited() || !rateLimit.res) {+ return undefined;+ }++ return createInAppAgentRateLimitResponse(rateLimit.res);+}++function createInAppAgentRateLimitResponse(rateLimitRes: RateLimitResult) {+ const headers = new Headers();++ for (const [header, value] of Object.entries(+ createHttpHeaderFromRateLimit(rateLimitRes),+ )) {+ headers.set(header, String(value));+ }++ return Response.json(+ { error: "Rate limit exceeded" },+ { status: 429, headers },+ );+}+function getLangfuseMcpUrl(): string {const rawUrl = env.NEXTAUTH_URL.replace(/\/api\/auth\/?$/, "");const baseUrl = new URL(rawUrl);diff --git a/web/src/features/public-api/server/RateLimitService.ts b/web/src/features/public-api/server/RateLimitService.tsindex 250b2f37a5..46cf711f06 100644--- a/web/src/features/public-api/server/RateLimitService.ts+++ b/web/src/features/public-api/server/RateLimitService.ts@@ -305,6 +305,12 @@ const getPlanBasedRateLimitConfig = (points: 50,durationInSec: 86400, // 50 requests per day};+ case "in-app-agent-run":+ return {+ resource: "in-app-agent-run",+ points: 100,+ durationInSec: 86400,+ };default:const exhaustiveCheck: never = resource;throw new Error(`Unhandled resource case: ${exhaustiveCheck}`);@@ -379,6 +385,12 @@ const getPlanBasedRateLimitConfig = (points: 200,durationInSec: 86400, // 200 requests per day};+ case "in-app-agent-run":+ return {+ resource: "in-app-agent-run",+ points: 1000,+ durationInSec: 86400,+ };default:const exhaustiveCheck: never = resource;throw new Error(`Unhandled resource case: ${exhaustiveCheck}`);@@ -447,6 +459,12 @@ const getPlanBasedRateLimitConfig = (points: 1000,durationInSec: 86400, // 1000 requests per day};+ case "in-app-agent-run":+ return {+ resource: "in-app-agent-run",+ points: 1000,+ durationInSec: 86400,+ };default:const exhaustiveCheck: never = resource;throw new Error(`Unhandled resource case: ${exhaustiveCheck}`);