0
# Public API
1
2
Direct access to Langfuse REST API endpoints through the `api` property. The public API client provides low-level access to all Langfuse backend operations, including operations not exposed through convenience methods.
3
4
## Capabilities
5
6
### Accessing the API Client
7
8
The `api` property provides access to the auto-generated REST API client.
9
10
```typescript { .api }
11
class Langfuse {
12
/** Public API client for direct API access */
13
api: LangfusePublicApi<null>["api"];
14
}
15
```
16
17
**Usage Example:**
18
19
```typescript
20
import { Langfuse } from 'langfuse';
21
22
const langfuse = new Langfuse({
23
publicKey: 'pk-lf-...',
24
secretKey: 'sk-lf-...'
25
});
26
27
// Access API groups
28
const traces = await langfuse.api.traces.list({ page: 1, limit: 10 });
29
const models = await langfuse.api.models.list();
30
const scores = await langfuse.api.score.list({ page: 1 });
31
```
32
33
## API Groups
34
35
The API client is organized into functional groups. All methods return promises and follow REST conventions.
36
37
### Traces API
38
39
Operations for managing traces.
40
41
```typescript { .api }
42
interface TracesAPI {
43
/** List traces with filtering */
44
list(query?: GetLangfuseTracesQuery): Promise<GetLangfuseTracesResponse>;
45
46
/** Get a specific trace by ID */
47
get(traceId: string): Promise<{ data: GetLangfuseTraceResponse }>;
48
}
49
```
50
51
**Usage Example:**
52
53
```typescript
54
// List traces
55
const traces = await langfuse.api.traces.list({
56
page: 1,
57
limit: 50,
58
userId: 'user-123',
59
tags: ['production'],
60
fromTimestamp: '2024-01-01T00:00:00Z'
61
});
62
63
// Get specific trace
64
const trace = await langfuse.api.traces.get('trace-id-123');
65
```
66
67
### Observations API
68
69
Operations for managing observations (spans, generations, events).
70
71
```typescript { .api }
72
interface ObservationsAPI {
73
/** List observations with filtering */
74
list(query?: GetLangfuseObservationsQuery): Promise<GetLangfuseObservationsResponse>;
75
76
/** Get a specific observation by ID */
77
get(observationId: string): Promise<{ data: GetLangfuseObservationResponse }>;
78
}
79
```
80
81
**Usage Example:**
82
83
```typescript
84
// List all generations
85
const generations = await langfuse.api.observations.list({
86
type: 'GENERATION',
87
page: 1,
88
limit: 100
89
});
90
91
// Get specific observation
92
const observation = await langfuse.api.observations.get('obs-id-123');
93
```
94
95
### Sessions API
96
97
Operations for managing sessions.
98
99
```typescript { .api }
100
interface SessionsAPI {
101
/** List sessions with filtering */
102
list(query?: GetLangfuseSessionsQuery): Promise<GetLangfuseSessionsResponse>;
103
}
104
```
105
106
**Usage Example:**
107
108
```typescript
109
// List recent sessions
110
const sessions = await langfuse.api.sessions.list({
111
page: 1,
112
limit: 50,
113
fromTimestamp: '2024-01-01T00:00:00Z'
114
});
115
```
116
117
### Dataset API
118
119
Operations for managing datasets.
120
121
```typescript { .api }
122
interface DatasetAPI {
123
/** List datasets */
124
list(): Promise<ApiPaginatedDatasets>;
125
126
/** Get a specific dataset */
127
get(datasetName: string): Promise<{ data: GetLangfuseDatasetResponse }>;
128
129
/** Create a dataset */
130
create(body: CreateLangfuseDatasetBody): Promise<CreateLangfuseDatasetResponse>;
131
}
132
```
133
134
**Usage Example:**
135
136
```typescript
137
// List all datasets
138
const datasets = await langfuse.api.dataset.list();
139
140
// Get specific dataset
141
const dataset = await langfuse.api.dataset.get('eval-dataset');
142
143
// Create new dataset
144
const newDataset = await langfuse.api.dataset.create({
145
name: 'new-eval-dataset',
146
description: 'Evaluation dataset for Q1 2024'
147
});
148
```
149
150
### Dataset Items API
151
152
Operations for managing dataset items.
153
154
```typescript { .api }
155
interface DatasetItemsAPI {
156
/** List items for a dataset */
157
list(datasetName: string, query?: any): Promise<GetLangfuseDatasetItemsResponse>;
158
159
/** Get a specific dataset item */
160
get(itemId: string): Promise<CreateLangfuseDatasetItemResponse>;
161
162
/** Create a dataset item */
163
create(body: CreateLangfuseDatasetItemBody): Promise<CreateLangfuseDatasetItemResponse>;
164
}
165
```
166
167
**Usage Example:**
168
169
```typescript
170
// List dataset items
171
const items = await langfuse.api.datasetItems.list('eval-dataset', {
172
page: 1,
173
limit: 100
174
});
175
176
// Get specific item
177
const item = await langfuse.api.datasetItems.get('item-id-123');
178
179
// Create item
180
const newItem = await langfuse.api.datasetItems.create({
181
datasetName: 'eval-dataset',
182
input: { question: 'What is AI?' },
183
expectedOutput: { answer: 'Artificial Intelligence...' }
184
});
185
```
186
187
### Dataset Run Items API
188
189
Operations for managing dataset run items.
190
191
```typescript { .api }
192
interface DatasetRunItemsAPI {
193
/** Create a dataset run item */
194
create(body: CreateLangfuseDatasetRunItemBody): Promise<CreateLangfuseDatasetRunItemResponse>;
195
}
196
```
197
198
**Usage Example:**
199
200
```typescript
201
// Link trace to dataset item
202
const runItem = await langfuse.api.datasetRunItems.create({
203
runName: 'gpt4-evaluation',
204
datasetItemId: 'item-123',
205
traceId: 'trace-456',
206
observationId: 'obs-789'
207
});
208
```
209
210
### Prompts API
211
212
Operations for managing prompts.
213
214
```typescript { .api }
215
interface PromptsAPI {
216
/** List prompt versions */
217
list(params: { name: string; version?: number; label?: string }): Promise<any>;
218
219
/** Get a specific prompt */
220
get(name: string, version?: number, label?: string): Promise<LangfusePromptRecord>;
221
222
/** Create a prompt */
223
create(body: CreateTextPromptBody | CreateChatPromptBody): Promise<CreateLangfusePromptResponse>;
224
}
225
```
226
227
**Usage Example:**
228
229
```typescript
230
// List prompt versions
231
const versions = await langfuse.api.prompts.list({
232
name: 'chat-template'
233
});
234
235
// Get specific version
236
const prompt = await langfuse.api.prompts.get('chat-template', 3);
237
238
// Create new prompt
239
const newPrompt = await langfuse.api.prompts.create({
240
name: 'new-template',
241
prompt: 'Hello {{name}}!',
242
labels: ['production']
243
});
244
```
245
246
### Score API
247
248
Operations for managing scores.
249
250
```typescript { .api }
251
interface ScoreAPI {
252
/** List scores */
253
list(query?: any): Promise<ApiGetScoresResponse>;
254
255
/** Create a score */
256
create(body: CreateLangfuseScoreBody): Promise<any>;
257
}
258
```
259
260
**Usage Example:**
261
262
```typescript
263
// List scores
264
const scores = await langfuse.api.score.list({
265
page: 1,
266
limit: 50,
267
name: 'quality'
268
});
269
270
// Create score
271
const score = await langfuse.api.score.create({
272
traceId: 'trace-123',
273
name: 'accuracy',
274
value: 0.95
275
});
276
```
277
278
### Score Configs API
279
280
Operations for managing score configurations.
281
282
```typescript { .api }
283
interface ScoreConfigsAPI {
284
/** List score configurations */
285
list(): Promise<ApiScoreConfigs>;
286
287
/** Create score configuration */
288
create(body: ApiCreateScoreConfigRequest): Promise<ApiScoreConfig>;
289
}
290
```
291
292
**Usage Example:**
293
294
```typescript
295
// List score configs
296
const configs = await langfuse.api.scoreConfigs.list();
297
298
// Create score config
299
const config = await langfuse.api.scoreConfigs.create({
300
name: 'quality',
301
dataType: 'NUMERIC',
302
minValue: 0,
303
maxValue: 1
304
});
305
```
306
307
### Models API
308
309
Operations for managing models.
310
311
```typescript { .api }
312
interface ModelsAPI {
313
/** List models */
314
list(): Promise<ApiPaginatedModels>;
315
316
/** Create a model */
317
create(body: ApiCreateModelRequest): Promise<ApiModel>;
318
}
319
```
320
321
**Usage Example:**
322
323
```typescript
324
// List available models
325
const models = await langfuse.api.models.list();
326
327
// Register custom model with pricing
328
const model = await langfuse.api.models.create({
329
modelName: 'custom-gpt-4',
330
matchPattern: 'custom-gpt-4.*',
331
unit: 'TOKENS',
332
inputPrice: 0.00003,
333
outputPrice: 0.00006
334
});
335
```
336
337
### Media API
338
339
Operations for managing media content.
340
341
```typescript { .api }
342
interface MediaAPI {
343
/** Get media metadata */
344
get(mediaId: string): Promise<GetMediaResponse>;
345
346
/** Get upload URL for media */
347
getUploadUrl(body: ApiGetMediaUploadUrlRequest): Promise<ApiGetMediaUploadUrlResponse>;
348
349
/** Update media metadata */
350
patch(mediaId: string, body: ApiPatchMediaBody): Promise<any>;
351
}
352
```
353
354
**Usage Example:**
355
356
```typescript
357
// Get media info
358
const media = await langfuse.api.media.get('media-id-123');
359
360
// Get upload URL
361
const uploadUrl = await langfuse.api.media.getUploadUrl({
362
contentType: 'image/png',
363
contentLength: 12345
364
});
365
366
// Upload media to URL
367
await fetch(uploadUrl.uploadUrl, {
368
method: 'PUT',
369
body: imageBuffer,
370
headers: { 'Content-Type': 'image/png' }
371
});
372
373
// Update media metadata
374
await langfuse.api.media.patch('media-id-123', {
375
metadata: { description: 'User uploaded image' }
376
});
377
```
378
379
### Comments API
380
381
Operations for managing comments (annotations).
382
383
```typescript { .api }
384
interface CommentsAPI {
385
/** List comments */
386
list(query: { objectType: string; objectId: string }): Promise<ApiGetCommentsResponse>;
387
388
/** Create a comment */
389
create(body: ApiCreateCommentRequest): Promise<ApiCreateCommentResponse>;
390
}
391
```
392
393
**Usage Example:**
394
395
```typescript
396
// List comments for a trace
397
const comments = await langfuse.api.comments.list({
398
objectType: 'TRACE',
399
objectId: 'trace-id-123'
400
});
401
402
// Create comment
403
const comment = await langfuse.api.comments.create({
404
objectType: 'TRACE',
405
objectId: 'trace-id-123',
406
content: 'This trace shows excellent performance'
407
});
408
```
409
410
### Annotation Queues API
411
412
Operations for managing annotation queues (enterprise feature).
413
414
```typescript { .api }
415
interface AnnotationQueuesAPI {
416
/** List annotation queues */
417
list(): Promise<ApiPaginatedAnnotationQueues>;
418
419
/** List items in a queue */
420
listItems(queueId: string): Promise<ApiPaginatedAnnotationQueueItems>;
421
422
/** Add item to queue */
423
addItem(body: ApiCreateAnnotationQueueItemRequest): Promise<any>;
424
425
/** Update queue item */
426
updateItem(itemId: string, body: ApiUpdateAnnotationQueueItemRequest): Promise<any>;
427
}
428
```
429
430
**Usage Example:**
431
432
```typescript
433
// List queues
434
const queues = await langfuse.api.annotationQueues.list();
435
436
// Get items in queue
437
const items = await langfuse.api.annotationQueues.listItems('queue-id-123');
438
439
// Add trace to annotation queue
440
await langfuse.api.annotationQueues.addItem({
441
queueId: 'queue-id-123',
442
objectType: 'TRACE',
443
objectId: 'trace-id-456'
444
});
445
```
446
447
### Projects API
448
449
Operations for managing projects.
450
451
```typescript { .api }
452
interface ProjectsAPI {
453
/** List projects */
454
list(): Promise<ApiProjects>;
455
456
/** Get project details */
457
get(projectId: string): Promise<ApiProject>;
458
}
459
```
460
461
**Usage Example:**
462
463
```typescript
464
// List all projects
465
const projects = await langfuse.api.projects.list();
466
467
// Get specific project
468
const project = await langfuse.api.projects.get('project-id-123');
469
```
470
471
### Ingestion API
472
473
Low-level event ingestion endpoint.
474
475
```typescript { .api }
476
interface IngestionAPI {
477
/** Batch ingest events */
478
batch(body: { batch: ApiIngestionEvent[] }): Promise<ApiIngestionResponse>;
479
}
480
```
481
482
**Usage Example:**
483
484
```typescript
485
// Batch ingest events (advanced usage)
486
const response = await langfuse.api.ingestion.batch({
487
batch: [
488
{
489
type: 'trace-create',
490
id: 'trace-123',
491
timestamp: new Date().toISOString(),
492
body: {
493
id: 'trace-123',
494
name: 'my-trace'
495
}
496
}
497
]
498
});
499
```
500
501
### Health and Metrics API
502
503
Health check and metrics endpoints.
504
505
```typescript { .api }
506
interface HealthAPI {
507
/** Health check */
508
check(): Promise<ApiHealthResponse>;
509
}
510
511
interface MetricsAPI {
512
/** Get metrics */
513
get(): Promise<ApiMetricsResponse>;
514
}
515
```
516
517
**Usage Example:**
518
519
```typescript
520
// Health check
521
const health = await langfuse.api.health.check();
522
console.log(health.status); // "ok"
523
524
// Get metrics
525
const metrics = await langfuse.api.metrics.get();
526
```
527
528
## Complete Public API Example
529
530
```typescript
531
import { Langfuse } from 'langfuse';
532
533
const langfuse = new Langfuse({
534
publicKey: 'pk-lf-...',
535
secretKey: 'sk-lf-...'
536
});
537
538
// Fetch traces from the last 7 days
539
const oneWeekAgo = new Date();
540
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
541
542
const traces = await langfuse.api.traces.list({
543
page: 1,
544
limit: 100,
545
fromTimestamp: oneWeekAgo.toISOString(),
546
tags: ['production']
547
});
548
549
// Analyze each trace
550
for (const trace of traces.data) {
551
// Get full trace details
552
const fullTrace = await langfuse.api.traces.get(trace.id);
553
554
// Get observations for this trace
555
const observations = await langfuse.api.observations.list({
556
traceId: trace.id,
557
type: 'GENERATION'
558
});
559
560
// Calculate average quality score
561
const scores = await langfuse.api.score.list({
562
traceId: trace.id,
563
name: 'quality'
564
});
565
566
const avgScore = scores.data.reduce((sum, s) => sum + Number(s.value), 0) / scores.data.length;
567
568
// Add comment if quality is low
569
if (avgScore < 0.5) {
570
await langfuse.api.comments.create({
571
objectType: 'TRACE',
572
objectId: trace.id,
573
content: `Low quality trace: avg score ${avgScore.toFixed(2)}`
574
});
575
576
// Add to annotation queue for review
577
await langfuse.api.annotationQueues.addItem({
578
queueId: 'review-queue',
579
objectType: 'TRACE',
580
objectId: trace.id
581
});
582
}
583
}
584
585
// Get all datasets
586
const datasets = await langfuse.api.dataset.list();
587
588
// For each dataset, check completeness
589
for (const dataset of datasets.data) {
590
const items = await langfuse.api.datasetItems.list(dataset.name, {
591
page: 1,
592
limit: 1000
593
});
594
595
console.log(`Dataset ${dataset.name}: ${items.data.length} items`);
596
597
// Check for items without expected output
598
const incomplete = items.data.filter(item => !item.expectedOutput);
599
600
if (incomplete.length > 0) {
601
console.log(` ${incomplete.length} items missing expected output`);
602
}
603
}
604
605
// List all available models and their pricing
606
const models = await langfuse.api.models.list();
607
608
for (const model of models.data) {
609
console.log(`${model.modelName}:`);
610
console.log(` Input: $${model.inputPrice}/1k ${model.unit}`);
611
console.log(` Output: $${model.outputPrice}/1k ${model.unit}`);
612
}
613
614
// Health check
615
const health = await langfuse.api.health.check();
616
console.log('Langfuse status:', health.status);
617
```
618
619
## API Types
620
621
The public API includes 190+ auto-generated TypeScript types from the OpenAPI specification. Key type categories include:
622
623
- **Trace Types**: `ApiTrace`, `ApiTraceWithDetails`, `ApiTraceWithFullDetails`, `ApiTraceBody`
624
- **Observation Types**: `ApiObservation`, `ApiObservationsView`, `ApiObservationType`, `ApiObservationLevel`
625
- **Score Types**: `ApiScore`, `ApiScoreConfig`, `ApiScoreDataType`, `ApiScoreSource`
626
- **Dataset Types**: `ApiDataset`, `ApiDatasetItem`, `ApiDatasetRun`, `ApiDatasetRunItem`
627
- **Prompt Types**: `ApiPrompt`, `ApiTextPrompt`, `ApiChatPrompt`, `ApiPromptMeta`
628
- **Model Types**: `ApiModel`, `ApiModelPrice`, `ApiModelUsageUnit`
629
- **Media Types**: `ApiMediaContentType`, `ApiGetMediaResponse`, `ApiGetMediaUploadUrlResponse`
630
- **Session Types**: `ApiSession`, `ApiSessionWithTraces`
631
- **Comment Types**: `ApiComment`, `ApiCommentObjectType`
632
- **Annotation Types**: `ApiAnnotationQueue`, `ApiAnnotationQueueItem`, `ApiAnnotationQueueStatus`
633
- **Ingestion Types**: `ApiIngestionEvent`, `ApiIngestionResponse`, `ApiIngestionSuccess`, `ApiIngestionError`
634
- **Usage Types**: `ApiUsage`, `ApiUsageDetails`, `ApiOpenAIUsage`
635
- **Pagination Types**: `ApiPaginatedDatasets`, `ApiPaginatedDatasetItems`, `ApiPaginatedModels`
636
637
All types are exported from the main package and can be imported:
638
639
```typescript
640
import type {
641
ApiTrace,
642
ApiObservation,
643
ApiScore,
644
ApiDataset,
645
ApiPrompt,
646
ApiModel
647
} from 'langfuse';
648
```
649
650
## Notes
651
652
- The public API client is auto-generated from the OpenAPI specification and provides low-level access to all backend operations
653
- Most common operations are available through higher-level convenience methods (e.g., `langfuse.trace()`, `langfuse.getDataset()`)
654
- Use the public API for advanced operations not exposed through convenience methods or for building custom integrations
655
- All API methods return promises and should be awaited
656
- API responses follow standard REST conventions with data and metadata structures
657
- Rate limiting and error handling are automatically managed by the client
658