or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

api-client.mdapi-resources.mdconstants.mderrors.mdindex.mdlogger.mdmedia.mdutils.md
tile.json

tessl/npm-langfuse--core

Core functions and utilities for Langfuse packages including API client, logging, media handling, and OpenTelemetry tracing attributes

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@langfuse/core@4.2.x

To install, run

npx @tessl/cli install tessl/npm-langfuse--core@4.2.0

index.mddocs/

Langfuse Core

The @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.

Package Information

  • Package Name: @langfuse/core
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @langfuse/core
  • Version: 4.2.0
  • License: MIT

Core Imports

import { 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');

Basic Usage

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/output

Architecture

The @langfuse/core package is organized around these key components:

API Client Architecture

  • LangfuseAPIClient: Main client class providing lazy-loaded access to 23 resource clients
  • Resource Clients: Specialized clients for different API domains (traces, prompts, datasets, etc.)
  • Auto-Generated Types: Complete TypeScript type definitions generated from Fern API specifications
  • Authentication: Basic Auth with public key (username) and secret key (password)
  • Error Handling: Structured error types for HTTP status codes (400, 401, 403, 404, 405)
  • Retry Logic: Built-in retry mechanism (default: 2 retries) with configurable timeouts

Core Utilities

  • Logger System: Configurable logging with levels (DEBUG, INFO, WARN, ERROR) and global singleton
  • Media Handler: SHA-256 hashing, content-addressable storage, and media reference tags
  • UUID Generation: Cross-platform UUID v4 generation for Node.js and browser environments
  • Base64 Utilities: Encoding/decoding for both environments with UTF-8 support
  • Environment Variables: Helper for reading Langfuse configuration from environment

OpenTelemetry Integration

  • Span Attributes: Standardized attribute keys for trace and observation metadata
  • SDK Identifiers: Constants for tracer name, SDK version, and platform identification
  • Compatibility: Support for both current and legacy attribute naming conventions

Capabilities

Logger System

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;

Logger System

API Client

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>;
}

API Client and Core Concepts

API Resources

Comprehensive access to Langfuse platform features through 19+ specialized resource clients.

Core Observability:

  • Traces: Trace lifecycle management and querying
  • Observations: Detailed observation queries (spans, generations, events)
  • Sessions: Session grouping and analytics

Prompt Management:

  • Prompts: Version-controlled prompt templates
  • Prompt Versions: Specific version operations

Evaluation & Scoring:

  • Datasets: Test dataset management
  • Dataset Items: Individual dataset entries
  • Dataset Runs: Evaluation run tracking
  • Score: Score creation
  • Score Configs: Score configuration management

Platform Management:

  • Projects: Project administration
  • Organizations: Multi-tenant organization management
  • Models: Model configuration and pricing
  • Media: Media upload and retrieval

API Resources

Constants and OpenTelemetry

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

Media Handling

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;
    };

Media Handling

Utilities

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;

Utilities

Error Handling

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);
}

Error Handling

Type Safety

The @langfuse/core package provides complete TypeScript type definitions for all APIs, with over 200 exported types including:

  • Core Entities: Trace, Observation, Session, Score, Prompt, Dataset, Model
  • Request Types: Query parameters, creation requests, update requests for all operations
  • Response Types: Paginated lists, single entities, deletion confirmations
  • Enums: Status codes, observation types, model usage units, data types
  • Utility Types: Usage metrics, metadata structures, pagination metadata

All types are auto-generated from Fern API specifications ensuring consistency with the Langfuse platform.

Environment Variables

The SDK reads configuration from these environment variables:

  • LANGFUSE_PUBLIC_KEY - Public API key for authentication
  • LANGFUSE_SECRET_KEY - Secret API key for authentication
  • LANGFUSE_BASE_URL - Base API URL (default: https://cloud.langfuse.com)
  • LANGFUSE_LOG_LEVEL - Logging level (DEBUG, INFO, WARN, ERROR)
  • LANGFUSE_TIMEOUT - Request timeout in milliseconds
  • LANGFUSE_FLUSH_AT - Batch size for flushing operations
  • LANGFUSE_FLUSH_INTERVAL - Flush interval in milliseconds
  • LANGFUSE_RELEASE - Release identifier for traces
  • LANGFUSE_TRACING_ENVIRONMENT - Environment identifier for traces

Best Practices

  1. Authentication: Store API keys securely using environment variables, never hardcode them
  2. Error Handling: Catch specific error types (UnauthorizedError, NotFoundError) for better UX
  3. Pagination: Always implement pagination for list operations to handle large datasets
  4. Field Selection: Use the fields parameter on trace queries to reduce payload size
  5. Media Optimization: Use media references rather than embedding large content directly in traces
  6. Environment Naming: Use lowercase alphanumeric with hyphens/underscores, avoid 'langfuse' prefix
  7. Cost Tracking: Prefer usageDetails and costDetails over deprecated usage field
  8. OpenTelemetry: Prefer OpenTelemetry endpoint over legacy batch ingestion for new integrations
  9. Logger Configuration: Configure global logger early in application initialization
  10. Type Safety: Leverage TypeScript types for compile-time validation and IDE autocompletion

Platform Compatibility

The @langfuse/core package is designed for universal JavaScript compatibility:

  • Node.js: Full support for Node.js environments (v20+)
  • Browser: Compatible with modern browsers via bundlers (webpack, vite, etc.)
  • Edge Runtime: Compatible with edge computing platforms (Cloudflare Workers, Vercel Edge)
  • Build System: Available as ESM (.mjs) and CommonJS (.cjs) with TypeScript definitions

Related Documentation