or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

autoevals-adapter.mdclient.mddatasets.mdexperiments.mdindex.mdmedia.mdprompts.mdscores.md

client.mddocs/

0

# Client Initialization

1

2

The LangfuseClient class is the main entry point for interacting with Langfuse. It provides centralized access to all managers and the underlying API client.

3

4

## Capabilities

5

6

### Create Client Instance

7

8

Initialize a LangfuseClient with credentials and configuration.

9

10

```typescript { .api }

11

/**

12

* Creates a new Langfuse client instance

13

* @param params - Optional configuration parameters

14

*/

15

function LangfuseClient(params?: LangfuseClientParams): LangfuseClient;

16

17

interface LangfuseClientParams {

18

/** Public API key (or use LANGFUSE_PUBLIC_KEY env var) */

19

publicKey?: string;

20

/** Secret API key (or use LANGFUSE_SECRET_KEY env var) */

21

secretKey?: string;

22

/** Langfuse instance URL (default: "https://cloud.langfuse.com") */

23

baseUrl?: string;

24

/** Request timeout in seconds (default: 5) */

25

timeout?: number;

26

/** Additional HTTP headers to include with requests */

27

additionalHeaders?: Record<string, string>;

28

}

29

```

30

31

**Usage Examples:**

32

33

```typescript

34

import { LangfuseClient } from '@langfuse/client';

35

36

// Initialize with explicit credentials

37

const langfuse = new LangfuseClient({

38

publicKey: 'pk_...',

39

secretKey: 'sk_...',

40

baseUrl: 'https://cloud.langfuse.com'

41

});

42

43

// Initialize using environment variables

44

// LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, LANGFUSE_BASE_URL

45

const langfuse = new LangfuseClient();

46

47

// With custom timeout and headers

48

const langfuse = new LangfuseClient({

49

publicKey: 'pk_...',

50

secretKey: 'sk_...',

51

timeout: 10,

52

additionalHeaders: {

53

'X-Custom-Header': 'value'

54

}

55

});

56

57

// Self-hosted instance

58

const langfuse = new LangfuseClient({

59

publicKey: 'pk_...',

60

secretKey: 'sk_...',

61

baseUrl: 'https://langfuse.example.com'

62

});

63

```

64

65

### Access Managers

66

67

The client provides access to specialized managers for different capabilities.

68

69

```typescript { .api }

70

class LangfuseClient {

71

/** Direct access to Langfuse API client for advanced operations */

72

readonly api: LangfuseAPIClient;

73

74

/** Manager for prompt operations (fetch, create, update, caching) */

75

readonly prompt: PromptManager;

76

77

/** Manager for dataset operations (fetch datasets with items) */

78

readonly dataset: DatasetManager;

79

80

/** Manager for score operations (create, batch, flush) */

81

readonly score: ScoreManager;

82

83

/** Manager for media operations (resolve media references) */

84

readonly media: MediaManager;

85

86

/** Manager for experiment execution and evaluation */

87

readonly experiment: ExperimentManager;

88

}

89

```

90

91

**Usage Examples:**

92

93

```typescript

94

const langfuse = new LangfuseClient();

95

96

// Use prompt manager

97

const prompt = await langfuse.prompt.get('my-prompt');

98

99

// Use dataset manager

100

const dataset = await langfuse.dataset.get('my-dataset');

101

102

// Use score manager

103

langfuse.score.create({

104

name: 'quality',

105

value: 0.85,

106

traceId: 'trace-123'

107

});

108

109

// Use media manager

110

const resolved = await langfuse.media.resolveReferences({

111

obj: myObject,

112

resolveWith: 'base64DataUri'

113

});

114

115

// Use experiment manager

116

const result = await langfuse.experiment.run({

117

name: 'Evaluation',

118

data: items,

119

task: myTask,

120

evaluators: [myEvaluator]

121

});

122

123

// Use API client directly for advanced operations

124

const traces = await langfuse.api.trace.list({ limit: 10 });

125

const observations = await langfuse.api.observations.getMany({ limit: 20 });

126

```

127

128

### Flush Pending Data

129

130

Ensure all queued scores are sent to the API immediately.

131

132

```typescript { .api }

133

/**

134

* Flushes all pending score events to the Langfuse API

135

* @returns Promise that resolves when all pending scores have been sent

136

*/

137

flush(): Promise<void>;

138

```

139

140

**Usage Examples:**

141

142

```typescript

143

const langfuse = new LangfuseClient();

144

145

// Create some scores (queued automatically)

146

langfuse.score.create({ name: 'quality', value: 0.8, traceId: 'abc' });

147

langfuse.score.create({ name: 'latency', value: 120, traceId: 'abc' });

148

149

// Force immediate send

150

await langfuse.flush();

151

152

// Before application exit

153

async function cleanup() {

154

await langfuse.flush();

155

process.exit(0);

156

}

157

```

158

159

### Graceful Shutdown

160

161

Shut down the client gracefully by flushing all pending data.

162

163

```typescript { .api }

164

/**

165

* Gracefully shuts down the client by flushing all pending data

166

* @returns Promise that resolves when shutdown is complete

167

*/

168

shutdown(): Promise<void>;

169

```

170

171

**Usage Examples:**

172

173

```typescript

174

const langfuse = new LangfuseClient();

175

176

// ... use the client ...

177

178

// Before application exit, ensure all data is sent

179

await langfuse.shutdown();

180

181

// In an Express.js app

182

process.on('SIGTERM', async () => {

183

console.log('SIGTERM received, shutting down gracefully');

184

await langfuse.shutdown();

185

process.exit(0);

186

});

187

188

// In a Next.js API route

189

export default async function handler(req, res) {

190

const langfuse = new LangfuseClient();

191

192

// ... handle request ...

193

194

// Flush before response

195

await langfuse.shutdown();

196

res.status(200).json({ success: true });

197

}

198

```

199

200

### Generate Trace URL

201

202

Generate a URL to view a specific trace in the Langfuse web UI.

203

204

```typescript { .api }

205

/**

206

* Generates a URL to view a trace in the Langfuse UI

207

* @param traceId - The ID of the trace

208

* @returns Promise resolving to the trace URL

209

*/

210

getTraceUrl(traceId: string): Promise<string>;

211

```

212

213

**Usage Examples:**

214

215

```typescript

216

const langfuse = new LangfuseClient();

217

218

// Generate URL for a specific trace

219

const traceId = 'trace-abc-123';

220

const url = await langfuse.getTraceUrl(traceId);

221

console.log(`View trace at: ${url}`);

222

// Output: View trace at: https://cloud.langfuse.com/project/proj-123/traces/trace-abc-123

223

224

// After running an experiment

225

const result = await langfuse.experiment.run({

226

name: 'Model Test',

227

data: items,

228

task: myTask

229

});

230

231

// Get URLs for all experiment traces

232

for (const itemResult of result.itemResults) {

233

if (itemResult.traceId) {

234

const traceUrl = await langfuse.getTraceUrl(itemResult.traceId);

235

console.log(`Item trace: ${traceUrl}`);

236

}

237

}

238

239

// In error logging

240

try {

241

await riskyOperation(traceId);

242

} catch (error) {

243

const traceUrl = await langfuse.getTraceUrl(traceId);

244

console.error(`Operation failed. Debug at: ${traceUrl}`);

245

throw error;

246

}

247

```

248

249

## Configuration

250

251

### Environment Variables

252

253

The client can be configured using environment variables:

254

255

| Variable | Description | Default |

256

|----------|-------------|---------|

257

| `LANGFUSE_PUBLIC_KEY` | Public API key | Required if not in constructor |

258

| `LANGFUSE_SECRET_KEY` | Secret API key | Required if not in constructor |

259

| `LANGFUSE_BASE_URL` | Langfuse instance URL | `https://cloud.langfuse.com` |

260

| `LANGFUSE_BASEURL` | Legacy alias for BASE_URL | Deprecated, use BASE_URL |

261

| `LANGFUSE_TIMEOUT` | Request timeout (seconds) | 5 |

262

263

**Usage Example:**

264

265

```bash

266

# .env file

267

LANGFUSE_PUBLIC_KEY=pk_...

268

LANGFUSE_SECRET_KEY=sk_...

269

LANGFUSE_BASE_URL=https://cloud.langfuse.com

270

LANGFUSE_TIMEOUT=10

271

```

272

273

```typescript

274

// Client will use environment variables

275

const langfuse = new LangfuseClient();

276

```

277

278

### Constructor Parameters vs Environment Variables

279

280

Constructor parameters take precedence over environment variables:

281

282

```typescript

283

// Environment: LANGFUSE_BASE_URL=https://cloud.langfuse.com

284

285

const langfuse = new LangfuseClient({

286

publicKey: 'pk_...',

287

secretKey: 'sk_...',

288

baseUrl: 'https://custom.langfuse.com' // Overrides env var

289

});

290

// Uses https://custom.langfuse.com

291

```

292

293

## Error Handling

294

295

### Missing Credentials

296

297

If credentials are not provided via constructor or environment variables, warnings are logged but the client is still created:

298

299

```typescript

300

const langfuse = new LangfuseClient();

301

// Logs warnings:

302

// "No public key provided in constructor or as LANGFUSE_PUBLIC_KEY env var..."

303

// "No secret key provided in constructor or as LANGFUSE_SECRET_KEY env var..."

304

// Client operations will fail until credentials are available

305

```

306

307

### Network Errors

308

309

API operations may throw errors on network failures:

310

311

```typescript

312

const langfuse = new LangfuseClient({

313

publicKey: 'pk_...',

314

secretKey: 'sk_...',

315

timeout: 1 // Very short timeout

316

});

317

318

try {

319

const prompt = await langfuse.prompt.get('my-prompt');

320

} catch (error) {

321

console.error('Failed to fetch prompt:', error.message);

322

// Handle timeout or network error

323

}

324

```

325

326

## Advanced Usage

327

328

### Direct API Access

329

330

For operations not covered by managers, use the `api` property:

331

332

```typescript

333

const langfuse = new LangfuseClient();

334

335

// Access raw API endpoints

336

const projects = await langfuse.api.projects.get();

337

const traces = await langfuse.api.trace.list({ limit: 100 });

338

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

339

const observations = await langfuse.api.observations.getMany({

340

traceId: 'trace-id',

341

limit: 50

342

});

343

const sessions = await langfuse.api.sessions.get({ limit: 20 });

344

345

// Dataset operations

346

const datasets = await langfuse.api.datasets.list();

347

const dataset = await langfuse.api.datasets.create({

348

name: 'new-dataset',

349

description: 'My dataset'

350

});

351

const run = await langfuse.api.datasets.getRun('dataset-name', 'run-id');

352

const runs = await langfuse.api.datasets.getRuns('dataset-name');

353

354

// Dataset items

355

const items = await langfuse.api.datasetItems.list({ datasetName: 'my-dataset' });

356

const item = await langfuse.api.datasetItems.get('item-id');

357

const newItem = await langfuse.api.datasetItems.create({

358

datasetName: 'my-dataset',

359

input: { question: 'What is AI?' },

360

expectedOutput: 'AI is...'

361

});

362

363

// Media operations

364

const media = await langfuse.api.media.get('media-id');

365

366

// Prompts

367

const prompts = await langfuse.api.prompts.list();

368

const promptVersions = await langfuse.api.promptVersion.list('prompt-name');

369

```

370

371

### Multiple Client Instances

372

373

You can create multiple client instances for different projects or environments:

374

375

```typescript

376

const prodClient = new LangfuseClient({

377

publicKey: 'pk_prod_...',

378

secretKey: 'sk_prod_...',

379

baseUrl: 'https://cloud.langfuse.com'

380

});

381

382

const devClient = new LangfuseClient({

383

publicKey: 'pk_dev_...',

384

secretKey: 'sk_dev_...',

385

baseUrl: 'https://dev.langfuse.com'

386

});

387

388

// Use different clients for different purposes

389

const prodPrompt = await prodClient.prompt.get('production-prompt');

390

const devPrompt = await devClient.prompt.get('experimental-prompt');

391

```

392

393

## TypeScript Support

394

395

The package provides full TypeScript support with detailed type definitions:

396

397

```typescript

398

import type {

399

LangfuseClient,

400

LangfuseClientParams,

401

TextPromptClient,

402

ChatPromptClient,

403

FetchedDataset,

404

ExperimentResult,

405

Evaluation

406

} from '@langfuse/client';

407

408

// Type-safe configuration

409

const config: LangfuseClientParams = {

410

publicKey: process.env.LANGFUSE_PUBLIC_KEY,

411

secretKey: process.env.LANGFUSE_SECRET_KEY,

412

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

413

timeout: 10

414

};

415

416

const langfuse = new LangfuseClient(config);

417

418

// Type inference works automatically

419

const prompt = await langfuse.prompt.get('my-prompt', { type: 'text' });

420

// prompt is inferred as TextPromptClient

421

422

const chatPrompt = await langfuse.prompt.get('chat-prompt', { type: 'chat' });

423

// chatPrompt is inferred as ChatPromptClient

424

```

425