Observability and analytics platform for LLM applications with hierarchical tracing, prompt management, dataset operations, and OpenAI integration
Comprehensive configuration options for customizing Langfuse client behavior including authentication, networking, persistence, sampling, and performance tuning.
Initialize the Langfuse client with configuration options.
class Langfuse {
/**
* Creates a Langfuse client instance
* @param params - Configuration including authentication and options
*/
constructor(params?: {
publicKey?: string;
secretKey?: string;
} & LangfuseOptions);
}
class LangfuseWeb {
/**
* Creates a web-only Langfuse client (no secret key required)
* @param params - Configuration without secretKey
*/
constructor(params?: Omit<LangfuseOptions, "secretKey">);
}Usage Example:
import { Langfuse, LangfuseWeb } from 'langfuse';
// Full client with all options
const langfuse = new Langfuse({
publicKey: 'pk-lf-...',
secretKey: 'sk-lf-...',
baseUrl: 'https://cloud.langfuse.com',
flushAt: 10,
flushInterval: 5000,
requestTimeout: 10000,
enabled: true
});
// Web client (browser-only, no secret key)
const langfuseWeb = new LangfuseWeb({
publicKey: 'pk-lf-...',
persistence: 'localStorage',
enabled: true
});Complete configuration interface for the Langfuse client.
interface LangfuseOptions {
/** Persistence strategy (browser/web environments) */
persistence?: "localStorage" | "sessionStorage" | "cookie" | "memory";
/** Custom name for persistence storage key */
persistence_name?: string;
/** Enable/disable tracing globally (default: true) */
enabled?: boolean;
/** Base URL for Langfuse API (default: https://cloud.langfuse.com) */
baseUrl?: string;
/** Number of events before auto-flush (default: 15) */
flushAt?: number;
/** Flush interval in milliseconds (default: 10000) */
flushInterval?: number;
/** Request timeout in milliseconds (default: 5000) */
requestTimeout?: number;
/** Release version identifier */
release?: string;
/** Environment name (e.g., production, staging) */
environment?: string;
/** Function to mask sensitive data in events */
mask?: MaskFunction;
/** Sampling rate 0-1 (1 = 100%, 0.1 = 10%) */
sampleRate?: number;
/** Number of retries for failed requests (default: 3) */
fetchRetryCount?: number;
/** Retry delay in milliseconds (default: 3000) */
fetchRetryDelay?: number;
/** SDK integration identifier */
sdkIntegration?: string;
/** Additional HTTP headers for API requests */
additionalHeaders?: Record<string, string>;
}
type MaskFunction = (params: { data: any }) => any;Configure authentication keys for Langfuse API access.
interface AuthenticationConfig {
/** Public key for authentication (required) */
publicKey?: string;
/** Secret key for authentication (required for server-side) */
secretKey?: string;
}Usage Example:
// From constructor
const langfuse = new Langfuse({
publicKey: 'pk-lf-1234567890abcdef',
secretKey: 'sk-lf-1234567890abcdef'
});
// From environment variables
// LANGFUSE_PUBLIC_KEY=pk-lf-...
// LANGFUSE_SECRET_KEY=sk-lf-...
const langfuse2 = new Langfuse();Environment Variables:
LANGFUSE_PUBLIC_KEY: Public API keyLANGFUSE_SECRET_KEY: Secret API keyLANGFUSE_BASEURL: Custom base URLLANGFUSE_SAMPLE_RATE: Default sampling rateLANGFUSE_TRACING_ENVIRONMENT: Default environment nameConfigure API endpoints and network behavior.
interface NetworkConfig {
/** Base URL for Langfuse API (default: https://cloud.langfuse.com) */
baseUrl?: string;
/** Request timeout in milliseconds (default: 5000) */
requestTimeout?: number;
/** Number of retries for failed requests (default: 3) */
fetchRetryCount?: number;
/** Retry delay in milliseconds (default: 3000) */
fetchRetryDelay?: number;
/** Additional HTTP headers for API requests */
additionalHeaders?: Record<string, string>;
}Usage Example:
const langfuse = new Langfuse({
publicKey: 'pk-lf-...',
secretKey: 'sk-lf-...',
// Self-hosted instance
baseUrl: 'https://langfuse.company.com',
// Longer timeout for slow networks
requestTimeout: 15000,
// More aggressive retries
fetchRetryCount: 5,
fetchRetryDelay: 5000,
// Custom headers
additionalHeaders: {
'X-Custom-Header': 'value',
'X-Environment': 'production'
}
});Configure event batching and automatic flushing behavior.
interface BatchingConfig {
/** Number of events before auto-flush (default: 15) */
flushAt?: number;
/** Flush interval in milliseconds (default: 10000) */
flushInterval?: number;
}Usage Example:
// Aggressive flushing (low latency, more network calls)
const lowLatency = new Langfuse({
publicKey: 'pk-lf-...',
secretKey: 'sk-lf-...',
flushAt: 1, // Flush after every event
flushInterval: 1000 // Flush every second
});
// Conservative batching (high throughput, fewer network calls)
const highThroughput = new Langfuse({
publicKey: 'pk-lf-...',
secretKey: 'sk-lf-...',
flushAt: 100, // Batch up to 100 events
flushInterval: 30000 // Flush every 30 seconds
});
// Balanced (default)
const balanced = new Langfuse({
publicKey: 'pk-lf-...',
secretKey: 'sk-lf-...',
flushAt: 15,
flushInterval: 10000
});Configure data persistence for browser environments.
interface PersistenceConfig {
/** Persistence strategy */
persistence?: "localStorage" | "sessionStorage" | "cookie" | "memory";
/** Custom name for persistence storage key */
persistence_name?: string;
}Usage Example:
// Use localStorage (survives page refresh)
const persistent = new LangfuseWeb({
publicKey: 'pk-lf-...',
persistence: 'localStorage',
persistence_name: 'my-app' // Key: lf_my-app_langfuse
});
// Use sessionStorage (cleared on tab close)
const session = new LangfuseWeb({
publicKey: 'pk-lf-...',
persistence: 'sessionStorage'
});
// Use memory only (cleared on page refresh)
const memory = new LangfuseWeb({
publicKey: 'pk-lf-...',
persistence: 'memory'
});
// Use cookies
const cookie = new LangfuseWeb({
publicKey: 'pk-lf-...',
persistence: 'cookie'
});Configure trace sampling to reduce data volume.
interface SamplingConfig {
/** Sampling rate 0-1 (1 = 100%, 0.1 = 10%, 0 = disabled) */
sampleRate?: number;
}Usage Example:
// Sample 10% of traces
const sampled = new Langfuse({
publicKey: 'pk-lf-...',
secretKey: 'sk-lf-...',
sampleRate: 0.1
});
// Sample 50% of traces
const halfSampled = new Langfuse({
publicKey: 'pk-lf-...',
secretKey: 'sk-lf-...',
sampleRate: 0.5
});
// No sampling (100% of traces)
const fullTracing = new Langfuse({
publicKey: 'pk-lf-...',
secretKey: 'sk-lf-...',
sampleRate: 1.0
});Configure sensitive data masking for privacy compliance.
type MaskFunction = (params: { data: any }) => any;
interface MaskingConfig {
/** Function to mask sensitive data in events */
mask?: MaskFunction;
}Usage Example:
// Mask email addresses and API keys
const langfuse = new Langfuse({
publicKey: 'pk-lf-...',
secretKey: 'sk-lf-...',
mask: ({ data }) => {
// Deep clone to avoid modifying original
const masked = JSON.parse(JSON.stringify(data));
// Mask function to recursively process object
const maskSensitiveData = (obj: any): any => {
if (typeof obj === 'string') {
// Mask email addresses
obj = obj.replace(/[\w.-]+@[\w.-]+\.\w+/g, '[EMAIL]');
// Mask API keys
obj = obj.replace(/sk-[a-zA-Z0-9]{32,}/g, '[API_KEY]');
// Mask credit card numbers
obj = obj.replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g, '[CARD]');
return obj;
}
if (Array.isArray(obj)) {
return obj.map(maskSensitiveData);
}
if (obj && typeof obj === 'object') {
const result: any = {};
for (const key in obj) {
// Mask specific fields
if (['password', 'apiKey', 'secretKey', 'token'].includes(key)) {
result[key] = '[REDACTED]';
} else {
result[key] = maskSensitiveData(obj[key]);
}
}
return result;
}
return obj;
};
return maskSensitiveData(masked);
}
});
// Usage
const trace = langfuse.trace({
name: 'user-action',
input: {
email: 'user@example.com',
apiKey: 'sk-1234567890abcdef',
message: 'Contact me at john.doe@company.com'
}
});
// Stored as: { email: '[EMAIL]', apiKey: '[API_KEY]', message: 'Contact me at [EMAIL]' }Tag traces with environment and release information.
interface EnvironmentConfig {
/** Environment name (e.g., production, staging, development) */
environment?: string;
/** Release version identifier */
release?: string;
}Usage Example:
// Tag all traces with environment
const langfuse = new Langfuse({
publicKey: 'pk-lf-...',
secretKey: 'sk-lf-...',
environment: 'production',
release: 'v1.2.3'
});
// Traces automatically include environment/release
const trace = langfuse.trace({
name: 'user-action'
// environment: 'production' and release: 'v1.2.3' are auto-added
});
// Override per trace
const devTrace = langfuse.trace({
name: 'test-action',
environment: 'development' // Overrides config
});Enable or disable tracing globally.
interface FeatureConfig {
/** Enable/disable tracing globally (default: true) */
enabled?: boolean;
}Usage Example:
// Disable tracing in development
const langfuse = new Langfuse({
publicKey: 'pk-lf-...',
secretKey: 'sk-lf-...',
enabled: process.env.NODE_ENV === 'production'
});
// No events are sent when enabled=false
const trace = langfuse.trace({ name: 'test' }); // No-op
await langfuse.flushAsync(); // No-op
// Toggle at runtime
langfuse.debug(false); // Disable
langfuse.debug(true); // EnableIdentify SDK integrations for analytics.
interface IntegrationConfig {
/** SDK integration identifier */
sdkIntegration?: string;
}Usage Example:
const langfuse = new Langfuse({
publicKey: 'pk-lf-...',
secretKey: 'sk-lf-...',
sdkIntegration: 'langchain' // Identifies usage from Langchain
});Langfuse automatically reads configuration from environment variables if not provided in the constructor.
/**
* Configures Langfuse SDK with environment variables
* @param params - Optional override parameters
* @param secretRequired - Whether secret key is required (default: true)
* @returns Merged configuration
*/
function configLangfuseSDK(
params?: LangfuseCoreOptions,
secretRequired?: boolean
): LangfuseCoreOptions;Supported Environment Variables:
LANGFUSE_PUBLIC_KEY: Public API keyLANGFUSE_SECRET_KEY: Secret API keyLANGFUSE_BASEURL: Custom base URLLANGFUSE_SAMPLE_RATE: Sampling rate (0-1)LANGFUSE_TRACING_ENVIRONMENT: Environment nameLANGFUSE_RELEASE: Release versionLANGFUSE_ENABLED: Enable/disable tracing (true/false)Usage Example:
# .env file
LANGFUSE_PUBLIC_KEY=pk-lf-1234567890
LANGFUSE_SECRET_KEY=sk-lf-1234567890
LANGFUSE_BASEURL=https://cloud.langfuse.com
LANGFUSE_SAMPLE_RATE=0.1
LANGFUSE_TRACING_ENVIRONMENT=production
LANGFUSE_RELEASE=v1.2.3
LANGFUSE_ENABLED=trueimport { Langfuse } from 'langfuse';
// Reads all config from environment
const langfuse = new Langfuse();
// Override specific values
const override = new Langfuse({
flushAt: 5, // Override batching
// Other values from environment
});import { Langfuse } from 'langfuse';
const langfuse = new Langfuse({
publicKey: process.env.LANGFUSE_PUBLIC_KEY,
secretKey: process.env.LANGFUSE_SECRET_KEY,
baseUrl: 'https://cloud.langfuse.com',
// Environment
environment: 'production',
release: process.env.APP_VERSION,
// Batching (balanced)
flushAt: 20,
flushInterval: 10000,
// Network (reliable)
requestTimeout: 10000,
fetchRetryCount: 5,
fetchRetryDelay: 3000,
// Sampling (10%)
sampleRate: 0.1,
// Masking
mask: ({ data }) => {
const masked = JSON.parse(JSON.stringify(data));
// Mask PII
const maskPII = (obj: any): any => {
if (typeof obj === 'string') {
return obj
.replace(/[\w.-]+@[\w.-]+\.\w+/g, '[EMAIL]')
.replace(/\b\d{3}-\d{2}-\d{4}\b/g, '[SSN]');
}
if (Array.isArray(obj)) return obj.map(maskPII);
if (obj && typeof obj === 'object') {
const result: any = {};
for (const key in obj) {
if (['password', 'ssn', 'creditCard'].includes(key)) {
result[key] = '[REDACTED]';
} else {
result[key] = maskPII(obj[key]);
}
}
return result;
}
return obj;
};
return maskPII(masked);
},
// Headers
additionalHeaders: {
'X-App-Name': 'my-app',
'X-Environment': 'production'
}
});import { Langfuse } from 'langfuse';
const langfuse = new Langfuse({
publicKey: 'pk-lf-dev-key',
secretKey: 'sk-lf-dev-key',
baseUrl: 'http://localhost:3000', // Local Langfuse instance
// Environment
environment: 'development',
release: 'dev',
// Aggressive flushing for testing
flushAt: 1,
flushInterval: 1000,
// Network (fast fail)
requestTimeout: 2000,
fetchRetryCount: 1,
fetchRetryDelay: 500,
// Full sampling
sampleRate: 1.0,
// No masking in development
mask: undefined
});
// Enable debug logging
langfuse.debug(true);import { Langfuse } from 'langfuse';
const langfuse = new Langfuse({
publicKey: process.env.LANGFUSE_PUBLIC_KEY,
secretKey: process.env.LANGFUSE_SECRET_KEY,
// Large batches
flushAt: 100,
flushInterval: 30000,
// Aggressive timeouts
requestTimeout: 15000,
fetchRetryCount: 3,
fetchRetryDelay: 5000,
// Low sampling for high volume
sampleRate: 0.01, // 1% sampling
// Environment
environment: 'production',
release: process.env.APP_VERSION
});import { LangfuseWeb } from 'langfuse';
const langfuse = new LangfuseWeb({
publicKey: 'pk-lf-browser-key',
// Persistence
persistence: 'localStorage',
persistence_name: 'my-app-analytics',
// Batching (browser-friendly)
flushAt: 5,
flushInterval: 5000,
// Network
requestTimeout: 5000,
fetchRetryCount: 2,
fetchRetryDelay: 2000,
// Sampling
sampleRate: 0.2, // 20% of users
// Environment
environment: 'production'
});Enable or disable debug logging at runtime.
/**
* Enables or disables debug mode
* @param enabled - Debug mode state (default: true)
*/
debug(enabled?: boolean): void;Usage Example:
const langfuse = new Langfuse();
// Enable debug logging
langfuse.debug(true);
// Disable debug logging
langfuse.debug(false);
// Toggle based on environment
langfuse.debug(process.env.DEBUG === 'true');Register event listeners for lifecycle events.
/**
* Registers an event listener
* @param event - Event name
* @param cb - Callback function
* @returns Unsubscribe function
*/
on(event: string, cb: (...args: any[]) => void): () => void;Usage Example:
const langfuse = new Langfuse();
// Listen for flush events
const unsubscribe = langfuse.on('flush', (data) => {
console.log('Events flushed:', data);
});
// Listen for errors
langfuse.on('error', (error) => {
console.error('Langfuse error:', error);
});
// Unsubscribe
unsubscribe();Install with Tessl CLI
npx tessl i tessl/npm-langfuse