Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(trace-ui): natural language filters (#9347)

Nimar17a358a1c285
diff --git a/.env.dev.example b/.env.dev.example
index 1b76317ed1..c9301d9636 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -87,4 +87,16 @@ NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"
# Slack credentials for development
SLACK_CLIENT_ID=your_slack_client_id
SLACK_CLIENT_SECRET=your_slack_client_secret
-SLACK_STATE_SECRET=your_slack_state_secret
\ No newline at end of file
+SLACK_STATE_SECRET=your_slack_state_secret
+
+# Langfuse AI feature credentials for development
+LANGFUSE_AI_FEATURES_PUBLIC_KEY="pk-lf-123456789"
+LANGFUSE_AI_FEATURES_SECRET_KEY="sk-lf-123456789"
+LANGFUSE_AI_FEATURES_HOST="https://staging.langfuse.com"
+
+# Bedrock credentials for development
+AWS_ACCESS_KEY_ID="A123456789"
+AWS_SECRET_ACCESS_KEY="SAK123456789"
+LANGFUSE_AWS_BEDROCK_REGION="eu-west-1"
+
+LANGFUSE_AWS_BEDROCK_MODEL="eu.anthropic.claude-3-5-sonnet-20240620-v1:0"
diff --git a/REVIEW.md b/REVIEW.md
index 18e3f0c27d..69d7f14a56 100644
--- a/REVIEW.md
+++ b/REVIEW.md
@@ -22,3 +22,7 @@
- Highlight usage of `redis.call` invocations. Those may have suboptimal redis cluster routing and will raise errors. Instead, use the native call patterns.
Example: `await redis?.call("SET", key, "1", "NX", "EX", TTLSeconds);` should use `await redis?.set(key, "1", "EX", TTLSeconds, "NX");` instead.
+
+## Langfuse Cloud
+
+- When attempting to confirm if the current environment is Langfuse Cloud in the frontend, use the `useLangfuseCloudRegion` hook and never environment variables directly.
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 8c32e69ca8..a21700ed29 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -641,6 +641,7 @@ export type Organization = {
updated_at: Generated<Timestamp>;
cloud_config: unknown | null;
metadata: unknown | null;
+ ai_features_enabled: Generated<boolean>;
};
export type OrganizationMembership = {
id: string;
diff --git a/packages/shared/prisma/migrations/20250925133604_organizations_add_ai_features_enabled/migration.sql b/packages/shared/prisma/migrations/20250925133604_organizations_add_ai_features_enabled/migration.sql
new file mode 100644
index 0000000000..10b0d8ee6c
--- /dev/null
+++ b/packages/shared/prisma/migrations/20250925133604_organizations_add_ai_features_enabled/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "organizations" ADD COLUMN "ai_features_enabled" BOOLEAN NOT NULL DEFAULT false;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 1327dc2f7c..1388674fe3 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -110,6 +110,7 @@ model Organization {
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
cloudConfig Json? @map("cloud_config") // Langfuse Cloud, for zod schema see @/src/features/organizations/utils/cloudConfigSchema
metadata Json?
+ aiFeaturesEnabled Boolean @default(false) @map("ai_features_enabled")
organizationMemberships OrganizationMembership[]
projects Project[]
MembershipInvitation MembershipInvitation[]
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 14a4c74105..eb2de9fa26 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -231,6 +231,14 @@ const EnvSchema = z.object({
.int()
.positive()
.default(120_000), // 2 minutes
+
+ LANGFUSE_AWS_BEDROCK_REGION: z.string().optional(),
+
+ // Langfuse AI Features
+ LANGFUSE_AI_FEATURES_PUBLIC_KEY: z.string().optional(),
+ LANGFUSE_AI_FEATURES_SECRET_KEY: z.string().optional(),
+ LANGFUSE_AI_FEATURES_HOST: z.string().optional(),
+ LANGFUSE_AI_FEATURES_PROJECT_ID: z.string().optional(),
});
export const env: z.infer<typeof EnvSchema> =
diff --git a/packages/shared/src/server/ingestion/processEventBatch.ts b/packages/shared/src/server/ingestion/processEventBatch.ts
index b684de5284..07db5b3137 100644
--- a/packages/shared/src/server/ingestion/processEventBatch.ts
+++ b/packages/shared/src/server/ingestion/processEventBatch.ts
@@ -1,7 +1,6 @@
import { randomUUID } from "crypto";
import { z } from "zod/v4";
-import { type Model } from "../../db";
import { env } from "../../env";
import {
InvalidRequestError,
@@ -50,12 +49,6 @@ const getS3StorageServiceClient = (bucketName: string): StorageService => {
return s3StorageServiceClient;
};
-// eslint-disable-next-line no-unused-vars
-export type TokenCountDelegate = (p: {
- model: Model;
- text: unknown;
-}) => number | undefined;
-
/**
* Get the delay for the event based on the event type. Uses delay if set, 0 if current UTC timestamp is not between
* 23:45 and 00:15, and env.LANGFUSE_INGESTION_QUEUE_DELAY_MS otherwise.
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index 7ccde8832a..b32a083584 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -25,6 +25,7 @@ import GCPServiceAccountKeySchema, {
BedrockCredentialSchema,
VertexAIConfigSchema,
BEDROCK_USE_DEFAULT_CREDENTIALS,
+ BedrockCredential,
} from "../../interfaces/customLLMProviderConfigSchemas";
import { processEventBatch } from "../ingestion/processEventBatch";
import { logger } from "../logger";
@@ -53,6 +54,29 @@ const PROVIDERS_WITH_REQUIRED_USER_MESSAGE = [
LLMAdapter.Anthropic,
];
+const resolveBedrockCredentials = (
+ apiKey: string,
+ context: LLMCompletionContext,
+): BedrockCredential | undefined => {
+ // Default credentials can only be used in self-hosted deployments or when credentials are managed by langfuse
+ const canUseDefaultCredentials =
+ !isLangfuseCloud || context.credentials === "langfuse";
+ return apiKey === BEDROCK_USE_DEFAULT_CREDENTIALS && canUseDefaultCredentials
+ ? undefined // undefined = use AWS SDK default credential provider chain
+ : BedrockCredentialSchema.parse(JSON.parse(apiKey));
+};
+
+const resolveBedrockRegion = (
+ context: LLMCompletionContext,
+ config?: Record<string, string> | null,
+): string | undefined => {
+ if (context.credentials === "langfuse") {
+ return env.LANGFUSE_AWS_BEDROCK_REGION ?? undefined;
+ }
+ const { region } = BedrockConfigSchema.parse(config);
+ return region;
+};
+
const transformSystemMessageToUserMessage = (
messages: ChatMessage[],
): BaseMessage[] => {
@@ -65,6 +89,16 @@ const transformSystemMessageToUserMessage = (
type ProcessTracedEvents = () => Promise<void>;
+type LLMCompletionContext = {
+ tracing: "langfuse";
+ credentials: "user" | "langfuse";
+};
+
+const DEFAULT_LLM_COMPLETION_CONTEXT: LLMCompletionContext = {
+ tracing: "langfuse",
+ credentials: "user",
+};
+
type LLMCompletionParams = {
messages: ChatMessage[];
modelParams: ModelParams;
@@ -77,6 +111,7 @@ type LLMCompletionParams = {
config?: Record<string, string> | null;
traceParams?: TraceParams;
throwOnError?: boolean; // default is true
+ context?: LLMCompletionContext;
};
type FetchLLMCompletionParams = LLMCompletionParams & {
@@ -150,33 +185,57 @@ export async function fetchLLMCompletion(
traceParams,
extraHeaders,
throwOnError = true,
+ context = DEFAULT_LLM_COMPLETION_CONTEXT,
} = params;
let finalCallbacks: BaseCallbackHandler[] | undefined = callbacks ?? [];
let processTracedEvents: ProcessTracedEvents = () => Promise.resolve();
if (traceParams) {
- const handler = new CallbackHandler({
- _projectId: traceParams.projectId,
- _isLocalEventExportEnabled: true,
- environment: traceParams.environment,
- });
- finalCallbacks.push(handler);
+ let handler: CallbackHandler;
+
+ if (
+ context.credentials === "langfuse" &&
+ env.LANGFUSE_AI_FEATURES_PUBLIC_KEY &&
+ env.LANGFUSE_AI_FEATURES_SECRET_KEY &&
+ env.LANGFUSE_AI_FEATURES_HOST
+ ) {
+ // send to configured cloud Langfuse instance
+ handler = new CallbackHandler({
+ publicKey: env.LANGFUSE_AI_FEATURES_PUBLIC_KEY,
+ secretKey: env.LANGFUSE_AI_FEATURES_SECRET_KEY,
+ baseUrl: env.LANGFUSE_AI_FEATURES_HOST,
+ environment: traceParams.environment,
+ });
- processTracedEvents = async () => {
- try {
- const events = await handler.langfuse._exportLocalEvents(
- traceParams.projectId,
- );
- await processEventBatch(
- JSON.parse(JSON.stringify(events)), // stringify to emulate network event batch from network call
- traceParams.authCheck,
- { isLangfuseInternal: true },
- );
- } catch (e) {
- logger.error("Failed to process traced events", { error: e });
- }
- };
+ processTracedEvents = () => Promise.resolve();
+ } else {
+ // use local trace export
+ handler = new CallbackHandler({
+ _projectId: traceParams.projectId,
+ _isLocalEventExportEnabled: true,
+ environment: traceParams.environment,
+ });
+
+ processTracedEvents = async () => {
+ try {
+ const events = await handler.langfuse._exportLocalEvents(
+ traceParams.projectId,
+ );
+ await processEventBatch(
+ JSON.parse(JSON.stringify(events)), // stringify to emulate network event batch from network call
+ traceParams.authCheck,
+ {
+ isLangfuseInternal: context.tracing === "langfuse",
+ },
+ );
+ } catch (e) {
+ logger.error("Failed to process traced events", { error: e });
+ }
+ };
+ }
+
+ finalCallbacks.push(handler);
}
finalCallbacks = finalCallbacks.length > 0 ? finalCallbacks : undefined;
@@ -301,12 +360,9 @@ export async function fetchLLMCompletion(
modelKwargs: modelParams.providerOptions,
});
} else if (modelParams.adapter === LLMAdapter.Bedrock) {
- const { region } = BedrockConfigSchema.parse(config);
// Handle both explicit credentials and default provider chain
- const credentials =
- apiKey === BEDROCK_USE_DEFAULT_CREDENTIALS && !isLangfuseCloud
- ? undefined // undefined = use AWS SDK default credential provider chain
- : BedrockCredentialSchema.parse(JSON.parse(apiKey));
+ const credentials = resolveBedrockCredentials(apiKey, context);
+ const region = resolveBedrockRegion(context, config);
chatModel = new ChatBedrockConverse({
model: modelParams.model,
diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.ts
index 490b5de93f..66f1d07e5a 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -4,7 +4,6 @@ import {
BedrockConfigSchema,
VertexAIConfigSchema,
} from "../../interfaces/customLLMProviderConfigSchemas";
-import { TokenCountDelegate } from "../ingestion/processEventBatch";
import { AuthHeaderValidVerificationResult } from "../auth/types";
import { JSONObjectSchema } from "../../utils/zod";
@@ -491,7 +490,7 @@ export type TraceParams = {
traceName: string;
traceId: string;
projectId: string;
- environment: PromptExperimentEnvironment;
- tokenCountDelegate: TokenCountDelegate;
+ // TODO: add more possibilities for environment re: langfuse AI features
+ environment: PromptExperimentEnvironment | string;
authCheck: AuthHeaderValidVerificationResult;
};
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a887d188bc..a3bc1d2b24 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -58,7 +58,7 @@ importers:
next-auth:
specifier: ^4.24.11
zod:
specifier: ^3.25.62
version: 3.25.62
@@ -238,7 +238,7 @@ importers:
version: 4.1.1
next-auth:
specifier: ^4.24.11
nodemailer:
specifier: ^6.9.15
version: 6.9.15
@@ -615,6 +615,9 @@ importers:
langchain:
specifier: ^0.3.30
+ langfuse:
+ specifier: 3.38.4
+ version: 3.38.4
lodash:
specifier: ^4.17.21
version: 4.17.21
@@ -629,7 +632,7 @@ importers:
next-auth:
specifier: ^4.24.11
next-query-params:
specifier: ^5.1.0
@@ -15885,7 +15888,7 @@ snapshots:
dependencies:
dependencies:
@@ -24773,7 +24776,7 @@ snapshots:
dependencies:
type-fest: 2.19.0
dependencies:
'@babel/runtime': 7.26.0
'@panva/hkdf': 1.1.1
diff --git a/web/package.json b/web/package.json
index 4ccbf7cf37..5e904ccb8a 100644
--- a/web/package.json
+++ b/web/package.json
@@ -119,6 +119,7 @@
"ip-address": "^9.0.5",
"kysely": "^0.27.4",
"langchain": "^0.3.30",
+ "langfuse": "3.38.4",
"lodash": "^4.17.21",
"lucide-react": "^0.462.0",
"nanoid": "^3.3.8",
diff --git a/web/src/components/EnvLabel.tsx b/web/src/components/EnvLabel.tsx
index 4418afe810..63bc697d94 100644
--- a/web/src/components/EnvLabel.tsx
+++ b/web/src/components/EnvLabel.tsx
@@ -1,4 +1,4 @@
-import { env } from "@/src/env.mjs";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
import { cn } from "@/src/utils/tailwind";
import { useSession } from "next-auth/react";
import { useState } from "react";
@@ -6,25 +6,26 @@ import { useState } from "react";
export const EnvLabel = ({ className }: { className?: string }) => {
const [isHidden, setIsHidden] = useState(false);
const session = useSession();
- if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) return null;
+ const { isLangfuseCloud, region } = useLangfuseCloudRegion();
+ if (!isLangfuseCloud) return null;
if (!session.data?.user?.email?.endsWith("@langfuse.com")) return null;
if (isHidden) return null;
return (
<div
className={cn(
"flex cursor-pointer items-center gap-1 self-stretch whitespace-nowrap rounded-md px-1 py-0.5 text-xs",
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "STAGING"
+ region === "STAGING"
? "bg-light-blue text-dark-blue"
- : env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV"
+ : region === "DEV"
? "bg-light-green text-dark-green"
: "bg-light-red text-dark-red",
className,
)}
onClick={() => setIsHidden(true)}
>
- {["EU", "US", "HIPAA"].includes(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION)
- ? `PROD-${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}`
- : env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}
+ {region && ["EU", "US", "HIPAA"].includes(region)
+ ? `PROD-${region}`
+ : region}
</div>
);
};
diff --git a/web/src/components/VersionLabel.tsx b/web/src/components/VersionLabel.tsx
index 0e332f2fdb..bb03510654 100644
--- a/web/src/components/VersionLabel.tsx
+++ b/web/src/components/VersionLabel.tsx
@@ -20,20 +20,22 @@ import {
import { ArrowUp } from "lucide-react";
import { api } from "@/src/utils/api";
import { Button } from "@/src/components/ui/button";
-import { env } from "@/src/env.mjs";
import { cn } from "@/src/utils/tailwind";
import { usePlan } from "@/src/features/entitlements/hooks";
import { isSelfHostedPlan, planLabels } from "@langfuse/shared";
import { StatusBadge } from "@/src/components/layouts/status-badge";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
export const VersionLabel = ({ className }: { className?: string }) => {
+ const isLangfuseCloud = useLangfuseCloudRegion();
+
const backgroundMigrationStatus = api.backgroundMigrations.status.useQuery(
undefined,
{
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
- enabled: !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION, // do not check for updates on Langfuse Cloud
+ enabled: !isLangfuseCloud, // do not check for updates on Langfuse Cloud
throwOnError: false, // do not render default error message
},
);
@@ -42,12 +44,11 @@ export const VersionLabel = ({ className }: { className?: string }) => {
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
- enabled: !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION, // do not check for updates on Langfuse Cloud
+ enabled: !isLangfuseCloud, // do not check for updates on Langfuse Cloud
throwOnError: false, // do not render default error message
});
const plan = usePlan();
- const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
const selfHostedPlanLabel = !isLangfuseCloud
? plan && isSelfHostedPlan(plan)
@@ -107,7 +108,7 @@ export const VersionLabel = ({ className }: { className?: string }) => {
</DropdownMenuLabel>
<DropdownMenuSeparator />
</>
- ) : !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION ? (
+ ) : !isLangfuseCloud ? (
<>
<DropdownMenuLabel>This is the latest release</DropdownMenuLabel>
<DropdownMenuSeparator />
diff --git a/web/src/components/layouts/layout.tsx b/web/src/components/layouts/layout.tsx
index 26ab5d24fc..861c6ebe37 100644
--- a/web/src/components/layouts/layout.tsx
+++ b/web/src/components/layouts/layout.tsx
@@ -35,6 +35,7 @@ import {
processNavigation,
type NavigationItem,
} from "@/src/components/layouts/utilities/routes";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
const signOutUser = async () => {
sessionStorage.clear();
@@ -119,6 +120,7 @@ export default function Layout(props: PropsWithChildren) {
| string
| undefined;
const session = useSessionWithRetryOnUnauthenticated();
+ const { isLangfuseCloud, region } = useLangfuseCloudRegion();
const enableExperimentalFeatures =
session.data?.environment.enableExperimentalFeatures ?? false;
@@ -127,9 +129,7 @@ export default function Layout(props: PropsWithChildren) {
const uiCustomization = useUiCustomization();
- const cloudAdmin =
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined &&
- session.data?.user?.admin === true;
+ const cloudAdmin = isLangfuseCloud && session.data?.user?.admin === true;
// project info based on projectId in the URL
const { project, organization } = useQueryProjectOrOrganization();
@@ -319,13 +319,13 @@ export default function Layout(props: PropsWithChildren) {
rel="icon"
type="image/png"
sizes="32x32"
- href={`${env.NEXT_PUBLIC_BASE_PATH ?? ""}/favicon-32x32${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV" ? "-dev" : ""}.png`}
+ href={`${env.NEXT_PUBLIC_BASE_PATH ?? ""}/favicon-32x32${region === "DEV" ? "-dev" : ""}.png`}
/>
<link
rel="icon"
type="image/png"
sizes="16x16"
- href={`${env.NEXT_PUBLIC_BASE_PATH ?? ""}/favicon-16x16${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV" ? "-dev" : ""}.png`}
+ href={`${env.NEXT_PUBLIC_BASE_PATH ?? ""}/favicon-16x16${region === "DEV" ? "-dev" : ""}.png`}
/>
</Head>
<div>
diff --git a/web/src/components/nav/app-sidebar.tsx b/web/src/components/nav/app-sidebar.tsx
index 3089807b9d..2dfc2b697c 100644
--- a/web/src/components/nav/app-sidebar.tsx
+++ b/web/src/components/nav/app-sidebar.tsx
@@ -22,12 +22,12 @@ import {
import { env } from "@/src/env.mjs";
import { useRouter } from "next/router";
import Link from "next/link";
-
import { LangfuseLogo } from "@/src/components/LangfuseLogo";
import { SidebarNotifications } from "@/src/components/nav/sidebar-notifications";
import { UsageTracker } from "@/src/ee/features/billing/components/UsageTracker";
import { type RouteGroup } from "@/src/components/layouts/routes";
import { ExternalLink, Grid2X2 } from "lucide-react";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
type AppSidebarProps = {
navItems: {
@@ -75,6 +75,7 @@ export function AppSidebar({
const DemoBadge = () => {
const router = useRouter();
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
const routerProjectId = router.query.projectId as string | undefined;
if (
@@ -82,7 +83,7 @@ const DemoBadge = () => {
env.NEXT_PUBLIC_DEMO_ORG_ID &&
env.NEXT_PUBLIC_DEMO_PROJECT_ID &&
routerProjectId === env.NEXT_PUBLIC_DEMO_PROJECT_ID &&
- Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION)
+ isLangfuseCloud
)
)
return null;
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 55f27cd7ce..de4a5c9a41 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -167,7 +167,6 @@ export const env = createEnv({
OTEL_SERVICE_NAME: z.string().default("web"),
OTEL_TRACE_SAMPLING_RATIO: z.coerce.number().gt(0).lte(1).default(1),
-
// clickhouse
CLICKHOUSE_URL: z.string().url(),
CLICKHOUSE_CLUSTER_NAME: z.string().default("default"),
@@ -276,6 +275,17 @@ export const env = createEnv({
SLACK_CLIENT_ID: z.string().optional(),
SLACK_CLIENT_SECRET: z.string().optional(),
SLACK_STATE_SECRET: z.string().optional(),
+
+ // AWS Bedrock for langfuse native AI feature such as natural language filters
+ LANGFUSE_AWS_BEDROCK_MODEL: z.string().optional(),
+
+ // Tracing for Langfuse AI Features
+ LANGFUSE_AI_FEATURES_HOST: z.string().optional(),
+
+ // Natural Langfuse Filters
+ LANGFUSE_AI_FEATURES_PUBLIC_KEY: z.string().optional(),
+ LANGFUSE_AI_FEATURES_SECRET_KEY: z.string().optional(),
+ LANGFUSE_AI_FEATURES_PROJECT_ID: z.string().optional(),
},
/**
@@ -446,7 +456,6 @@ export const env = createEnv({
OTEL_SERVICE_NAME: process.env.OTEL_SERVICE_NAME,
OTEL_TRACE_SAMPLING_RATIO: process.env.OTEL_TRACE_SAMPLING_RATIO,
-
// S3 media upload
LANGFUSE_S3_MEDIA_MAX_CONTENT_LENGTH:
process.env.LANGFUSE_S3_MEDIA_MAX_CONTENT_LENGTH,
@@ -549,6 +558,20 @@ export const env = createEnv({
SLACK_CLIENT_ID: process.env.SLACK_CLIENT_ID,
SLACK_CLIENT_SECRET: process.env.SLACK_CLIENT_SECRET,
SLACK_STATE_SECRET: process.env.SLACK_STATE_SECRET,
+
+ // AWS Bedrock for langfuse native AI feature such as natural language filters
+ LANGFUSE_AWS_BEDROCK_MODEL: process.env.LANGFUSE_AWS_BEDROCK_MODEL,
+
+ // Langfuse Tracing AI Features
+ LANGFUSE_AI_FEATURES_HOST: process.env.LANGFUSE_AI_FEATURES_HOST,
+
+ // Natural Language Filters
+ LANGFUSE_AI_FEATURES_PUBLIC_KEY:
+ process.env.LANGFUSE_AI_FEATURES_PUBLIC_KEY,
+ LANGFUSE_AI_FEATURES_SECRET_KEY:
+ process.env.LANGFUSE_AI_FEATURES_SECRET_KEY,
+ LANGFUSE_AI_FEATURES_PROJECT_ID:
+ process.env.LANGFUSE_AI_FEATURES_PROJECT_ID,
},
// Skip validation in Docker builds
// DOCKER_BUILD is set in Dockerfile
diff --git a/web/src/features/auth/components/AuthCloudRegionSwitch.tsx b/web/src/features/auth/components/AuthCloudRegionSwitch.tsx
index e9d75e84e8..3161d68f58 100644
--- a/web/src/features/auth/components/AuthCloudRegionSwitch.tsx
+++ b/web/src/features/auth/components/AuthCloudRegionSwitch.tsx
@@ -16,6 +16,7 @@ import {
DialogTitle,
DialogTrigger,
} from "@/src/components/ui/dialog";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
const regions =
env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "STAGING"
@@ -58,12 +59,11 @@ export function CloudRegionSwitch({
isSignUpPage?: boolean;
}) {
const capture = usePostHogClientCapture();
+ const { isLangfuseCloud, region: cloudRegion } = useLangfuseCloudRegion();
- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === undefined) return null;
+ if (!isLangfuseCloud) return null;
- const currentRegion = regions.find(
- (region) => region.name === env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
- );
+ const currentRegion = regions.find((region) => region.name === cloudRegion);
return (
<div className="-mb-10 mt-8 rounded-lg bg-card px-6 py-6 text-sm sm:mx-auto sm:w-full sm:max-w-[480px] sm:rounded-lg sm:px-10">
@@ -73,7 +73,7 @@ export function CloudRegionSwitch({
Data Region
<DataRegionInfo />
</span>
- {isSignUpPage && env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "HIPAA" ? (
+ {isSignUpPage && cloudRegion === "HIPAA" ? (
<p className="text-xs text-muted-foreground">
Demo project is not available in the HIPAA data region.
</p>
@@ -111,7 +111,7 @@ export function CloudRegionSwitch({
</SelectContent>
</Select>
- {env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "HIPAA" && (
+ {cloudRegion === "HIPAA" && (
<div className="mt-2 rounded-md bg-muted/50 p-3 text-xs text-muted-foreground">
<p>
The Business Associate Agreement (BAA) is only effective on the
diff --git a/web/src/features/cloud-status-notification/components/CloudStatusMenu.tsx b/web/src/features/cloud-status-notification/components/CloudStatusMenu.tsx
index 8edf4a8a0a..02cd851e8a 100644
--- a/web/src/features/cloud-status-notification/components/CloudStatusMenu.tsx
+++ b/web/src/features/cloud-status-notification/components/CloudStatusMenu.tsx
@@ -1,10 +1,11 @@
import { api } from "@/src/utils/api";
-import { env } from "@/src/env.mjs";
import { cn } from "@/src/utils/tailwind";
import Link from "next/link";
import { SidebarMenuButton } from "@/src/components/ui/sidebar";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
export function CloudStatusMenu() {
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
const { data, isLoading } = api.cloudStatus.getStatus.useQuery(undefined, {
refetchOnMount: false,
refetchOnReconnect: false,
@@ -12,11 +13,11 @@ export function CloudStatusMenu() {
// Refresh status data every 5 minutes, keep response cached for 5 minutes
refetchInterval: 5 * 60 * 1000,
staleTime: 5 * 60 * 1000,
- enabled: !!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
+ enabled: !!isLangfuseCloud,
});
// Skip component rendering if not running on Langfuse Cloud
- if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
+ if (!isLangfuseCloud) {
return null;
}
diff --git a/web/src/features/filters/components/filter-builder.tsx b/web/src/features/filters/components/filter-builder.tsx
index ebf2667980..24ef5f7d26 100644
--- a/web/src/features/filters/components/filter-builder.tsx
+++ b/web/src/features/filters/components/filter-builder.tsx
@@ -1,5 +1,6 @@
import { Button } from "@/src/components/ui/button";
import { Input } from "@/src/components/ui/input";
+import { Textarea } from "@/src/components/ui/textarea";
import {
Select,
SelectContent,
@@ -9,12 +10,29 @@ import {
} from "@/src/components/ui/select";
import { DatePicker } from "@/src/components/date-picker";
import { useState, type Dispatch, type SetStateAction } from "react";
-import { Check, ChevronDown, Filter, Plus, X } from "lucide-react";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import { api } from "@/src/utils/api";
+import {
+ Check,
+ ChevronDown,
+ ExternalLink,
+ Filter,
+ Info,
+ Plus,
+ WandSparkles,
+ X,
+} from "lucide-react";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/src/components/ui/popover";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
import { MultiSelect } from "@/src/features/filters/components/multi-select";
import {
type WipFilterState,
@@ -36,6 +54,8 @@ import {
InputCommandItem,
InputCommandList,
} from "@/src/components/ui/input-command";
+import { useQueryProject } from "@/src/features/projects/hooks";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
// Has WipFilterState, passes all valid filters to parent onChange
export function PopoverFilterBuilder({
@@ -273,6 +293,15 @@ function FilterBuilderForm({
disabled?: boolean;
columnsWithCustomSelect?: string[];
}) {
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
+ const [showAiFilter, setShowAiFilter] = useState(false);
+ const [aiPrompt, setAiPrompt] = useState("");
+ const [aiError, setAiError] = useState<string | null>(null);
+ const projectId = useProjectIdFromURL();
+ const { organization } = useQueryProject();
+
+ const createFilterMutation =
+ api.naturalLanguageFilters.createCompletion.useMutation();
const handleFilterChange = (filter: WipFilterCondition, i: number) => {
onChange((prev) => {
const newState = [...prev];
@@ -302,332 +331,475 @@ function FilterBuilderForm({
});
};
+ const handleAiFilterSubmit = async () => {
+ if (aiPrompt.trim() && !createFilterMutation.isPending && projectId) {
+ setAiError(null);
+ try {
+ const result = await createFilterMutation.mutateAsync({
+ projectId,
+ prompt: aiPrompt.trim(),
+ });
+
+ if (result && Array.isArray(result.filters)) {
+ if (result.filters.length === 0) {
+ setAiError("Failed to generate filters, try again");
+ return;
+ }
+
+ // Set the filters from the API response
+ onChange(result.filters as WipFilterState);
+ setAiPrompt("");
+ setShowAiFilter(false);
+ } else {
+ console.error(result);
+ setAiError("Invalid response format from API");
+ }
+ } catch (error) {
+ console.error("Error calling tRPC API:", error);
+ setAiError(
+ error instanceof Error ? error.message : "Failed to generate filters",
+ );
+ }
+ }
+ };
+
return (
<>
- <table className="table-auto">
- <tbody>
- {filterState.map((filter, i) => {
- const column = columns.find(
- (c) => c.id === filter.column || c.name === filter.column,
- );
- return (
- <tr key={i}>
- <td className="p-1 text-sm">{i === 0 ? "Where" : "And"}</td>
- <td className="flex gap-2 p-1">
- {/* selector of the column to be filtered */}
- <Popover>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- role="combobox"
- type="button"
- disabled={disabled}
- className="flex w-full min-w-32 items-center justify-between gap-2"
- >
- <span className="truncate">
- {column ? column.name : "Column"}
- </span>
- <ChevronDown className="h-4 w-4 flex-shrink-0 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent
- className="max-w-fit p-0"
- onWheel={(e) => {
- e.stopPropagation();
- }}
- onTouchMove={(e) => {
- e.stopPropagation();
- }}
- >
- <InputCommand>
- <InputCommandInput
- placeholder="Search for column"
- onFocus={(e) => (e.target.style.border = "none")}
- />
- <InputCommandList>
- <InputCommandEmpty>
- No options found.
- </InputCommandEmpty>
- <InputCommandGroup>
- {columns.map((option) => (
- <InputCommandItem
- key={option.id}
- value={option.id}
- onSelect={(value) => {
- const col = columns.find(
- (c) => c.id === value,
- );
- const defaultOperator = col?.type
- ? getOperator(col.type)
- : undefined;
+ {/* AI Filter Section at the top */}
+ {!disabled && isLangfuseCloud && (
+ <div className="flex flex-col gap-2">
+ <Button
+ onClick={() => {
+ if (!organization?.aiFeaturesEnabled && organization?.id) {
+ window.open(
+ `/organization/${organization.id}/settings`,
+ "_blank",
+ );
+ } else {
+ setShowAiFilter(!showAiFilter);
+ }
+ }}
+ type="button"
+ variant="outline"
+ size="default"
+ disabled={false}
+ title={
+ !organization?.aiFeaturesEnabled
+ ? "AI features are disabled for your organization. Click to enable them in organization settings."
+ : undefined
+ }
+ className="w-full justify-start text-muted-foreground"
+ >
+ <WandSparkles className="mr-2 h-4 w-4" />
+ {!organization?.aiFeaturesEnabled ? (
+ <>
+ AI Filters: Enable in Organization Settings (Admin Only)
+ <ExternalLink className="ml-2 h-4 w-4" />
+ </>
+ ) : showAiFilter ? (
+ "Cancel"
+ ) : (
+ "Create Filter with AI"
+ )}
+ </Button>
+ {showAiFilter && (
+ <div className="flex flex-col gap-3">
+ <Textarea
+ value={aiPrompt}
+ onChange={(e) => {
+ setAiPrompt(e.target.value);
+ if (aiError) setAiError(null); // Clear error when user starts typing
+ }}
+ placeholder="Describe the filters you want to apply..."
+ className="min-h-[80px] min-w-[28rem] resize-none"
+ disabled={createFilterMutation.isPending}
+ onKeyDown={(e) => {
+ if (
+ e.key === "Enter" &&
+ e.ctrlKey &&
+ !createFilterMutation.isPending
+ ) {
+ handleAiFilterSubmit();
+ }
+ }}
+ />
+ <div className="flex items-center gap-2">
+ <Button
+ onClick={handleAiFilterSubmit}
+ type="button"
+ variant="default"
+ size="sm"
+ disabled={createFilterMutation.isPending || !aiPrompt.trim()}
+ >
+ {createFilterMutation.isPending
+ ? "Loading..."
+ : "Generate filters"}
+ </Button>
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info className="h-4 w-4 text-muted-foreground" />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p className="text-xs">
+ We convert natural language into deterministic filters
+ which you can adjust afterwards
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ {aiError && (
+ <div className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
+ {aiError}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Hide filter builder UI while AI filter is open */}
+ {!showAiFilter && (
+ <>
+ <table className="table-auto">
+ <tbody>
+ {filterState.map((filter, i) => {
+ const column = columns.find(
+ (c) => c.id === filter.column || c.name === filter.column,
+ );
+ return (
+ <tr key={i}>
+ <td className="p-1 text-sm">{i === 0 ? "Where" : "And"}</td>
+ <td className="flex gap-2 p-1">
+ {/* selector of the column to be filtered */}
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ type="button"
+ disabled={disabled}
+ className="flex w-full min-w-32 items-center justify-between gap-2"
+ >
+ <span className="truncate">
+ {column ? column.name : "Column"}
+ </span>
+ <ChevronDown className="h-4 w-4 flex-shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ className="max-w-fit p-0"
+ onWheel={(e) => {
+ e.stopPropagation();
+ }}
+ onTouchMove={(e) => {
+ e.stopPropagation();
+ }}
+ >
+ <InputCommand>
+ <InputCommandInput
+ placeholder="Search for column"
+ onFocus={(e) => (e.target.style.border = "none")}
+ />
+ <InputCommandList>
+ <InputCommandEmpty>
+ No options found.
+ </InputCommandEmpty>
+ <InputCommandGroup>
+ {columns.map((option) => (
+ <InputCommandItem
+ key={option.id}
+ value={option.id}
+ onSelect={(value) => {
+ const col = columns.find(
+ (c) => c.id === value,
+ );
+ const defaultOperator = col?.type
+ ? getOperator(col.type)
+ : undefined;
- handleFilterChange(
- {
- column: col?.name,
- type: col?.type,
- operator: defaultOperator,
- value: undefined,
- key: undefined,
- } as WipFilterCondition,
- i,
- );
- }}
+ handleFilterChange(
+ {
+ column: col?.name,
+ type: col?.type,
+ operator: defaultOperator,
+ value: undefined,
+ key: undefined,
+ } as WipFilterCondition,
+ i,
+ );
+ }}
+ >
+ <Check
+ className={cn(
+ "mr-2 h-4 w-4",
+ option.id === column?.id
+ ? "visible"
+ : "invisible",
+ )}
+ />
+ {option.name}
+ </InputCommandItem>
+ ))}
+ </InputCommandGroup>
+ </InputCommandList>
+ </InputCommand>
+ </PopoverContent>
+ </Popover>
+ {filter.type &&
+ (filter.type === "numberObject" ||
+ filter.type === "stringObject") &&
+ (column?.type === "numberObject" ||
+ column?.type === "stringObject") ? (
+ column.keyOptions ? (
+ // Case 1: object with keyOptions - selector of the key of the object
+ <Select
+ disabled={!filter.column}
+ onValueChange={(value) => {
+ handleFilterChange({ ...filter, key: value }, i);
+ }}
+ value={filter.key ?? ""}
+ >
+ <SelectTrigger className="min-w-[60px]">
+ <SelectValue placeholder="" />
+ </SelectTrigger>
+ <SelectContent>
+ {column.keyOptions
+ .filter(
+ (o) => NonEmptyString.safeParse(o).success,
+ )
+ .map((option) => (
+ <SelectItem key={option} value={option}>
+ {option}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ // Case 2: object without keyOptions - text input
+ <Input
+ value={filter.key ?? ""}
+ placeholder="key"
+ disabled={disabled}
+ onChange={(e) =>
+ handleFilterChange(
+ { ...filter, key: e.target.value },
+ i,
+ )
+ }
+ />
+ )
+ ) : filter.type === "categoryOptions" &&
+ column?.type === "categoryOptions" ? (
+ // Case 3: categoryOptions
+ <Select
+ onValueChange={(value) => {
+ handleFilterChange({ ...filter, key: value }, i);
+ }}
+ value={filter.key ?? ""}
+ >
+ <SelectTrigger className="min-w-[60px]">
+ <SelectValue placeholder="" />
+ </SelectTrigger>
+ <SelectContent>
+ {column?.options.map((option) => (
+ <SelectItem
+ key={option.label}
+ value={option.label}
>
- <Check
- className={cn(
- "mr-2 h-4 w-4",
- option.id === column?.id
- ? "visible"
- : "invisible",
- )}
- />
- {option.name}
- </InputCommandItem>
+ {option.label}
+ </SelectItem>
))}
- </InputCommandGroup>
- </InputCommandList>
- </InputCommand>
- </PopoverContent>
- </Popover>
- {filter.type &&
- (filter.type === "numberObject" ||
- filter.type === "stringObject") &&
- (column?.type === "numberObject" ||
- column?.type === "stringObject") ? (
- column.keyOptions ? (
- // Case 1: object with keyOptions - selector of the key of the object
+ </SelectContent>
+ </Select>
+ ) : null}
+ </td>
+ <td className="p-1">
<Select
- disabled={!filter.column}
+ disabled={!filter.column || disabled}
onValueChange={(value) => {
- handleFilterChange({ ...filter, key: value }, i);
+ // protect against invalid empty operator values
+ if (value === "") return;
+ handleFilterChange(
+ {
+ ...filter,
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
+ operator: value as any,
+ },
+ i,
+ );
}}
- value={filter.key ?? ""}
+ value={filter.operator ?? ""}
>
<SelectTrigger className="min-w-[60px]">
<SelectValue placeholder="" />
</SelectTrigger>
<SelectContent>
- {column.keyOptions
- .filter((o) => NonEmptyString.safeParse(o).success)
- .map((option) => (
+ {filter.type !== undefined
+ ? filterOperators[filter.type].map((option) => (
+ <SelectItem key={option} value={option}>
+ {option}
+ </SelectItem>
+ ))
+ : null}
+ </SelectContent>
+ </Select>
+ </td>
+ <td className="p-1">
+ {filter.type === "string" ||
+ filter.type === "stringObject" ? (
+ <Input
+ disabled={disabled}
+ value={filter.value ?? ""}
+ placeholder="string"
+ onChange={(e) =>
+ handleFilterChange(
+ { ...filter, value: e.target.value },
+ i,
+ )
+ }
+ />
+ ) : filter.type === "number" ||
+ filter.type === "numberObject" ? (
+ <Input
+ value={filter.value ?? undefined}
+ disabled={disabled}
+ type="number"
+ step="0.01"
+ lang="en-US"
+ onChange={(e) =>
+ handleFilterChange(
+ {
+ ...filter,
+ value: isNaN(Number(e.target.value))
+ ? e.target.value
+ : Number(e.target.value),
+ },
+ i,
+ )
+ }
+ />
+ ) : filter.type === "datetime" ? (
+ <DatePicker
+ className="w-full"
+ disabled={disabled}
+ date={
+ filter.value ? new Date(filter.value) : undefined
+ }
+ onChange={(date) => {
+ handleFilterChange(
+ {
+ ...filter,
+ value: date,
+ },
+ i,
+ );
+ }}
+ includeTimePicker
+ />
+ ) : filter.type === "stringOptions" ||
+ filter.type === "arrayOptions" ? (
+ <MultiSelect
+ title="Value"
+ className="min-w-[100px]"
+ options={
+ column?.type === filter.type ? column.options : []
+ }
+ onValueChange={(value) =>
+ handleFilterChange({ ...filter, value }, i)
+ }
+ values={
+ Array.isArray(filter.value) ? filter.value : []
+ }
+ disabled={disabled}
+ isCustomSelectEnabled={
+ column?.type === filter.type &&
+ columnsWithCustomSelect.includes(column.id)
+ }
+ />
+ ) : filter.type === "categoryOptions" &&
+ column?.type === "categoryOptions" ? (
+ <MultiSelect
+ title="Value"
+ className="min-w-[100px]"
+ options={
+ column?.options
+ .find((o) => o.label === filter.key)
+ ?.values?.map((v) => ({ value: v })) ?? []
+ }
+ onValueChange={(value) =>
+ handleFilterChange({ ...filter, value }, i)
+ }
+ values={
+ Array.isArray(filter.value) ? filter.value : []
+ }
+ disabled={disabled}
+ isCustomSelectEnabled={
+ column?.type === filter.type &&
+ columnsWithCustomSelect.includes(column.id)
+ }
+ />
+ ) : filter.type === "boolean" ? (
+ <Select
+ disabled={disabled}
+ onValueChange={(value) => {
+ handleFilterChange(
+ {
+ ...filter,
+ value:
+ value !== "" ? value === "true" : undefined,
+ },
+ i,
+ );
+ }}
+ value={filter.value?.toString() ?? ""}
+ >
+ <SelectTrigger className="min-w-[60px]">
+ <SelectValue placeholder="" />
+ </SelectTrigger>
+ <SelectContent>
+ {["true", "false"].map((option) => (
<SelectItem key={option} value={option}>
{option}
</SelectItem>
))}
- </SelectContent>
- </Select>
- ) : (
- // Case 2: object without keyOptions - text input
- <Input
- value={filter.key ?? ""}
- placeholder="key"
+ </SelectContent>
+ </Select>
+ ) : (
+ <Input disabled />
+ )}
+ </td>
+ <td>
+ <Button
+ onClick={() => removeFilter(i)}
+ variant="ghost"
+ type="button"
disabled={disabled}
- onChange={(e) =>
- handleFilterChange(
- { ...filter, key: e.target.value },
- i,
- )
- }
- />
- )
- ) : filter.type === "categoryOptions" &&
- column?.type === "categoryOptions" ? (
- // Case 3: categoryOptions
- <Select
- onValueChange={(value) => {
- handleFilterChange({ ...filter, key: value }, i);
- }}
- value={filter.key ?? ""}
- >
- <SelectTrigger className="min-w-[60px]">
- <SelectValue placeholder="" />
- </SelectTrigger>
- <SelectContent>
- {column?.options.map((option) => (
- <SelectItem key={option.label} value={option.label}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- ) : null}
- </td>
- <td className="p-1">
- <Select
- disabled={!filter.column || disabled}
- onValueChange={(value) => {
- // protect against invalid empty operator values
- if (value === "") return;
- handleFilterChange(
- {
- ...filter,
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
- operator: value as any,
- },
- i,
- );
- }}
- value={filter.operator ?? ""}
- >
- <SelectTrigger className="min-w-[60px]">
- <SelectValue placeholder="" />
- </SelectTrigger>
- <SelectContent>
- {filter.type !== undefined
- ? filterOperators[filter.type].map((option) => (
- <SelectItem key={option} value={option}>
- {option}
- </SelectItem>
- ))
- : null}
- </SelectContent>
- </Select>
- </td>
- <td className="p-1">
- {filter.type === "string" ||
- filter.type === "stringObject" ? (
- <Input
- disabled={disabled}
- value={filter.value ?? ""}
- placeholder="string"
- onChange={(e) =>
- handleFilterChange(
- { ...filter, value: e.target.value },
- i,
- )
- }
- />
- ) : filter.type === "number" ||
- filter.type === "numberObject" ? (
- <Input
- value={filter.value ?? undefined}
- disabled={disabled}
- type="number"
- step="0.01"
- lang="en-US"
- onChange={(e) =>
- handleFilterChange(
- {
- ...filter,
- value: isNaN(Number(e.target.value))
- ? e.target.value
- : Number(e.target.value),
- },
- i,
- )
- }
- />
- ) : filter.type === "datetime" ? (
- <DatePicker
- className="w-full"
- disabled={disabled}
- date={filter.value ? new Date(filter.value) : undefined}
- onChange={(date) => {
- handleFilterChange(
- {
- ...filter,
- value: date,
- },
- i,
- );
- }}
- includeTimePicker
- />
- ) : filter.type === "stringOptions" ||
- filter.type === "arrayOptions" ? (
- <MultiSelect
- title="Value"
- className="min-w-[100px]"
- options={
- column?.type === filter.type ? column.options : []
- }
- onValueChange={(value) =>
- handleFilterChange({ ...filter, value }, i)
- }
- values={Array.isArray(filter.value) ? filter.value : []}
- disabled={disabled}
- isCustomSelectEnabled={
- column?.type === filter.type &&
- columnsWithCustomSelect.includes(column.id)
- }
- />
- ) : filter.type === "categoryOptions" &&
- column?.type === "categoryOptions" ? (
- <MultiSelect
- title="Value"
- className="min-w-[100px]"
- options={
- column?.options
- .find((o) => o.label === filter.key)
- ?.values?.map((v) => ({ value: v })) ?? []
- }
- onValueChange={(value) =>
- handleFilterChange({ ...filter, value }, i)
- }
- values={Array.isArray(filter.value) ? filter.value : []}
- disabled={disabled}
- isCustomSelectEnabled={
- column?.type === filter.type &&
- columnsWithCustomSelect.includes(column.id)
- }
- />
- ) : filter.type === "boolean" ? (
- <Select
- disabled={disabled}
- onValueChange={(value) => {
- handleFilterChange(
- {
- ...filter,
- value: value !== "" ? value === "true" : undefined,
- },
- i,
- );
- }}
- value={filter.value?.toString() ?? ""}
- >
- <SelectTrigger className="min-w-[60px]">
- <SelectValue placeholder="" />
- </SelectTrigger>
- <SelectContent>
- {["true", "false"].map((option) => (
- <SelectItem key={option} value={option}>
- {option}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- ) : (
- <Input disabled />
- )}
- </td>
- <td>
- <Button
- onClick={() => removeFilter(i)}
- variant="ghost"
- type="button"
- disabled={disabled}
- size="xs"
- >
- <X className="h-4 w-4" />
- </Button>
- </td>
- </tr>
- );
- })}
- </tbody>
- </table>
- {!disabled ? (
- <Button
- onClick={() => addNewFilter()}
- type="button" // required as it will otherwise submit forms where this component is used
- className="mt-2"
- variant="outline"
- size="sm"
- >
- <Plus className="mr-2 h-4 w-4" />
- Add filter
- </Button>
- ) : null}
+ size="xs"
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ {!disabled ? (
+ <Button
+ onClick={() => addNewFilter()}
+ type="button" // required as it will otherwise submit forms where this component is used
+ className="mt-2"
+ variant="outline"
+ size="sm"
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ Add filter
+ </Button>
+ ) : null}
+ </>
+ )}
</>
);
}
diff --git a/web/src/features/filters/hooks/useFilterState.ts b/web/src/features/filters/hooks/useFilterState.ts
index 953551296e..7460d5da86 100644
--- a/web/src/features/filters/hooks/useFilterState.ts
+++ b/web/src/features/filters/hooks/useFilterState.ts
@@ -30,28 +30,34 @@ const DEBUG_QUERY_STATE = false;
const getCommaArrayParam = (table: TableName) => ({
encode: (filterState: FilterState) =>
encodeDelimitedArray(
- filterState.map((f) => {
- const columnId = getColumnId(table, f.column);
+ filterState
+ .map((f) => {
+ const columnId = getColumnId(table, f.column);
- const stringified = `${columnId};${f.type};${
- f.type === "numberObject" ||
- f.type === "stringObject" ||
- f.type === "categoryOptions"
- ? f.key
- : ""
- };${f.operator};${encodeURIComponent(
- f.type === "datetime"
- ? new Date(f.value).toISOString()
- : f.type === "stringOptions" ||
- f.type === "arrayOptions" ||
- f.type === "categoryOptions"
- ? f.value.join("|")
- : f.value,
- )}`;
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
- if (DEBUG_QUERY_STATE) console.log("stringified", stringified);
- return stringified;
- }),
+ if (!columnId) {
+ return null;
+ }
+
+ const stringified = `${columnId};${f.type};${
+ f.type === "numberObject" ||
+ f.type === "stringObject" ||
+ f.type === "categoryOptions"
+ ? f.key
+ : ""
+ };${f.operator};${encodeURIComponent(
+ f.type === "datetime"
+ ? new Date(f.value).toISOString()
+ : f.type === "stringOptions" ||
+ f.type === "arrayOptions" ||
+ f.type === "categoryOptions"
+ ? f.value.join("|")
+ : f.value,
+ )}`;
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+ if (DEBUG_QUERY_STATE) console.log("stringified", stringified);
+ return stringified;
+ })
+ .filter((s): s is string => s !== null),
",",
),
@@ -166,7 +172,10 @@ const tableCols = {
};
function getColumnId(table: TableName, name: string): string | undefined {
- return tableCols[table]?.find((col) => col.name === name)?.id;
+ // TODO: make this more robust, will change with new filters
+ // to give more leeway to LLMs, we check against name or id
+ return tableCols[table]?.find((col) => col.name === name || col.id === name)
+ ?.id;
}
function getColumnName(table: TableName, id: string): string | undefined {
diff --git a/web/src/features/natural-language-filters/server/router.ts b/web/src/features/natural-language-filters/server/router.ts
new file mode 100644
index 0000000000..83f0b46a5a
--- /dev/null
+++ b/web/src/features/natural-language-filters/server/router.ts
@@ -0,0 +1,149 @@
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import { TRPCError } from "@trpc/server";
+import {
+ type ChatMessage,
+ ChatMessageType,
+ fetchLLMCompletion,
+ logger,
+ type TraceParams,
+} from "@langfuse/shared/src/server";
+import { env } from "@/src/env.mjs";
+import { CreateNaturalLanguageFilterCompletion } from "./validation";
+import {
+ getDefaultModelParams,
+ parseFiltersFromCompletion,
+ getLangfuseClient,
+} from "./utils";
+import { randomBytes } from "crypto";
+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { BEDROCK_USE_DEFAULT_CREDENTIALS } from "@langfuse/shared";
+
+export const naturalLanguageFilterRouter = createTRPCRouter({
+ createCompletion: protectedProjectProcedure
+ .input(CreateNaturalLanguageFilterCompletion)
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "prompts:CUD",
+ });
+
+ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message:
+ "Natural language filtering is not available in self-hosted deployments.",
+ });
+ }
+
+ if (!env.LANGFUSE_AWS_BEDROCK_MODEL) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message:
+ "Bedrock environment variables not configured. Please set LANGFUSE_AWS_BEDROCK_* variables.",
+ });
+ }
+
+ if (
+ !env.LANGFUSE_AI_FEATURES_PUBLIC_KEY ||
+ !env.LANGFUSE_AI_FEATURES_SECRET_KEY
+ ) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message:
+ "Langfuse AI filters environment variables not configured. Please set LANGFUSE_AI_FEATURES_PUBLIC_KEY and LANGFUSE_AI_FEATURES_SECRET_KEY variables.",
+ });
+ }
+
+ const getEnvironment = (): string => {
+ switch (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
+ case "US":
+ case "EU":
+ case "HIPAA":
+ return "prod";
+ case "STAGING":
+ return "staging";
+ default:
+ return "dev";
+ }
+ };
+
+ const traceParams: TraceParams = {
+ environment: getEnvironment(),
+ traceName: "natural-language-filter",
+ traceId: randomBytes(16).toString("hex"),
+ projectId: env.LANGFUSE_AI_FEATURES_PROJECT_ID as string,
+ authCheck: {
+ validKey: true as const,
+ scope: {
+ projectId: env.LANGFUSE_AI_FEATURES_PROJECT_ID,
+ accessLevel: "project",
+ } as any,
+ },
+ };
+
+ const client = getLangfuseClient(
+ env.LANGFUSE_AI_FEATURES_PUBLIC_KEY as string,
+ env.LANGFUSE_AI_FEATURES_SECRET_KEY as string,
+ env.LANGFUSE_AI_FEATURES_HOST,
+ );
+
+ const promptResponse = await client.getPrompt(
+ "get-filter-conditions-from-query",
+ undefined,
+ { type: "chat" },
+ );
+
+ const messages = promptResponse.compile({ userPrompt: input.prompt });
+ const modelParams = getDefaultModelParams();
+
+ const llmCompletion = await fetchLLMCompletion({
+ messages: messages.map((m: ChatMessage) => ({
+ ...m,
+ type: ChatMessageType.PublicAPICreated,
+ })),
+ modelParams,
+ apiKey: BEDROCK_USE_DEFAULT_CREDENTIALS,
+ streaming: false,
+ traceParams,
+ context: {
+ tracing: "langfuse",
+ credentials: "langfuse",
+ },
+ });
+
+ await llmCompletion.processTracedEvents();
+
+ logger.info(
+ `LLM completion received: ${JSON.stringify(llmCompletion.completion, null, 2)}`,
+ );
+
+ const parsedFilters = parseFiltersFromCompletion(
+ llmCompletion.completion as string,
+ );
+
+ return {
+ filters: parsedFilters,
+ };
+ } catch (error) {
+ logger.error(
+ "Failed to create natural language filter completion: ",
+ error,
+ );
+
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message:
+ "The AI backend currently appears to be unavailable. Please try again later.",
+ });
+ }
+ }),
+});
diff --git a/web/src/features/natural-language-filters/server/utils.ts b/web/src/features/natural-language-filters/server/utils.ts
new file mode 100644
index 0000000000..d4cf28c232
--- /dev/null
+++ b/web/src/features/natural-language-filters/server/utils.ts
@@ -0,0 +1,62 @@
+import { LLMAdapter } from "@langfuse/shared/src/server";
+import { Langfuse } from "langfuse";
+import { env } from "@/src/env.mjs";
+import { type FilterCondition, singleFilter } from "@langfuse/shared";
+import { z } from "zod/v4";
+
+let langfuseClient: Langfuse | null = null;
+
+export function getDefaultModelParams() {
+ return {
+ provider: "bedrock",
+ adapter: LLMAdapter.Bedrock,
+ model: env.LANGFUSE_AWS_BEDROCK_MODEL ?? "",
+ temperature: 0.1,
+ maxTokens: 1000,
+ topP: 0.9,
+ };
+}
+
+const FilterArraySchema = z.array(singleFilter);
+
+export function parseFiltersFromCompletion(
+ completion: string,
+): FilterCondition[] {
+ const arrayMatch = completion.match(/\[[\s\S]*?\]/)?.[0];
+ const objectMatch = completion.match(/\{[\s\S]*?\}/)?.[0];
+
+ const candidates = [
+ completion, // full response
+ arrayMatch, // extract JSON array
+ objectMatch ? `[${objectMatch}]` : undefined, // wrap single object in array
+ ].filter((c): c is string => Boolean(c));
+
+ for (const candidate of candidates) {
+ try {
+ const parsed = JSON.parse(candidate);
+
+ // sometimes, ai returns {filters: [...]}, extract the filters array
+ const filtersArray = parsed.filters || parsed;
+ const validated = FilterArraySchema.parse(filtersArray);
+ return validated;
+ } catch {
+ // try next candidate
+ }
+ }
+ return [];
+}
+
+export function getLangfuseClient(
+ publicKey: string,
+ secretKey: string,
+ baseUrl?: string,
+): Langfuse {
+ if (!langfuseClient) {
+ langfuseClient = new Langfuse({
+ publicKey,
+ secretKey,
+ baseUrl,
+ });
+ }
+ return langfuseClient;
+}
diff --git a/web/src/features/natural-language-filters/server/validation.ts b/web/src/features/natural-language-filters/server/validation.ts
new file mode 100644
index 0000000000..20e6f7c07d
--- /dev/null
+++ b/web/src/features/natural-language-filters/server/validation.ts
@@ -0,0 +1,10 @@
+import { z } from "zod/v4";
+
+export const CreateNaturalLanguageFilterCompletion = z.object({
+ projectId: z.string(),
+ prompt: z.string().min(1).max(2048),
+});
+
+export type CreateNaturalLanguageFilterCompletionInput = z.infer<
+ typeof CreateNaturalLanguageFilterCompletion
+>;
diff --git a/web/src/features/organizations/components/AIFeatureSwitch.tsx b/web/src/features/organizations/components/AIFeatureSwitch.tsx
new file mode 100644
index 0000000000..3d5ceffb60
--- /dev/null
+++ b/web/src/features/organizations/components/AIFeatureSwitch.tsx
@@ -0,0 +1,187 @@
+import { Button } from "@/src/components/ui/button";
+import { Switch } from "@/src/components/ui/switch";
+import { api } from "@/src/utils/api";
+import { useState } from "react";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/src/components/ui/dialog";
+import Header from "@/src/components/layouts/header";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import {
+ useLangfuseCloudRegion,
+ useQueryOrganization,
+} from "@/src/features/organizations/hooks";
+import { Card } from "@/src/components/ui/card";
+import { LockIcon, ExternalLink } from "lucide-react";
+import { useSession } from "next-auth/react";
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import * as z from "zod/v4";
+
+const aiFeaturesSchema = z.object({
+ aiFeaturesEnabled: z.boolean(),
+});
+
+export default function AIFeatureSwitch() {
+ const { update: updateSession } = useSession();
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
+ const capture = usePostHogClientCapture();
+ const organization = useQueryOrganization();
+ const [isAIFeatureSwitchEnabled, setIsAIFeatureSwitchEnabled] = useState(
+ organization?.aiFeaturesEnabled ?? false,
+ );
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const hasAccess = useHasOrganizationAccess({
+ organizationId: organization?.id,
+ scope: "organization:update",
+ });
+
+ const confirmForm = useForm<z.infer<typeof aiFeaturesSchema>>({
+ resolver: zodResolver(aiFeaturesSchema),
+ defaultValues: {
+ aiFeaturesEnabled: isAIFeatureSwitchEnabled,
+ },
+ });
+
+ const updateAIFeatures = api.organizations.update.useMutation({
+ onSuccess: () => {
+ void updateSession();
+ setConfirmOpen(false);
+ },
+ onError: () => {
+ setConfirmOpen(false);
+ },
+ });
+
+ function handleSwitchChange(newValue: boolean) {
+ if (!hasAccess) return;
+ setIsAIFeatureSwitchEnabled(newValue);
+ confirmForm.setValue("aiFeaturesEnabled", newValue);
+ setConfirmOpen(true);
+ }
+
+ function handleCancel() {
+ setIsAIFeatureSwitchEnabled(organization?.aiFeaturesEnabled ?? false);
+ setConfirmOpen(false);
+ }
+
+ function handleConfirm() {
+ if (!organization || !hasAccess) return;
+ capture("organization_settings:ai_features_toggle");
+ updateAIFeatures.mutate({
+ orgId: organization.id,
+ aiFeaturesEnabled: isAIFeatureSwitchEnabled,
+ });
+ }
+
+ if (!isLangfuseCloud) return null;
+
+ return (
+ <div>
+ <Header title="AI Features" />
+ <Card className="mb-4 p-3">
+ <div className="flex flex-row items-center justify-between">
+ <div className="flex flex-col gap-1">
+ <h4 className="font-semibold">
+ Enable AI powered features for your organization
+ </h4>
+ <p className="text-sm">
+ Enable AI powered features for your organization. This setting
+ applies to all users and projects. Any data <i>can</i> be sent to
+ AWS Bedrock within the Langfuse data region. Traces are sent to
+ Langfuse Cloud in your data region. Your data will not be used for
+ training models. Applicable HIPAA, SOC2, GDPR, and ISO 27001
+ compliance remains intact.{" "}
+ <a
+ href="https://langfuse.com/docs/security/ai-features"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-1 text-primary hover:underline"
+ >
+ More details in the docs here.
+ <ExternalLink className="h-3 w-3" />
+ </a>
+ </p>
+ </div>
+ <div className="relative">
+ <Switch
+ checked={isAIFeatureSwitchEnabled}
+ onCheckedChange={handleSwitchChange}
+ disabled={!hasAccess}
+ />
+ {!hasAccess && (
+ <span title="No access">
+ <LockIcon className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 transform text-muted" />
+ </span>
+ )}
+ </div>
+ </div>
+ </Card>
+
+ <Dialog
+ open={confirmOpen}
+ onOpenChange={(isOpen) => {
+ if (!isOpen && !updateAIFeatures.isPending) {
+ handleCancel();
+ }
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Confirm AI Features Change</DialogTitle>
+ </DialogHeader>
+ <DialogBody>
+ <span className="text-sm">
+ You are about to{" "}
+ <strong>
+ {isAIFeatureSwitchEnabled ? "enable " : "disable"}
+ </strong>{" "}
+ AI features for your organization. When enabled, any data{" "}
+ <i>can</i> be sent to AWS Bedrock in your data region for
+ processing.
+ <br />
+ <br />{" "}
+ <a
+ href="https://langfuse.com/docs/security/ai-features"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-1 text-primary hover:underline"
+ >
+ Learn more in the docs.
+ <ExternalLink className="h-3 w-3" />
+ </a>
+ </span>
+ <p className="mt-3 text-sm text-muted-foreground">
+ Are you sure you want to proceed?
+ </p>
+ </DialogBody>
+ <DialogFooter>
+ <div className="flex justify-end space-x-2">
+ <Button
+ type="button"
+ variant="outline"
+ disabled={updateAIFeatures.isPending}
+ onClick={handleCancel}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ onClick={handleConfirm}
+ loading={updateAIFeatures.isPending}
+ >
+ Confirm
+ </Button>
+ </div>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
diff --git a/web/src/features/organizations/components/NewOrganizationForm.tsx b/web/src/features/organizations/components/NewOrganizationForm.tsx
index 7ac721caa3..9e9492466c 100644
--- a/web/src/features/organizations/components/NewOrganizationForm.tsx
+++ b/web/src/features/organizations/components/NewOrganizationForm.tsx
@@ -25,7 +25,7 @@ import { useSession } from "next-auth/react";
import { organizationFormSchema } from "@/src/features/organizations/utils/organizationNameSchema";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { SurveyName } from "@prisma/client";
-import { env } from "@/src/env.mjs";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
export const NewOrganizationForm = ({
onSuccess,
@@ -48,7 +48,7 @@ export const NewOrganizationForm = ({
});
const createSurveyMutation = api.surveys.create.useMutation();
const watchedType = form.watch("type");
- const isCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
function onSubmit(values: z.infer<typeof organizationFormSchema>) {
capture("organizations:new_form_submit");
@@ -58,7 +58,7 @@ export const NewOrganizationForm = ({
})
.then(async (org) => {
// Submit survey with organization data only on Cloud and if type is provided
- if (isCloud && values.type) {
+ if (isLangfuseCloud && values.type) {
const surveyResponse: Record<string, string> = {
type: values.type,
};
@@ -119,7 +119,7 @@ export const NewOrganizationForm = ({
</FormItem>
)}
/>
- {isCloud && (
+ {isLangfuseCloud && (
<>
<FormField
control={form.control}
diff --git a/web/src/features/organizations/hooks.ts b/web/src/features/organizations/hooks.ts
index 6aa3a117d0..56d7ec5335 100644
--- a/web/src/features/organizations/hooks.ts
+++ b/web/src/features/organizations/hooks.ts
@@ -1,3 +1,4 @@
+import { env } from "@/src/env.mjs";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
@@ -22,3 +23,13 @@ export const useOrganization = (organizationId: string | null) => {
return organization ?? null;
};
+
+export const useLangfuseCloudRegion = (): {
+ isLangfuseCloud: boolean;
+ region: string | undefined;
+} => {
+ return {
+ isLangfuseCloud: Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION),
+ region: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
+ };
+};
diff --git a/web/src/features/organizations/server/organizationRouter.ts b/web/src/features/organizations/server/organizationRouter.ts
index 883899e2a8..a47d5b6593 100644
--- a/web/src/features/organizations/server/organizationRouter.ts
+++ b/web/src/features/organizations/server/organizationRouter.ts
@@ -4,13 +4,17 @@ import {
authenticatedProcedure,
} from "@/src/server/api/trpc";
import { auditLog } from "@/src/features/audit-logs/auditLog";
-import { organizationNameSchema } from "@/src/features/organizations/utils/organizationNameSchema";
+import {
+ organizationOptionalNameSchema,
+ organizationNameSchema,
+} from "@/src/features/organizations/utils/organizationNameSchema";
import * as z from "zod/v4";
import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
import { TRPCError } from "@trpc/server";
import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { redis } from "@langfuse/shared/src/server";
import { createBillingServiceFromContext } from "@/src/ee/features/billing/server/stripeBillingService";
+import { env } from "@/src/env.mjs";
export const organizationsRouter = createTRPCRouter({
create: authenticatedProcedure
@@ -51,9 +55,14 @@ export const organizationsRouter = createTRPCRouter({
}),
update: protectedOrganizationProcedure
.input(
- organizationNameSchema.extend({
- orgId: z.string(),
- }),
+ organizationOptionalNameSchema
+ .extend({
+ orgId: z.string(),
+ aiFeaturesEnabled: z.boolean().optional(),
+ })
+ .refine((data) => data.name || data.aiFeaturesEnabled !== undefined, {
+ message: "At least one of name or aiFeaturesEnabled is required",
+ }),
)
.mutation(async ({ input, ctx }) => {
throwIfNoOrganizationAccess({
@@ -61,6 +70,18 @@ export const organizationsRouter = createTRPCRouter({
organizationId: input.orgId,
scope: "organization:update",
});
+
+ if (
+ input.aiFeaturesEnabled !== undefined &&
+ !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
+ ) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message:
+ "Natural language filtering is not available in self-hosted deployments.",
+ });
+ }
+
const beforeOrganization = await ctx.prisma.organization.findFirst({
where: {
id: input.orgId,
@@ -72,6 +93,7 @@ export const organizationsRouter = createTRPCRouter({
},
data: {
name: input.name,
+ aiFeaturesEnabled: input.aiFeaturesEnabled,
},
});
diff --git a/web/src/features/organizations/utils/organizationNameSchema.ts b/web/src/features/organizations/utils/organizationNameSchema.ts
index 4ea76b34bb..564f92242e 100644
--- a/web/src/features/organizations/utils/organizationNameSchema.ts
+++ b/web/src/features/organizations/utils/organizationNameSchema.ts
@@ -18,12 +18,18 @@ const organizationSizeOptions = [
"More than 300",
] as const;
+const organizationName = StringNoHTML.min(
+ 3,
+ "Must have at least 3 characters",
+).max(60, "Must have at most 60 characters");
+
// Base schema for org creation, used for server-side validation too
export const organizationNameSchema = z.object({
- name: StringNoHTML.min(3, "Must have at least 3 characters").max(
- 60,
- "Must have at most 60 characters",
- ),
+ name: organizationName,
+});
+
+export const organizationOptionalNameSchema = z.object({
+ name: organizationName.optional(),
});
// Extended schema for client-side form validation including type and size,
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 830be1781d..4388ebc825 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -183,6 +183,7 @@ const events = {
"api_key_delete",
"pricing_dialog_opened",
"delete_organization",
+ "ai_features_toggle",
],
help_popup: ["opened", "href_clicked"],
navigate_detail_pages: ["button_click_prev_or_next"],
diff --git a/web/src/features/support-chat/IntroSection.tsx b/web/src/features/support-chat/IntroSection.tsx
index b16d4398e6..2cad1ad417 100644
--- a/web/src/features/support-chat/IntroSection.tsx
+++ b/web/src/features/support-chat/IntroSection.tsx
@@ -16,8 +16,7 @@ import { Separator } from "@/src/components/ui/separator";
import { usePlan } from "@/src/features/entitlements/hooks";
import { isCloudPlan } from "@langfuse/shared";
import { useUiCustomization } from "@/src/ee/features/ui-customization/useUiCustomization";
-
-import { env } from "@/src/env.mjs";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
type SupportType = "in-app-support" | "custom" | "community";
@@ -28,6 +27,7 @@ export function IntroSection({
displayDensity?: "default" | "compact";
}) {
const uiCustomization = useUiCustomization();
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
// Note: We previously added an entitlement for in-app support, but removed it for now.
// The issue was that on global routes e.g., https://langfuse.com/setup, the entitlement
@@ -35,7 +35,7 @@ export function IntroSection({
// false if asked. However on these pages, the in-app-chat should be available.
// Therefore we now check for whether wer are in a cloud deployment instead.
// const hasInAppSupportEntitlement = useHasEntitlement("in-app-support");
- const hasInAppSupportEntitlement = !!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ const hasInAppSupportEntitlement = !!isLangfuseCloud;
const plan = usePlan();
const supportType: SupportType = useMemo(() => {
diff --git a/web/src/pages/_app.tsx b/web/src/pages/_app.tsx
index 3e2000471d..ea97a426fd 100644
--- a/web/src/pages/_app.tsx
+++ b/web/src/pages/_app.tsx
@@ -34,6 +34,7 @@ import { env } from "@/src/env.mjs";
import { ThemeProvider } from "@/src/features/theming/ThemeProvider";
import { MarkdownContextProvider } from "@/src/features/theming/useMarkdownContext";
import { SupportDrawerProvider } from "@/src/features/support-chat/SupportDrawerProvider";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
// Check that PostHog is client-side (used to handle Next.js SSR) and that env vars are set
if (
@@ -121,6 +122,7 @@ export default api.withTRPC(MyApp);
function UserTracking() {
const session = useSession();
+ const { region } = useLangfuseCloudRegion();
const sessionUser = session.data?.user;
// Track user identity and properties
@@ -146,7 +148,7 @@ function UserTracking() {
organization: org,
})),
) ?? undefined,
- LANGFUSE_CLOUD_REGION: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
+ LANGFUSE_CLOUD_REGION: region,
});
// Sentry
@@ -163,7 +165,7 @@ function UserTracking() {
// Sentry
setUser(null);
}
- }, [sessionUser, session.status]);
+ }, [sessionUser, session.status, region]);
// add stripe link to chat
// const orgStripeLink = organization?.cloudConfig?.stripe?.customerId
@@ -194,7 +196,8 @@ if (
}
function BetterStackUptimeStatusMessage() {
- if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) return null;
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
+ if (!isLangfuseCloud) return null;
return (
<script
src="https://uptime.betterstack.com/widgets/announcement.js"
diff --git a/web/src/pages/auth/sign-in.tsx b/web/src/pages/auth/sign-in.tsx
index e6f51f1f25..aad94b7f67 100644
--- a/web/src/pages/auth/sign-in.tsx
+++ b/web/src/pages/auth/sign-in.tsx
@@ -41,6 +41,7 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePos
import useLocalStorage from "@/src/components/useLocalStorage";
import { AuthProviderButton } from "@/src/features/auth/components/AuthProviderButton";
import { cn } from "@/src/utils/tailwind";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
const credentialAuthForm = z.object({
email: z.string().email(),
@@ -482,6 +483,7 @@ export default function SignIn({
);
const capture = usePostHogClientCapture();
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
const [turnstileToken, setTurnstileToken] = useState<string>();
// Used to refresh turnstile as the token can only be used once
const [turnstileCData, setTurnstileCData] = useState<string>(
@@ -633,7 +635,7 @@ export default function SignIn({
</h2>
</div>
- {env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined && (
+ {isLangfuseCloud && (
<div className="-mb-4 mt-4 rounded-lg bg-card p-3 text-center text-sm sm:mx-auto sm:w-full sm:max-w-[480px] sm:rounded-lg sm:px-6">
If you are experiencing issues signing in, please force refresh this
page (CMD + SHIFT + R) or clear your browser cache. We are working
@@ -750,7 +752,7 @@ export default function SignIn({
{credentialsFormError}
<br />
Contact support if this error is unexpected.{" "}
- {env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined &&
+ {isLangfuseCloud &&
"Make sure you are using the correct cloud data region."}
</div>
) : null}
diff --git a/web/src/pages/auth/sign-up.tsx b/web/src/pages/auth/sign-up.tsx
index 806af55d57..c88b46f88a 100644
--- a/web/src/pages/auth/sign-up.tsx
+++ b/web/src/pages/auth/sign-up.tsx
@@ -28,6 +28,7 @@ import {
import { PasswordInput } from "@/src/components/ui/password-input";
import { Divider } from "@tremor/react";
import { Turnstile } from "@marsidev/react-turnstile";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
// Use the same getServerSideProps function as src/pages/auth/sign-in.tsx
export { getServerSideProps } from "@/src/pages/auth/sign-in";
@@ -37,6 +38,7 @@ export default function SignIn({
runningOnHuggingFaceSpaces,
}: PageProps) {
useHuggingFaceRedirect(runningOnHuggingFaceSpaces);
+ const { isLangfuseCloud, region } = useLangfuseCloudRegion();
const [turnstileToken, setTurnstileToken] = useState<string>();
// Used to refresh turnstile as the token can only be used once
@@ -76,8 +78,7 @@ export default function SignIn({
email: values.email,
password: values.password,
callbackUrl:
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== "DEV"
+ isLangfuseCloud && region !== "DEV"
? `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding`
: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/`,
turnstileToken,
@@ -110,7 +111,7 @@ export default function SignIn({
Create new account
</h2>
</div>
- {env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined ? (
+ {isLangfuseCloud ? (
<div className="text-center sm:mx-auto sm:w-full sm:max-w-[480px]">
No credit card required.
</div>
diff --git a/web/src/pages/organization/[organizationId]/settings/index.tsx b/web/src/pages/organization/[organizationId]/settings/index.tsx
index 09506710c8..8ebdaed73e 100644
--- a/web/src/pages/organization/[organizationId]/settings/index.tsx
+++ b/web/src/pages/organization/[organizationId]/settings/index.tsx
@@ -15,6 +15,7 @@ import { SSOSettings } from "@/src/ee/features/sso-settings/components/SSOSettin
import { isCloudPlan } from "@langfuse/shared";
import { useQueryProjectOrOrganization } from "@/src/features/projects/hooks";
import { ApiKeyList } from "@/src/features/public-api/components/ApiKeyList";
+import AIFeatureSwitch from "@/src/features/organizations/components/AIFeatureSwitch";
type OrganizationSettingsPage = {
title: string;
@@ -69,6 +70,7 @@ export const getOrganizationSettingsPages = ({
}}
/>
</div>
+ <AIFeatureSwitch />
<SettingsDangerZone
items={[
{
diff --git a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
index d306291c7c..ca0ce3632d 100644
--- a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
+++ b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
@@ -21,7 +21,6 @@ import {
SelectTrigger,
SelectValue,
} from "@/src/components/ui/select";
-import { env } from "@/src/env.mjs";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import {
blobStorageIntegrationFormSchema,
@@ -43,6 +42,7 @@ import {
BlobStorageExportMode,
type BlobStorageIntegration,
} from "@langfuse/shared";
+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
export default function BlobStorageIntegrationSettings() {
const router = useRouter();
@@ -162,11 +162,12 @@ const BlobStorageIntegrationSettingsForm = ({
isLoading: boolean;
}) => {
const capture = usePostHogClientCapture();
+ const { isLangfuseCloud } = useLangfuseCloudRegion();
const [integrationType, setIntegrationType] =
useState<BlobStorageIntegrationType>(BlobStorageIntegrationType.S3);
// Check if this is a self-hosted instance (no cloud region set)
- const isSelfHosted = !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ const isSelfHosted = !isLangfuseCloud;
const blobStorageForm = useForm({
resolver: zodResolver(blobStorageIntegrationFormSchema),
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index e8b5bef558..b806703539 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -44,6 +44,7 @@ import { slackRouter } from "@/src/features/slack/server/router";
import { plainRouter } from "@/src/features/support-chat/trpc/plainRouter";
import { queueAssignmentRouter } from "@/src/features/annotation-queues/server/annotationQueueAssignments";
import { surveysRouter } from "@/src/server/api/routers/surveys";
+import { naturalLanguageFilterRouter } from "@/src/features/natural-language-filters/server/router";
/**
* This is the primary router for your server.
@@ -96,6 +97,7 @@ export const appRouter = createTRPCRouter({
slack: slackRouter,
plainRouter: plainRouter,
surveys: surveysRouter,
+ naturalLanguageFilters: naturalLanguageFilterRouter,
});
// export type definition of API
diff --git a/web/src/server/auth.ts b/web/src/server/auth.ts
index 9ef3a5237a..d290a23063 100644
--- a/web/src/server/auth.ts
+++ b/web/src/server/auth.ts
@@ -609,6 +609,8 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {
string,
unknown
>) ?? {},
+ aiFeaturesEnabled:
+ orgMembership.organization.aiFeaturesEnabled,
cloudConfig: parsedCloudConfig.data,
projects: orgMembership.organization.projects
.map((project) => {
diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.ts
index 212d2afd4d..ea11cae10d 100644
--- a/web/types/next-auth.d.ts
+++ b/web/types/next-auth.d.ts
@@ -42,6 +42,7 @@ declare module "next-auth" {
cloudConfig: CloudConfigSchema | undefined;
plan: Plan;
metadata: Record<string, unknown>;
+ aiFeaturesEnabled: boolean;
projects: {
id: PrismaProject["id"];
name: PrismaProject["name"];
diff --git a/worker/src/features/utils/utilities.ts b/worker/src/features/utils/utilities.ts
index 012e8856d9..7b5651009b 100644
--- a/worker/src/features/utils/utilities.ts
+++ b/worker/src/features/utils/utilities.ts
@@ -10,7 +10,6 @@ import { z } from "zod/v4";
import { z as zodV3 } from "zod/v3";
import { ZodSchema as ZodV3Schema } from "zod/v3";
import { decrypt } from "@langfuse/shared/encryption";
-import { tokenCount } from "../tokenisation/usage";
import Handlebars from "handlebars";
/**
@@ -81,7 +80,7 @@ export async function callLLM(
modelParams: z.infer<typeof ZodModelConfig>,
provider: string,
model: string,
- traceParams?: Omit<TraceParams, "tokenCountDelegate">,
+ traceParams?: TraceParams,
): Promise<string> {
return withLLMErrorHandling(async () => {
const { completion, processTracedEvents } = await fetchLLMCompletion({
@@ -97,9 +96,7 @@ export async function callLLM(
...modelParams,
},
config: llmApiKey.config,
- traceParams: traceParams
- ? { ...traceParams, tokenCountDelegate: tokenCount }
- : undefined,
+ traceParams,
maxRetries: 1,
throwOnError: false,
});