or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# Langfuse Core

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: @langfuse/core

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @langfuse/core`

10

- **Version**: 4.2.0

11

- **License**: MIT

12

13

## Core Imports

14

15

```typescript

16

import { LangfuseAPIClient } from '@langfuse/core';

17

```

18

19

For logger utilities:

20

21

```typescript

22

import { Logger, LogLevel, configureGlobalLogger } from '@langfuse/core';

23

```

24

25

For media handling:

26

27

```typescript

28

import { LangfuseMedia } from '@langfuse/core';

29

```

30

31

For constants and utilities:

32

33

```typescript

34

import {

35

LANGFUSE_SDK_VERSION,

36

LangfuseOtelSpanAttributes,

37

generateUUID,

38

getEnv

39

} from '@langfuse/core';

40

```

41

42

CommonJS:

43

44

```javascript

45

const { LangfuseAPIClient, Logger, LangfuseMedia } = require('@langfuse/core');

46

```

47

48

## Basic Usage

49

50

```typescript

51

import { LangfuseAPIClient } from '@langfuse/core';

52

53

// Initialize the API client

54

const client = new LangfuseAPIClient({

55

environment: 'https://cloud.langfuse.com',

56

username: 'your-public-key',

57

password: 'your-secret-key',

58

xLangfuseSdkName: 'javascript',

59

xLangfuseSdkVersion: '4.2.0'

60

});

61

62

// Fetch a trace

63

const trace = await client.trace.get('trace-id');

64

65

// List traces with filters

66

const traces = await client.trace.list({

67

page: 1,

68

limit: 50,

69

userId: 'user-123',

70

fromTimestamp: '2024-01-01T00:00:00Z'

71

});

72

73

// Get a prompt

74

const prompt = await client.prompts.get('my-prompt', {

75

version: 1,

76

label: 'production'

77

});

78

79

// Create media content

80

import { LangfuseMedia } from '@langfuse/core';

81

82

const media = new LangfuseMedia({

83

source: 'base64_data_uri',

84

base64DataUri: 'data:image/png;base64,iVBORw0KGgoAAAA...'

85

});

86

87

const mediaTag = await media.getTag();

88

// Use mediaTag in trace input/output

89

```

90

91

## Architecture

92

93

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

94

95

### API Client Architecture

96

97

- **LangfuseAPIClient**: Main client class providing lazy-loaded access to 23 resource clients

98

- **Resource Clients**: Specialized clients for different API domains (traces, prompts, datasets, etc.)

99

- **Auto-Generated Types**: Complete TypeScript type definitions generated from Fern API specifications

100

- **Authentication**: Basic Auth with public key (username) and secret key (password)

101

- **Error Handling**: Structured error types for HTTP status codes (400, 401, 403, 404, 405)

102

- **Retry Logic**: Built-in retry mechanism (default: 2 retries) with configurable timeouts

103

104

### Core Utilities

105

106

- **Logger System**: Configurable logging with levels (DEBUG, INFO, WARN, ERROR) and global singleton

107

- **Media Handler**: SHA-256 hashing, content-addressable storage, and media reference tags

108

- **UUID Generation**: Cross-platform UUID v4 generation for Node.js and browser environments

109

- **Base64 Utilities**: Encoding/decoding for both environments with UTF-8 support

110

- **Environment Variables**: Helper for reading Langfuse configuration from environment

111

112

### OpenTelemetry Integration

113

114

- **Span Attributes**: Standardized attribute keys for trace and observation metadata

115

- **SDK Identifiers**: Constants for tracer name, SDK version, and platform identification

116

- **Compatibility**: Support for both current and legacy attribute naming conventions

117

118

## Capabilities

119

120

### Logger System

121

122

Configurable logging infrastructure with multiple severity levels, timestamps, and global configuration.

123

124

```typescript { .api }

125

enum LogLevel {

126

DEBUG = 0,

127

INFO = 1,

128

WARN = 2,

129

ERROR = 3

130

}

131

132

class Logger {

133

constructor(config?: LoggerConfig);

134

error(message: string, ...args: unknown[]): void;

135

warn(message: string, ...args: unknown[]): void;

136

info(message: string, ...args: unknown[]): void;

137

debug(message: string, ...args: unknown[]): void;

138

setLevel(level: LogLevel): void;

139

getLevel(): LogLevel;

140

}

141

142

interface LoggerConfig {

143

level: LogLevel;

144

prefix?: string;

145

enableTimestamp?: boolean;

146

}

147

148

function configureGlobalLogger(config: LoggerConfig): void;

149

function getGlobalLogger(): Logger;

150

```

151

152

[Logger System](./logger.md)

153

154

### API Client

155

156

Type-safe API client for all Langfuse platform resources with built-in authentication, retry logic, and comprehensive error handling.

157

158

```typescript { .api }

159

class LangfuseAPIClient {

160

constructor(options: LangfuseAPIClient.Options);

161

162

// Resource accessors (23 total)

163

readonly trace: Trace;

164

readonly prompts: Prompts;

165

readonly datasets: Datasets;

166

readonly observations: Observations;

167

readonly score: Score;

168

readonly sessions: Sessions;

169

readonly media: Media;

170

// ... and 16 more resources

171

}

172

173

interface Options {

174

environment: core.Supplier<string>;

175

baseUrl?: core.Supplier<string>;

176

username?: core.Supplier<string | undefined>;

177

password?: core.Supplier<string | undefined>;

178

xLangfuseSdkName?: core.Supplier<string | undefined>;

179

xLangfuseSdkVersion?: core.Supplier<string | undefined>;

180

xLangfusePublicKey?: core.Supplier<string | undefined>;

181

headers?: Record<string, string | core.Supplier<string | null | undefined> | null | undefined>;

182

}

183

```

184

185

[API Client and Core Concepts](./api-client.md)

186

187

### API Resources

188

189

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

190

191

**Core Observability:**

192

- Traces: Trace lifecycle management and querying

193

- Observations: Detailed observation queries (spans, generations, events)

194

- Sessions: Session grouping and analytics

195

196

**Prompt Management:**

197

- Prompts: Version-controlled prompt templates

198

- Prompt Versions: Specific version operations

199

200

**Evaluation & Scoring:**

201

- Datasets: Test dataset management

202

- Dataset Items: Individual dataset entries

203

- Dataset Runs: Evaluation run tracking

204

- Score: Score creation

205

- Score Configs: Score configuration management

206

207

**Platform Management:**

208

- Projects: Project administration

209

- Organizations: Multi-tenant organization management

210

- Models: Model configuration and pricing

211

- Media: Media upload and retrieval

212

213

[API Resources](./api-resources.md)

214

215

### Constants and OpenTelemetry

216

217

SDK identifiers and standardized OpenTelemetry span attribute keys for tracing integration.

218

219

```typescript { .api }

220

const LANGFUSE_TRACER_NAME: string;

221

const LANGFUSE_SDK_VERSION: string;

222

const LANGFUSE_SDK_NAME: string;

223

224

enum LangfuseOtelSpanAttributes {

225

TRACE_NAME = "langfuse.trace.name",

226

TRACE_USER_ID = "user.id",

227

OBSERVATION_TYPE = "langfuse.observation.type",

228

OBSERVATION_MODEL = "langfuse.observation.model.name",

229

// ... 20+ more attributes

230

}

231

```

232

233

[Constants and OpenTelemetry Attributes](./constants.md)

234

235

### Media Handling

236

237

Rich media support with content-addressable storage, SHA-256 hashing, and media reference tags for embedding in traces.

238

239

```typescript { .api }

240

class LangfuseMedia {

241

constructor(params: LangfuseMediaParams);

242

async getId(): Promise<string | null>;

243

async getSha256Hash(): Promise<string | undefined>;

244

async getTag(): Promise<string | null>;

245

get contentLength(): number | undefined;

246

get base64DataUri(): string | null;

247

toJSON(): string | null;

248

}

249

250

type LangfuseMediaParams =

251

| {

252

source: "base64_data_uri";

253

base64DataUri: string;

254

}

255

| {

256

source: "bytes";

257

contentBytes: Uint8Array;

258

contentType: MediaContentType;

259

};

260

```

261

262

[Media Handling](./media.md)

263

264

### Utilities

265

266

Cross-platform utility functions for UUID generation, base64 encoding, environment variables, and safe timeouts.

267

268

```typescript { .api }

269

function generateUUID(globalThis?: any): string;

270

function getEnv(key: LangfuseEnvVar): string | undefined;

271

function base64Encode(input: string): string;

272

function base64Decode(input: string): string;

273

function safeSetTimeout(fn: () => void, timeout: number): any;

274

```

275

276

[Utilities](./utils.md)

277

278

### Error Handling

279

280

Structured error classes for API interactions with status codes, response bodies, and timeout handling.

281

282

```typescript { .api }

283

class LangfuseAPIError extends Error {

284

readonly statusCode?: number;

285

readonly body?: unknown;

286

readonly rawResponse?: RawResponse;

287

288

constructor(params: {

289

message?: string;

290

statusCode?: number;

291

body?: unknown;

292

rawResponse?: RawResponse;

293

});

294

}

295

296

class LangfuseAPITimeoutError extends Error {

297

constructor(message: string);

298

}

299

```

300

301

[Error Handling](./errors.md)

302

303

## Type Safety

304

305

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

306

307

- **Core Entities**: `Trace`, `Observation`, `Session`, `Score`, `Prompt`, `Dataset`, `Model`

308

- **Request Types**: Query parameters, creation requests, update requests for all operations

309

- **Response Types**: Paginated lists, single entities, deletion confirmations

310

- **Enums**: Status codes, observation types, model usage units, data types

311

- **Utility Types**: Usage metrics, metadata structures, pagination metadata

312

313

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

314

315

## Environment Variables

316

317

The SDK reads configuration from these environment variables:

318

319

- `LANGFUSE_PUBLIC_KEY` - Public API key for authentication

320

- `LANGFUSE_SECRET_KEY` - Secret API key for authentication

321

- `LANGFUSE_BASE_URL` - Base API URL (default: https://cloud.langfuse.com)

322

- `LANGFUSE_LOG_LEVEL` - Logging level (DEBUG, INFO, WARN, ERROR)

323

- `LANGFUSE_TIMEOUT` - Request timeout in milliseconds

324

- `LANGFUSE_FLUSH_AT` - Batch size for flushing operations

325

- `LANGFUSE_FLUSH_INTERVAL` - Flush interval in milliseconds

326

- `LANGFUSE_RELEASE` - Release identifier for traces

327

- `LANGFUSE_TRACING_ENVIRONMENT` - Environment identifier for traces

328

329

## Best Practices

330

331

1. **Authentication**: Store API keys securely using environment variables, never hardcode them

332

2. **Error Handling**: Catch specific error types (`UnauthorizedError`, `NotFoundError`) for better UX

333

3. **Pagination**: Always implement pagination for list operations to handle large datasets

334

4. **Field Selection**: Use the `fields` parameter on trace queries to reduce payload size

335

5. **Media Optimization**: Use media references rather than embedding large content directly in traces

336

6. **Environment Naming**: Use lowercase alphanumeric with hyphens/underscores, avoid 'langfuse' prefix

337

7. **Cost Tracking**: Prefer `usageDetails` and `costDetails` over deprecated `usage` field

338

8. **OpenTelemetry**: Prefer OpenTelemetry endpoint over legacy batch ingestion for new integrations

339

9. **Logger Configuration**: Configure global logger early in application initialization

340

10. **Type Safety**: Leverage TypeScript types for compile-time validation and IDE autocompletion

341

342

## Platform Compatibility

343

344

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

345

346

- **Node.js**: Full support for Node.js environments (v20+)

347

- **Browser**: Compatible with modern browsers via bundlers (webpack, vite, etc.)

348

- **Edge Runtime**: Compatible with edge computing platforms (Cloudflare Workers, Vercel Edge)

349

- **Build System**: Available as ESM (.mjs) and CommonJS (.cjs) with TypeScript definitions

350

351

## Related Documentation

352

353

- **Official Docs**: https://langfuse.com/docs/sdk/typescript

354

- **API Reference**: https://js.reference.langfuse.com

355

- **GitHub Repository**: https://github.com/langfuse/langfuse-js

356

- **OpenTelemetry Integration**: https://langfuse.com/integrations/native/opentelemetry

357