Core functions and utilities for Langfuse packages including API client, logging, media handling, and OpenTelemetry tracing attributes
npx @tessl/cli install tessl/npm-langfuse--core@4.2.0The @langfuse/core package is the foundation of the Langfuse JavaScript SDK, providing the core API client for interacting with the Langfuse observability platform. It includes essential utilities for logging, media handling, OpenTelemetry integration, and type-safe access to 23 API resources for managing traces, observations, prompts, datasets, and more.
npm install @langfuse/coreimport { LangfuseAPIClient } from '@langfuse/core';For logger utilities:
import { Logger, LogLevel, configureGlobalLogger } from '@langfuse/core';For media handling:
import { LangfuseMedia } from '@langfuse/core';For constants and utilities:
import {
LANGFUSE_SDK_VERSION,
LangfuseOtelSpanAttributes,
generateUUID,
getEnv
} from '@langfuse/core';CommonJS:
const { LangfuseAPIClient, Logger, LangfuseMedia } = require('@langfuse/core');import { LangfuseAPIClient } from '@langfuse/core';
// Initialize the API client
const client = new LangfuseAPIClient({
environment: 'https://cloud.langfuse.com',
username: 'your-public-key',
password: 'your-secret-key',
xLangfuseSdkName: 'javascript',
xLangfuseSdkVersion: '4.2.0'
});
// Fetch a trace
const trace = await client.trace.get('trace-id');
// List traces with filters
const traces = await client.trace.list({
page: 1,
limit: 50,
userId: 'user-123',
fromTimestamp: '2024-01-01T00:00:00Z'
});
// Get a prompt
const prompt = await client.prompts.get('my-prompt', {
version: 1,
label: 'production'
});
// Create media content
import { LangfuseMedia } from '@langfuse/core';
const media = new LangfuseMedia({
source: 'base64_data_uri',
base64DataUri: 'data:image/png;base64,iVBORw0KGgoAAAA...'
});
const mediaTag = await media.getTag();
// Use mediaTag in trace input/outputThe @langfuse/core package is organized around these key components:
Configurable logging infrastructure with multiple severity levels, timestamps, and global configuration.
enum LogLevel {
DEBUG = 0,
INFO = 1,
WARN = 2,
ERROR = 3
}
class Logger {
constructor(config?: LoggerConfig);
error(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
info(message: string, ...args: unknown[]): void;
debug(message: string, ...args: unknown[]): void;
setLevel(level: LogLevel): void;
getLevel(): LogLevel;
}
interface LoggerConfig {
level: LogLevel;
prefix?: string;
enableTimestamp?: boolean;
}
function configureGlobalLogger(config: LoggerConfig): void;
function getGlobalLogger(): Logger;Type-safe API client for all Langfuse platform resources with built-in authentication, retry logic, and comprehensive error handling.
class LangfuseAPIClient {
constructor(options: LangfuseAPIClient.Options);
// Resource accessors (23 total)
readonly trace: Trace;
readonly prompts: Prompts;
readonly datasets: Datasets;
readonly observations: Observations;
readonly score: Score;
readonly sessions: Sessions;
readonly media: Media;
// ... and 16 more resources
}
interface Options {
environment: core.Supplier<string>;
baseUrl?: core.Supplier<string>;
username?: core.Supplier<string | undefined>;
password?: core.Supplier<string | undefined>;
xLangfuseSdkName?: core.Supplier<string | undefined>;
xLangfuseSdkVersion?: core.Supplier<string | undefined>;
xLangfusePublicKey?: core.Supplier<string | undefined>;
headers?: Record<string, string | core.Supplier<string | null | undefined> | null | undefined>;
}Comprehensive access to Langfuse platform features through 19+ specialized resource clients.
Core Observability:
Prompt Management:
Evaluation & Scoring:
Platform Management:
SDK identifiers and standardized OpenTelemetry span attribute keys for tracing integration.
const LANGFUSE_TRACER_NAME: string;
const LANGFUSE_SDK_VERSION: string;
const LANGFUSE_SDK_NAME: string;
enum LangfuseOtelSpanAttributes {
TRACE_NAME = "langfuse.trace.name",
TRACE_USER_ID = "user.id",
OBSERVATION_TYPE = "langfuse.observation.type",
OBSERVATION_MODEL = "langfuse.observation.model.name",
// ... 20+ more attributes
}Constants and OpenTelemetry Attributes
Rich media support with content-addressable storage, SHA-256 hashing, and media reference tags for embedding in traces.
class LangfuseMedia {
constructor(params: LangfuseMediaParams);
async getId(): Promise<string | null>;
async getSha256Hash(): Promise<string | undefined>;
async getTag(): Promise<string | null>;
get contentLength(): number | undefined;
get base64DataUri(): string | null;
toJSON(): string | null;
}
type LangfuseMediaParams =
| {
source: "base64_data_uri";
base64DataUri: string;
}
| {
source: "bytes";
contentBytes: Uint8Array;
contentType: MediaContentType;
};Cross-platform utility functions for UUID generation, base64 encoding, environment variables, and safe timeouts.
function generateUUID(globalThis?: any): string;
function getEnv(key: LangfuseEnvVar): string | undefined;
function base64Encode(input: string): string;
function base64Decode(input: string): string;
function safeSetTimeout(fn: () => void, timeout: number): any;Structured error classes for API interactions with status codes, response bodies, and timeout handling.
class LangfuseAPIError extends Error {
readonly statusCode?: number;
readonly body?: unknown;
readonly rawResponse?: RawResponse;
constructor(params: {
message?: string;
statusCode?: number;
body?: unknown;
rawResponse?: RawResponse;
});
}
class LangfuseAPITimeoutError extends Error {
constructor(message: string);
}The @langfuse/core package provides complete TypeScript type definitions for all APIs, with over 200 exported types including:
Trace, Observation, Session, Score, Prompt, Dataset, ModelAll types are auto-generated from Fern API specifications ensuring consistency with the Langfuse platform.
The SDK reads configuration from these environment variables:
LANGFUSE_PUBLIC_KEY - Public API key for authenticationLANGFUSE_SECRET_KEY - Secret API key for authenticationLANGFUSE_BASE_URL - Base API URL (default: https://cloud.langfuse.com)LANGFUSE_LOG_LEVEL - Logging level (DEBUG, INFO, WARN, ERROR)LANGFUSE_TIMEOUT - Request timeout in millisecondsLANGFUSE_FLUSH_AT - Batch size for flushing operationsLANGFUSE_FLUSH_INTERVAL - Flush interval in millisecondsLANGFUSE_RELEASE - Release identifier for tracesLANGFUSE_TRACING_ENVIRONMENT - Environment identifier for tracesUnauthorizedError, NotFoundError) for better UXfields parameter on trace queries to reduce payload sizeusageDetails and costDetails over deprecated usage fieldThe @langfuse/core package is designed for universal JavaScript compatibility: