0
# API Resources
1
2
Comprehensive documentation for all 23 API resource clients providing access to traces, observations, prompts, datasets, scores, and platform management features.
3
4
## Overview
5
6
All API resources are accessed through the `LangfuseAPIClient` and provide type-safe methods for CRUD operations. Each resource is lazily instantiated and includes complete TypeScript type definitions.
7
8
```typescript
9
import { LangfuseAPIClient } from '@langfuse/core';
10
11
const client = new LangfuseAPIClient({
12
environment: 'https://cloud.langfuse.com',
13
username: 'pk-lf-...',
14
password: 'sk-lf-...'
15
});
16
17
// Access any resource
18
const trace = await client.trace.get('trace-id');
19
const prompts = await client.prompts.list();
20
```
21
22
## Core Observability Resources
23
24
### Trace Resource
25
26
Complete trace lifecycle management including creation, retrieval, deletion, and querying.
27
28
```typescript { .api }
29
interface Trace {
30
get(traceId: string, options?: RequestOptions): Promise<TraceWithFullDetails>;
31
list(request?: GetTracesRequest, options?: RequestOptions): Promise<Traces>;
32
delete(traceId: string, options?: RequestOptions): Promise<DeleteTraceResponse>;
33
deleteMultiple(request: DeleteTracesRequest, options?: RequestOptions): Promise<DeleteTraceResponse>;
34
}
35
36
interface GetTracesRequest {
37
page?: number;
38
limit?: number;
39
userId?: string;
40
name?: string;
41
sessionId?: string;
42
fromTimestamp?: string;
43
toTimestamp?: string;
44
orderBy?: string;
45
tags?: string | string[];
46
version?: string;
47
release?: string;
48
environment?: string | string[];
49
fields?: string;
50
}
51
52
interface TraceWithFullDetails {
53
id: string;
54
timestamp: string;
55
name?: string;
56
input?: unknown;
57
output?: unknown;
58
sessionId?: string;
59
release?: string;
60
version?: string;
61
userId?: string;
62
metadata?: unknown;
63
tags?: string[];
64
public?: boolean;
65
environment?: string;
66
observations?: Observation[];
67
scores?: Score[];
68
}
69
70
interface Traces {
71
data: TraceWithFullDetails[];
72
meta: MetaResponse;
73
}
74
75
interface DeleteTraceResponse {
76
message: string;
77
}
78
```
79
80
**Usage Examples:**
81
82
```typescript
83
// Get a specific trace with full details
84
const trace = await client.trace.get('trace-123');
85
console.log(trace.name, trace.userId, trace.observations);
86
87
// List traces with filters
88
const traces = await client.trace.list({
89
page: 1,
90
limit: 50,
91
userId: 'user-123',
92
sessionId: 'session-456',
93
fromTimestamp: '2024-01-01T00:00:00Z',
94
toTimestamp: '2024-12-31T23:59:59Z',
95
tags: ['production', 'api'],
96
environment: 'production',
97
orderBy: 'timestamp.desc',
98
fields: 'core,scores,metrics' // Optimize response size
99
});
100
101
// Iterate through paginated results
102
for (const trace of traces.data) {
103
console.log(`${trace.id}: ${trace.name}`);
104
}
105
106
// Delete a trace
107
await client.trace.delete('trace-123');
108
109
// Delete multiple traces
110
await client.trace.deleteMultiple({
111
traceIds: ['trace-1', 'trace-2', 'trace-3']
112
});
113
```
114
115
### Observations Resource
116
117
Query observations (spans, generations, events) with detailed filtering.
118
119
```typescript { .api }
120
interface Observations {
121
get(observationId: string, options?: RequestOptions): Promise<Observation>;
122
getMany(request?: GetObservationsRequest, options?: RequestOptions): Promise<ObservationsViews>;
123
}
124
125
interface GetObservationsRequest {
126
page?: number;
127
limit?: number;
128
name?: string;
129
userId?: string;
130
type?: string;
131
traceId?: string;
132
parentObservationId?: string;
133
fromStartTime?: string;
134
toStartTime?: string;
135
version?: string;
136
}
137
138
interface Observation {
139
id: string;
140
traceId?: string;
141
type: string;
142
name?: string;
143
startTime: string;
144
endTime?: string;
145
completionStartTime?: string;
146
model?: string;
147
modelParameters?: Record<string, MapValue>;
148
input?: unknown;
149
output?: unknown;
150
version?: string;
151
metadata?: unknown;
152
usage?: Usage;
153
usageDetails?: Record<string, number>;
154
costDetails?: Record<string, number>;
155
level: ObservationLevel;
156
statusMessage?: string;
157
parentObservationId?: string;
158
promptId?: string;
159
environment?: string;
160
}
161
162
enum ObservationLevel {
163
DEBUG = "DEBUG",
164
DEFAULT = "DEFAULT",
165
WARNING = "WARNING",
166
ERROR = "ERROR"
167
}
168
169
interface ObservationsViews {
170
data: ObservationView[];
171
meta: MetaResponse;
172
}
173
```
174
175
**Usage Examples:**
176
177
```typescript
178
// Get a single observation
179
const observation = await client.observations.get('obs-123');
180
console.log(observation.name, observation.type, observation.model);
181
182
// List all observations for a trace
183
const observations = await client.observations.getMany({
184
traceId: 'trace-123',
185
page: 1,
186
limit: 100
187
});
188
189
// Filter by observation type
190
const generations = await client.observations.getMany({
191
type: 'GENERATION',
192
fromStartTime: '2024-01-01T00:00:00Z'
193
});
194
195
// Find errors
196
const errors = await client.observations.getMany({
197
level: 'ERROR',
198
limit: 50
199
});
200
201
// Get observations for a specific user
202
const userObservations = await client.observations.getMany({
203
userId: 'user-123',
204
name: 'chat-completion'
205
});
206
```
207
208
### Sessions Resource
209
210
Session grouping and analytics for organizing related traces.
211
212
```typescript { .api }
213
interface Sessions {
214
list(request?: GetSessionsRequest, options?: RequestOptions): Promise<PaginatedSessions>;
215
}
216
217
interface Session {
218
id: string;
219
createdAt: string;
220
projectId: string;
221
}
222
223
interface PaginatedSessions {
224
data: Session[];
225
meta: MetaResponse;
226
}
227
```
228
229
**Usage Examples:**
230
231
```typescript
232
// List sessions
233
const sessions = await client.sessions.list({
234
page: 1,
235
limit: 50,
236
fromTimestamp: '2024-01-01T00:00:00Z'
237
});
238
239
// Find sessions for a user
240
const userSessions = await client.sessions.list({
241
userId: 'user-123'
242
});
243
```
244
245
## Prompt Management Resources
246
247
### Prompts Resource
248
249
Version-controlled prompt template management with labels and tags.
250
251
```typescript { .api }
252
interface Prompts {
253
get(promptName: string, request?: GetPromptRequest, options?: RequestOptions): Promise<Prompt>;
254
list(request?: ListPromptsMetaRequest, options?: RequestOptions): Promise<PromptMetaListResponse>;
255
create(request: CreatePromptRequest, options?: RequestOptions): Promise<Prompt>;
256
}
257
258
interface GetPromptRequest {
259
version?: number;
260
label?: string;
261
}
262
263
interface ListPromptsMetaRequest {
264
name?: string;
265
label?: string;
266
tag?: string;
267
page?: number;
268
limit?: number;
269
fromUpdatedAt?: string;
270
toUpdatedAt?: string;
271
}
272
273
type Prompt = TextPrompt | ChatPrompt;
274
275
interface TextPrompt {
276
type: 'text';
277
name: string;
278
prompt: string;
279
config?: Record<string, unknown>;
280
labels?: string[];
281
tags?: string[];
282
version: number;
283
}
284
285
interface ChatPrompt {
286
type: 'chat';
287
name: string;
288
prompt: ChatMessage[];
289
config?: Record<string, unknown>;
290
labels?: string[];
291
tags?: string[];
292
version: number;
293
}
294
295
interface ChatMessage {
296
role: string;
297
content: string;
298
}
299
300
type CreatePromptRequest = CreateTextPromptRequest | CreateChatPromptRequest;
301
302
interface CreateTextPromptRequest {
303
type: 'text';
304
name: string;
305
prompt: string;
306
config?: Record<string, unknown>;
307
labels?: string[];
308
tags?: string[];
309
}
310
311
interface CreateChatPromptRequest {
312
type: 'chat';
313
name: string;
314
prompt: ChatMessage[];
315
config?: Record<string, unknown>;
316
labels?: string[];
317
tags?: string[];
318
}
319
```
320
321
**Usage Examples:**
322
323
```typescript
324
// Get latest version of a prompt
325
const prompt = await client.prompts.get('chat-assistant');
326
327
// Get specific version
328
const promptV2 = await client.prompts.get('chat-assistant', { version: 2 });
329
330
// Get by label
331
const prodPrompt = await client.prompts.get('chat-assistant', { label: 'production' });
332
333
// List prompts
334
const prompts = await client.prompts.list({
335
page: 1,
336
limit: 50,
337
tag: 'gpt-4',
338
label: 'production'
339
});
340
341
// Create text prompt
342
await client.prompts.create({
343
type: 'text',
344
name: 'summarize-text',
345
prompt: 'Summarize the following text:\n\n{{text}}',
346
config: {
347
temperature: 0.7,
348
max_tokens: 500
349
},
350
labels: ['production'],
351
tags: ['summarization']
352
});
353
354
// Create chat prompt
355
await client.prompts.create({
356
type: 'chat',
357
name: 'customer-support',
358
prompt: [
359
{
360
role: 'system',
361
content: 'You are a helpful customer support assistant.'
362
},
363
{
364
role: 'user',
365
content: '{{user_message}}'
366
}
367
],
368
config: {
369
temperature: 0.7,
370
model: 'gpt-4'
371
},
372
labels: ['latest'],
373
tags: ['support', 'gpt-4']
374
});
375
```
376
377
## Evaluation Resources
378
379
### Datasets Resource
380
381
Test dataset management for evaluation and testing.
382
383
```typescript { .api }
384
interface Datasets {
385
list(request?: ListDatasetsRequest, options?: RequestOptions): Promise<PaginatedDatasets>;
386
get(datasetName: string, options?: RequestOptions): Promise<Dataset>;
387
create(request: CreateDatasetRequest, options?: RequestOptions): Promise<Dataset>;
388
getRun(datasetName: string, runName: string, options?: RequestOptions): Promise<DatasetRunWithItems>;
389
deleteRun(datasetName: string, runName: string, options?: RequestOptions): Promise<DeleteDatasetRunResponse>;
390
getRuns(datasetName: string, request?: GetDatasetRunsRequest, options?: RequestOptions): Promise<PaginatedDatasetRuns>;
391
}
392
393
interface Dataset {
394
id: string;
395
name: string;
396
description?: string;
397
metadata?: unknown;
398
projectId: string;
399
createdAt: string;
400
updatedAt: string;
401
status: DatasetStatus;
402
}
403
404
enum DatasetStatus {
405
ACTIVE = "ACTIVE",
406
ARCHIVED = "ARCHIVED"
407
}
408
409
interface CreateDatasetRequest {
410
name: string;
411
description?: string;
412
metadata?: unknown;
413
}
414
415
interface PaginatedDatasets {
416
data: Dataset[];
417
meta: MetaResponse;
418
}
419
420
interface PaginatedDatasetRuns {
421
data: DatasetRun[];
422
meta: MetaResponse;
423
}
424
```
425
426
**Usage Examples:**
427
428
```typescript
429
// List datasets
430
const datasets = await client.datasets.list({
431
page: 1,
432
limit: 50
433
});
434
435
// Get a specific dataset by name
436
const dataset = await client.datasets.get('customer-support-eval');
437
438
// Create dataset
439
const newDataset = await client.datasets.create({
440
name: 'Customer Support Eval',
441
description: 'Test cases for customer support chatbot',
442
metadata: {
443
category: 'support',
444
version: '1.0'
445
}
446
});
447
448
// Get a specific dataset run
449
const run = await client.datasets.getRun('customer-support-eval', 'run-2024-01');
450
451
// Delete a dataset run
452
await client.datasets.deleteRun('customer-support-eval', 'run-2024-01');
453
454
// Get all dataset runs
455
const runs = await client.datasets.getRuns('customer-support-eval', {
456
page: 1,
457
limit: 25
458
});
459
```
460
461
### Dataset Items Resource
462
463
Individual dataset entries for test cases.
464
465
```typescript { .api }
466
interface DatasetItems {
467
create(request: CreateDatasetItemRequest, options?: RequestOptions): Promise<DatasetItem>;
468
get(id: string, options?: RequestOptions): Promise<DatasetItem>;
469
list(request?: GetDatasetItemsRequest, options?: RequestOptions): Promise<PaginatedDatasetItems>;
470
delete(id: string, options?: RequestOptions): Promise<DeleteDatasetItemResponse>;
471
}
472
473
interface DatasetItem {
474
id: string;
475
datasetId: string;
476
input: unknown;
477
expectedOutput?: unknown;
478
metadata?: unknown;
479
sourceTraceId?: string;
480
sourceObservationId?: string;
481
createdAt: string;
482
updatedAt: string;
483
}
484
485
interface CreateDatasetItemRequest {
486
datasetId: string;
487
input: unknown;
488
expectedOutput?: unknown;
489
metadata?: unknown;
490
sourceTraceId?: string;
491
sourceObservationId?: string;
492
}
493
```
494
495
**Usage Examples:**
496
497
```typescript
498
// Create dataset item
499
const item = await client.datasetItems.create({
500
datasetName: 'customer-support-eval',
501
input: {
502
message: 'How do I reset my password?'
503
},
504
expectedOutput: {
505
response: 'Click on "Forgot Password" on the login page...',
506
category: 'account'
507
},
508
metadata: {
509
difficulty: 'easy',
510
language: 'en'
511
}
512
});
513
514
// Get a specific dataset item
515
const datasetItem = await client.datasetItems.get('item-456');
516
517
// List dataset items
518
const items = await client.datasetItems.list({
519
datasetName: 'customer-support-eval',
520
page: 1,
521
limit: 50
522
});
523
524
// Delete dataset item
525
await client.datasetItems.delete('item-456');
526
```
527
528
### Dataset Run Items Resource
529
530
Track individual test case executions within a dataset run.
531
532
```typescript { .api }
533
interface DatasetRunItems {
534
create(request: CreateDatasetRunItemRequest, options?: RequestOptions): Promise<DatasetRunItem>;
535
}
536
537
interface DatasetRunItem {
538
id: string;
539
datasetRunId: string;
540
datasetItemId: string;
541
traceId: string;
542
observationId?: string;
543
createdAt: string;
544
}
545
546
interface CreateDatasetRunItemRequest {
547
datasetRunId: string;
548
datasetItemId: string;
549
traceId: string;
550
observationId?: string;
551
}
552
```
553
554
**Usage Examples:**
555
556
```typescript
557
// Create dataset run item (link trace to test case)
558
await client.datasetRunItems.create({
559
datasetRunId: 'run-789',
560
datasetItemId: 'item-456',
561
traceId: 'trace-123',
562
observationId: 'obs-abc'
563
});
564
```
565
566
### Score Resource
567
568
Score creation for evaluation and feedback.
569
570
```typescript { .api }
571
interface Score {
572
create(request: CreateScoreRequest, options?: RequestOptions): Promise<CreateScoreResponse>;
573
}
574
575
interface CreateScoreRequest {
576
name: string;
577
value: CreateScoreValue;
578
traceId: string;
579
observationId?: string;
580
comment?: string;
581
dataType?: ScoreDataType;
582
configId?: string;
583
}
584
585
type CreateScoreValue = number | string | boolean;
586
587
enum ScoreDataType {
588
NUMERIC = "NUMERIC",
589
CATEGORICAL = "CATEGORICAL",
590
BOOLEAN = "BOOLEAN"
591
}
592
```
593
594
**Usage Examples:**
595
596
```typescript
597
// Create numeric score
598
await client.score.create({
599
name: 'accuracy',
600
value: 0.95,
601
dataType: 'NUMERIC',
602
traceId: 'trace-123',
603
comment: 'High accuracy response'
604
});
605
606
// Create boolean score
607
await client.score.create({
608
name: 'hallucination',
609
value: false,
610
dataType: 'BOOLEAN',
611
traceId: 'trace-123',
612
observationId: 'obs-456'
613
});
614
615
// Create categorical score
616
await client.score.create({
617
name: 'sentiment',
618
value: 'positive',
619
dataType: 'CATEGORICAL',
620
traceId: 'trace-123'
621
});
622
```
623
624
### Score V2 Resource
625
626
Query scores with detailed filtering and pagination.
627
628
```typescript { .api }
629
interface ScoreV2 {
630
list(request?: GetScoresRequest, options?: RequestOptions): Promise<GetScoresResponse>;
631
}
632
633
interface GetScoresResponse {
634
data: GetScoresResponseData[];
635
meta: MetaResponse;
636
}
637
638
type GetScoresResponseData =
639
| GetScoresResponseDataNumeric
640
| GetScoresResponseDataCategorical
641
| GetScoresResponseDataBoolean;
642
```
643
644
**Usage Examples:**
645
646
```typescript
647
// List scores for a trace
648
const scores = await client.scoreV2.list({
649
traceId: 'trace-123'
650
});
651
652
// List scores by name
653
const accuracyScores = await client.scoreV2.list({
654
name: 'accuracy',
655
fromTimestamp: '2024-01-01T00:00:00Z'
656
});
657
```
658
659
### Score Configs Resource
660
661
Score configuration and schema management.
662
663
```typescript { .api }
664
interface ScoreConfigs {
665
create(request: CreateScoreConfigRequest, options?: RequestOptions): Promise<ScoreConfig>;
666
get(request?: GetScoreConfigsRequest, options?: RequestOptions): Promise<ScoreConfigs>;
667
getById(configId: string, options?: RequestOptions): Promise<ScoreConfig>;
668
}
669
670
interface ScoreConfig {
671
id: string;
672
name: string;
673
dataType: ScoreDataType;
674
isArchived: boolean;
675
categories?: ConfigCategory[];
676
description?: string;
677
minValue?: number;
678
maxValue?: number;
679
}
680
681
interface CreateScoreConfigRequest {
682
name: string;
683
dataType: ScoreDataType;
684
categories?: ConfigCategory[];
685
description?: string;
686
minValue?: number;
687
maxValue?: number;
688
}
689
```
690
691
**Usage Examples:**
692
693
```typescript
694
// Get all score configs
695
const configs = await client.scoreConfigs.get();
696
697
// Get a specific score config by ID
698
const config = await client.scoreConfigs.getById('config-id-123');
699
700
// Create numeric score config
701
await client.scoreConfigs.create({
702
name: 'relevance',
703
dataType: 'NUMERIC',
704
minValue: 0,
705
maxValue: 1,
706
description: 'Response relevance score'
707
});
708
709
// Create categorical score config
710
await client.scoreConfigs.create({
711
name: 'category',
712
dataType: 'CATEGORICAL',
713
categories: [
714
{ value: 'technical', label: 'Technical' },
715
{ value: 'billing', label: 'Billing' },
716
{ value: 'general', label: 'General' }
717
],
718
description: 'Request category classification'
719
});
720
```
721
722
## Platform Management Resources
723
724
### Projects Resource
725
726
Project administration and API key management. Organization-scoped API keys required for create, update, delete, and API key management operations.
727
728
```typescript { .api }
729
interface Projects {
730
get(options?: RequestOptions): Promise<Projects>;
731
create(request: CreateProjectRequest, options?: RequestOptions): Promise<Project>;
732
update(projectId: string, request: UpdateProjectRequest, options?: RequestOptions): Promise<Project>;
733
delete(projectId: string, options?: RequestOptions): Promise<ProjectDeletionResponse>;
734
getApiKeys(projectId: string, options?: RequestOptions): Promise<ApiKeyList>;
735
createApiKey(projectId: string, request?: CreateApiKeyRequest, options?: RequestOptions): Promise<ApiKeyResponse>;
736
deleteApiKey(projectId: string, apiKeyId: string, options?: RequestOptions): Promise<ApiKeyDeletionResponse>;
737
}
738
739
interface Project {
740
id: string;
741
name: string;
742
createdAt: string;
743
updatedAt: string;
744
}
745
```
746
747
**Usage Examples:**
748
749
```typescript
750
// Get project associated with API key
751
const projects = await client.projects.get();
752
753
// Create a new project (requires org-scoped API key)
754
const newProject = await client.projects.create({
755
name: 'My New Project',
756
retention: 30
757
});
758
759
// Update a project (requires org-scoped API key)
760
const updatedProject = await client.projects.update('project-123', {
761
name: 'Updated Project Name',
762
retention: 60
763
});
764
765
// Delete project (requires org-scoped API key)
766
await client.projects.delete('project-123');
767
768
// Get API keys for a project (requires org-scoped API key)
769
const apiKeys = await client.projects.getApiKeys('project-123');
770
771
// Create new API key (requires org-scoped API key)
772
const newApiKey = await client.projects.createApiKey('project-123', {
773
note: 'Production API key'
774
});
775
776
// Delete API key (requires org-scoped API key)
777
await client.projects.deleteApiKey('project-123', 'api-key-id-456');
778
```
779
780
### Organizations Resource
781
782
Multi-tenant organization management and membership. Requires organization-scoped API keys.
783
784
```typescript { .api }
785
interface Organizations {
786
getOrganizationMemberships(options?: RequestOptions): Promise<MembershipsResponse>;
787
updateOrganizationMembership(request: MembershipRequest, options?: RequestOptions): Promise<MembershipResponse>;
788
deleteOrganizationMembership(request: DeleteMembershipRequest, options?: RequestOptions): Promise<MembershipDeletionResponse>;
789
getProjectMemberships(projectId: string, options?: RequestOptions): Promise<MembershipsResponse>;
790
updateProjectMembership(projectId: string, request: MembershipRequest, options?: RequestOptions): Promise<MembershipResponse>;
791
deleteProjectMembership(projectId: string, request: DeleteMembershipRequest, options?: RequestOptions): Promise<MembershipDeletionResponse>;
792
getOrganizationProjects(options?: RequestOptions): Promise<OrganizationProjectsResponse>;
793
}
794
795
enum MembershipRole {
796
OWNER = "OWNER",
797
ADMIN = "ADMIN",
798
MEMBER = "MEMBER",
799
VIEWER = "VIEWER"
800
}
801
802
interface MembershipRequest {
803
email: string;
804
role: MembershipRole;
805
organizationId: string;
806
}
807
```
808
809
**Usage Examples:**
810
811
```typescript
812
// Get organization memberships
813
const orgMemberships = await client.organizations.getOrganizationMemberships();
814
815
// Update organization membership (create or update)
816
await client.organizations.updateOrganizationMembership({
817
userId: 'user-456',
818
role: 'ADMIN'
819
});
820
821
// Delete organization membership
822
await client.organizations.deleteOrganizationMembership({
823
userId: 'user-456'
824
});
825
826
// Get project memberships
827
const projectMemberships = await client.organizations.getProjectMemberships('project-123');
828
829
// Update project membership
830
await client.organizations.updateProjectMembership('project-123', {
831
userId: 'user-789',
832
role: 'MEMBER'
833
});
834
835
// Delete project membership
836
await client.organizations.deleteProjectMembership('project-123', {
837
userId: 'user-789'
838
});
839
840
// Get organization projects
841
const projects = await client.organizations.getOrganizationProjects();
842
```
843
844
### Models Resource
845
846
Model configuration and pricing management.
847
848
```typescript { .api }
849
interface Models {
850
list(request?: ListModelsRequest, options?: RequestOptions): Promise<PaginatedModels>;
851
create(request: CreateModelRequest, options?: RequestOptions): Promise<Model>;
852
}
853
854
interface Model {
855
id: string;
856
modelName: string;
857
matchPattern: string;
858
unit: ModelUsageUnit;
859
inputPrice?: number;
860
outputPrice?: number;
861
totalPrice?: number;
862
tokenizerId?: string;
863
tokenizerConfig?: Record<string, unknown>;
864
}
865
866
enum ModelUsageUnit {
867
TOKENS = "TOKENS",
868
CHARACTERS = "CHARACTERS",
869
SECONDS = "SECONDS",
870
IMAGES = "IMAGES"
871
}
872
873
interface CreateModelRequest {
874
modelName: string;
875
matchPattern: string;
876
unit: ModelUsageUnit;
877
inputPrice?: number;
878
outputPrice?: number;
879
totalPrice?: number;
880
tokenizerId?: string;
881
tokenizerConfig?: Record<string, unknown>;
882
}
883
```
884
885
**Usage Examples:**
886
887
```typescript
888
// List models
889
const models = await client.models.list({
890
page: 1,
891
limit: 50
892
});
893
894
// Create model configuration
895
await client.models.create({
896
modelName: 'gpt-4-turbo',
897
matchPattern: 'gpt-4-turbo*',
898
unit: 'TOKENS',
899
inputPrice: 0.00001, // $0.01 per 1k tokens
900
outputPrice: 0.00003 // $0.03 per 1k tokens
901
});
902
```
903
904
### Media Resource
905
906
Media upload and retrieval for rich content.
907
908
```typescript { .api }
909
interface Media {
910
get(mediaId: string, options?: RequestOptions): Promise<GetMediaResponse>;
911
getUploadUrl(request: GetMediaUploadUrlRequest, options?: RequestOptions): Promise<GetMediaUploadUrlResponse>;
912
patch(mediaId: string, body: PatchMediaBody, options?: RequestOptions): Promise<void>;
913
}
914
915
interface GetMediaResponse {
916
mediaId: string;
917
contentType: MediaContentType;
918
contentLength: number;
919
uploadedAt: string;
920
}
921
922
interface GetMediaUploadUrlRequest {
923
traceId: string;
924
observationId?: string;
925
contentType: MediaContentType;
926
contentLength: number;
927
sha256Hash: string;
928
field: string;
929
}
930
931
interface GetMediaUploadUrlResponse {
932
mediaId: string;
933
uploadUrl: string;
934
}
935
```
936
937
**Usage Examples:**
938
939
```typescript
940
// Get media info
941
const media = await client.media.get('media-123');
942
943
// Get upload URL
944
const { mediaId, uploadUrl } = await client.media.getUploadUrl({
945
contentType: 'image/png',
946
contentLength: 102400,
947
sha256Hash: 'abc123...'
948
});
949
950
// Upload to URL (using fetch)
951
await fetch(uploadUrl, {
952
method: 'PUT',
953
headers: { 'Content-Type': 'image/png' },
954
body: imageBytes
955
});
956
```
957
958
## Additional Resources
959
960
### Health Resource
961
962
Health check endpoint for monitoring.
963
964
```typescript { .api }
965
interface Health {
966
health(options?: RequestOptions): Promise<HealthResponse>;
967
}
968
969
interface HealthResponse {
970
status: string;
971
version: string;
972
}
973
```
974
975
**Usage Examples:**
976
977
```typescript
978
// Check API health
979
const health = await client.health.health();
980
console.log(`Status: ${health.status}, Version: ${health.version}`);
981
```
982
983
### Metrics Resource
984
985
Analytics and metrics queries.
986
987
```typescript { .api }
988
interface Metrics {
989
metrics(request: GetMetricsRequest, options?: RequestOptions): Promise<MetricsResponse>;
990
}
991
```
992
993
**Usage Examples:**
994
995
```typescript
996
// Get metrics
997
const metrics = await client.metrics.metrics({
998
query: 'traces-count'
999
});
1000
```
1001
1002
### Comments Resource
1003
1004
Comment management for traces and observations.
1005
1006
```typescript { .api }
1007
interface Comments {
1008
create(request: CreateCommentRequest, options?: RequestOptions): Promise<CreateCommentResponse>;
1009
get(request?: GetCommentsRequest, options?: RequestOptions): Promise<GetCommentsResponse>;
1010
}
1011
1012
interface CreateCommentRequest {
1013
projectId: string;
1014
objectType: CommentObjectType;
1015
objectId: string;
1016
content: string;
1017
authorUserId?: string;
1018
}
1019
1020
interface CreateCommentResponse {
1021
id: string;
1022
}
1023
1024
interface GetCommentsRequest {
1025
projectId?: string;
1026
objectType?: string;
1027
objectId?: string;
1028
authorUserId?: string;
1029
}
1030
1031
interface GetCommentsResponse {
1032
data: Comment[];
1033
meta: MetaResponse;
1034
}
1035
1036
interface Comment {
1037
id: string;
1038
projectId: string;
1039
objectType: string;
1040
objectId: string;
1041
content: string;
1042
authorUserId?: string;
1043
createdAt: string;
1044
updatedAt: string;
1045
}
1046
1047
enum CommentObjectType {
1048
TRACE = "TRACE",
1049
OBSERVATION = "OBSERVATION"
1050
}
1051
```
1052
1053
**Usage Examples:**
1054
1055
```typescript
1056
// Create comment on trace
1057
await client.comments.create({
1058
projectId: 'project-123',
1059
objectType: 'TRACE',
1060
objectId: 'trace-123',
1061
content: 'This trace shows an interesting edge case'
1062
});
1063
1064
// Get comments with filtering
1065
const comments = await client.comments.get({
1066
projectId: 'project-123',
1067
objectType: 'TRACE',
1068
objectId: 'trace-123'
1069
});
1070
1071
// Get all comments for a project
1072
const allComments = await client.comments.get({
1073
projectId: 'project-123'
1074
});
1075
```
1076
1077
### Annotation Queues Resource
1078
1079
Annotation workflow management for human review.
1080
1081
```typescript { .api }
1082
interface AnnotationQueues {
1083
listQueues(request?: GetAnnotationQueuesRequest, options?: RequestOptions): Promise<PaginatedAnnotationQueues>;
1084
createQueue(request: CreateAnnotationQueueRequest, options?: RequestOptions): Promise<AnnotationQueue>;
1085
getQueue(queueId: string, options?: RequestOptions): Promise<AnnotationQueue>;
1086
listQueueItems(queueId: string, request?: GetAnnotationQueueItemsRequest, options?: RequestOptions): Promise<PaginatedAnnotationQueueItems>;
1087
getQueueItem(queueId: string, itemId: string, options?: RequestOptions): Promise<AnnotationQueueItem>;
1088
createQueueItem(queueId: string, request: CreateAnnotationQueueItemRequest, options?: RequestOptions): Promise<AnnotationQueueItem>;
1089
updateQueueItem(queueId: string, itemId: string, request: UpdateAnnotationQueueItemRequest, options?: RequestOptions): Promise<AnnotationQueueItem>;
1090
deleteQueueItem(queueId: string, itemId: string, options?: RequestOptions): Promise<void>;
1091
createQueueAssignment(queueId: string, request: AnnotationQueueAssignmentRequest, options?: RequestOptions): Promise<AnnotationQueueAssignment>;
1092
deleteQueueAssignment(queueId: string, request: AnnotationQueueAssignmentRequest, options?: RequestOptions): Promise<void>;
1093
}
1094
1095
interface GetAnnotationQueuesRequest {
1096
page?: number;
1097
limit?: number;
1098
}
1099
1100
interface CreateAnnotationQueueRequest {
1101
name: string;
1102
description?: string;
1103
scoreConfigIds: string[];
1104
}
1105
1106
interface GetAnnotationQueueItemsRequest {
1107
page?: number;
1108
limit?: number;
1109
}
1110
1111
interface CreateAnnotationQueueItemRequest {
1112
objectId: string;
1113
objectType: string;
1114
}
1115
1116
interface UpdateAnnotationQueueItemRequest {
1117
status?: string;
1118
assignedTo?: string;
1119
}
1120
1121
interface AnnotationQueueAssignmentRequest {
1122
userId: string;
1123
}
1124
1125
interface AnnotationQueue {
1126
id: string;
1127
name: string;
1128
description?: string;
1129
projectId: string;
1130
scoreConfigIds: string[];
1131
createdAt: string;
1132
updatedAt: string;
1133
}
1134
1135
interface AnnotationQueueItem {
1136
id: string;
1137
queueId: string;
1138
objectId: string;
1139
objectType: string;
1140
status?: string;
1141
assignedTo?: string;
1142
createdAt: string;
1143
updatedAt: string;
1144
}
1145
1146
interface AnnotationQueueAssignment {
1147
queueId: string;
1148
userId: string;
1149
createdAt: string;
1150
}
1151
1152
interface PaginatedAnnotationQueues {
1153
data: AnnotationQueue[];
1154
meta: MetaResponse;
1155
}
1156
1157
interface PaginatedAnnotationQueueItems {
1158
data: AnnotationQueueItem[];
1159
meta: MetaResponse;
1160
}
1161
```
1162
1163
**Usage Examples:**
1164
1165
```typescript
1166
// List all annotation queues
1167
const queues = await client.annotationQueues.listQueues({
1168
page: 1,
1169
limit: 50
1170
});
1171
1172
// Create annotation queue
1173
const queue = await client.annotationQueues.createQueue({
1174
name: 'Manual Review',
1175
description: 'Traces requiring manual review',
1176
scoreConfigIds: ['score-config-1', 'score-config-2']
1177
});
1178
1179
// Get a specific queue
1180
const queue = await client.annotationQueues.getQueue('queue-123');
1181
1182
// List items in a queue
1183
const items = await client.annotationQueues.listQueueItems('queue-123', {
1184
page: 1,
1185
limit: 50
1186
});
1187
1188
// Get a specific queue item
1189
const item = await client.annotationQueues.getQueueItem('queue-123', 'item-456');
1190
1191
// Add an item to a queue
1192
await client.annotationQueues.createQueueItem('queue-123', {
1193
objectId: 'trace-789',
1194
objectType: 'TRACE'
1195
});
1196
1197
// Update a queue item
1198
await client.annotationQueues.updateQueueItem('queue-123', 'item-456', {
1199
status: 'IN_PROGRESS',
1200
assignedTo: 'user-123'
1201
});
1202
1203
// Remove an item from a queue
1204
await client.annotationQueues.deleteQueueItem('queue-123', 'item-456');
1205
1206
// Create queue assignment
1207
await client.annotationQueues.createQueueAssignment('queue-123', {
1208
userId: 'user-456'
1209
});
1210
1211
// Delete queue assignment
1212
await client.annotationQueues.deleteQueueAssignment('queue-123', {
1213
userId: 'user-456'
1214
});
1215
```
1216
1217
### LLM Connections Resource
1218
1219
LLM integration configuration management.
1220
1221
```typescript { .api }
1222
interface LlmConnections {
1223
list(request?: GetLlmConnectionsRequest, options?: RequestOptions): Promise<PaginatedLlmConnections>;
1224
upsert(request: UpsertLlmConnectionRequest, options?: RequestOptions): Promise<LlmConnection>;
1225
}
1226
1227
interface GetLlmConnectionsRequest {
1228
page?: number;
1229
limit?: number;
1230
}
1231
1232
interface UpsertLlmConnectionRequest {
1233
provider: string;
1234
adapter: "anthropic" | "openai" | "azure";
1235
secretKey: string;
1236
baseURL?: string;
1237
customModels?: LlmConnectionModel[];
1238
withDefaultModels?: boolean;
1239
extraHeaders?: Record<string, string>;
1240
}
1241
1242
interface LlmConnectionModel {
1243
id: string;
1244
modelName: string;
1245
inputPrice?: number;
1246
outputPrice?: number;
1247
}
1248
1249
interface LlmConnection {
1250
id: string;
1251
provider: string;
1252
adapter: string;
1253
baseURL?: string;
1254
customModels?: LlmConnectionModel[];
1255
withDefaultModels?: boolean;
1256
createdAt: string;
1257
updatedAt: string;
1258
}
1259
1260
interface PaginatedLlmConnections {
1261
data: LlmConnection[];
1262
meta: MetaResponse;
1263
}
1264
```
1265
1266
**Usage Examples:**
1267
1268
```typescript
1269
// List LLM connections
1270
const connections = await client.llmConnections.list({
1271
page: 1,
1272
limit: 50
1273
});
1274
1275
// Create/update OpenAI connection
1276
await client.llmConnections.upsert({
1277
provider: 'openai-production',
1278
adapter: 'openai',
1279
secretKey: process.env.OPENAI_API_KEY,
1280
withDefaultModels: true
1281
});
1282
1283
// Create/update Anthropic connection with custom models
1284
await client.llmConnections.upsert({
1285
provider: 'anthropic-production',
1286
adapter: 'anthropic',
1287
secretKey: process.env.ANTHROPIC_API_KEY,
1288
customModels: [
1289
{
1290
id: 'custom-claude',
1291
modelName: 'claude-3-5-sonnet-20241022',
1292
inputPrice: 0.000003,
1293
outputPrice: 0.000015
1294
}
1295
]
1296
});
1297
1298
// Create/update Azure OpenAI connection
1299
await client.llmConnections.upsert({
1300
provider: 'azure-production',
1301
adapter: 'azure',
1302
secretKey: process.env.AZURE_API_KEY,
1303
baseURL: 'https://my-resource.openai.azure.com',
1304
extraHeaders: {
1305
'api-version': '2024-02-15-preview'
1306
}
1307
});
1308
```
1309
1310
### Blob Storage Integrations Resource
1311
1312
Blob storage configuration for data export.
1313
1314
```typescript { .api }
1315
interface BlobStorageIntegrations {
1316
getBlobStorageIntegrations(options?: RequestOptions): Promise<BlobStorageIntegrationsResponse>;
1317
upsertBlobStorageIntegration(request: CreateBlobStorageIntegrationRequest, options?: RequestOptions): Promise<BlobStorageIntegrationResponse>;
1318
deleteBlobStorageIntegration(id: string, options?: RequestOptions): Promise<void>;
1319
}
1320
1321
interface CreateBlobStorageIntegrationRequest {
1322
projectId: string;
1323
type: "S3";
1324
bucketName: string;
1325
endpoint?: string;
1326
region: string;
1327
accessKeyId?: string;
1328
secretAccessKey?: string;
1329
prefix?: string;
1330
exportFrequency: "hourly" | "daily";
1331
enabled: boolean;
1332
forcePathStyle: boolean;
1333
fileType: "JSON";
1334
exportMode: "FULL_HISTORY" | "INCREMENTAL";
1335
exportStartDate?: string;
1336
}
1337
1338
interface BlobStorageIntegrationResponse {
1339
id: string;
1340
projectId: string;
1341
type: string;
1342
bucketName: string;
1343
region: string;
1344
prefix?: string;
1345
exportFrequency: string;
1346
enabled: boolean;
1347
fileType: string;
1348
exportMode: string;
1349
createdAt: string;
1350
updatedAt: string;
1351
}
1352
1353
interface BlobStorageIntegrationsResponse {
1354
data: BlobStorageIntegrationResponse[];
1355
}
1356
```
1357
1358
**Usage Examples:**
1359
1360
```typescript
1361
// List all blob storage integrations
1362
const integrations = await client.blobStorageIntegrations.getBlobStorageIntegrations();
1363
1364
// Create or update S3 integration with full history export
1365
await client.blobStorageIntegrations.upsertBlobStorageIntegration({
1366
projectId: 'project-123',
1367
type: 'S3',
1368
bucketName: 'langfuse-exports',
1369
region: 'us-east-1',
1370
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
1371
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
1372
prefix: 'production/',
1373
exportFrequency: 'daily',
1374
enabled: true,
1375
forcePathStyle: false,
1376
fileType: 'JSON',
1377
exportMode: 'FULL_HISTORY'
1378
});
1379
1380
// Create or update S3 integration with incremental export
1381
await client.blobStorageIntegrations.upsertBlobStorageIntegration({
1382
projectId: 'project-123',
1383
type: 'S3',
1384
bucketName: 'langfuse-incremental',
1385
region: 'eu-west-1',
1386
exportFrequency: 'hourly',
1387
enabled: true,
1388
forcePathStyle: false,
1389
fileType: 'JSON',
1390
exportMode: 'INCREMENTAL',
1391
exportStartDate: '2024-01-01T00:00:00Z'
1392
});
1393
1394
// Create S3-compatible integration (e.g., MinIO)
1395
await client.blobStorageIntegrations.upsertBlobStorageIntegration({
1396
projectId: 'project-123',
1397
type: 'S3',
1398
bucketName: 'my-bucket',
1399
endpoint: 'https://minio.example.com',
1400
region: 'us-east-1',
1401
accessKeyId: 'minioadmin',
1402
secretAccessKey: 'minioadmin',
1403
exportFrequency: 'daily',
1404
enabled: true,
1405
forcePathStyle: true,
1406
fileType: 'JSON',
1407
exportMode: 'FULL_HISTORY'
1408
});
1409
1410
// Delete blob storage integration
1411
await client.blobStorageIntegrations.deleteBlobStorageIntegration('integration-id-123');
1412
```
1413
1414
### SCIM Resource
1415
1416
SCIM (System for Cross-domain Identity Management) endpoints for identity management.
1417
1418
```typescript { .api }
1419
interface Scim {
1420
getServiceProviderConfig(options?: RequestOptions): Promise<ServiceProviderConfig>;
1421
listUsers(request?: ListUsersRequest, options?: RequestOptions): Promise<ScimUsersListResponse>;
1422
}
1423
```
1424
1425
**Usage Examples:**
1426
1427
```typescript
1428
// Get SCIM configuration
1429
const config = await client.scim.getServiceProviderConfig();
1430
1431
// List SCIM users
1432
const users = await client.scim.listUsers();
1433
```
1434
1435
### Ingestion Resource (Legacy)
1436
1437
Legacy batch ingestion endpoint for high-volume data ingestion.
1438
1439
**Note**: The OpenTelemetry endpoint (`/api/public/otel`) is preferred over this legacy endpoint.
1440
1441
```typescript { .api }
1442
interface Ingestion {
1443
batch(request: IngestionRequest, options?: RequestOptions): Promise<IngestionResponse>;
1444
}
1445
1446
interface IngestionRequest {
1447
batch: IngestionEvent[];
1448
metadata?: Record<string, unknown>;
1449
}
1450
1451
type IngestionEvent =
1452
| TraceEvent
1453
| CreateObservationEvent
1454
| UpdateObservationEvent
1455
| CreateGenerationEvent
1456
| UpdateGenerationEvent
1457
| CreateSpanEvent
1458
| UpdateSpanEvent
1459
| CreateEventEvent
1460
| ScoreEvent
1461
| SdkLogEvent;
1462
1463
interface IngestionResponse {
1464
successes: IngestionSuccess[];
1465
errors: IngestionError[];
1466
}
1467
```
1468
1469
**Usage Examples:**
1470
1471
```typescript
1472
// Batch ingest events (legacy)
1473
const response = await client.ingestion.batch({
1474
batch: [
1475
{
1476
type: 'trace-create',
1477
id: 'event-1',
1478
timestamp: '2024-01-01T00:00:00Z',
1479
body: {
1480
id: 'trace-1',
1481
name: 'Chat Request',
1482
userId: 'user-123',
1483
input: { message: 'Hello' },
1484
output: { response: 'Hi there!' }
1485
}
1486
},
1487
{
1488
type: 'generation-create',
1489
id: 'event-2',
1490
timestamp: '2024-01-01T00:00:01Z',
1491
body: {
1492
id: 'gen-1',
1493
traceId: 'trace-1',
1494
name: 'OpenAI Call',
1495
model: 'gpt-4',
1496
input: { messages: [{ role: 'user', content: 'Hello' }] },
1497
output: { message: { role: 'assistant', content: 'Hi there!' } },
1498
usageDetails: {
1499
promptTokens: 10,
1500
completionTokens: 5,
1501
totalTokens: 15
1502
}
1503
}
1504
}
1505
]
1506
});
1507
1508
console.log(`Successes: ${response.successes.length}`);
1509
console.log(`Errors: ${response.errors.length}`);
1510
```
1511
1512
## Common Types
1513
1514
### Pagination
1515
1516
```typescript { .api }
1517
interface MetaResponse {
1518
page: number;
1519
limit: number;
1520
totalItems: number;
1521
totalPages: number;
1522
}
1523
```
1524
1525
### Usage and Cost (Deprecated)
1526
1527
**Note**: Prefer `usageDetails` and `costDetails` for new implementations.
1528
1529
```typescript { .api }
1530
interface Usage {
1531
input?: number;
1532
output?: number;
1533
total?: number;
1534
unit?: ModelUsageUnit;
1535
inputCost?: number;
1536
outputCost?: number;
1537
totalCost?: number;
1538
}
1539
```
1540
1541
## Best Practices
1542
1543
1. **Pagination**: Always implement pagination for list operations
1544
2. **Field Selection**: Use `fields` parameter on traces to reduce payload
1545
3. **Filtering**: Apply filters at the API level rather than in application code
1546
4. **Batch Operations**: Use batch ingestion for high-volume scenarios
1547
5. **Error Handling**: Catch and handle specific error types for each operation
1548
6. **Resource Cleanup**: Delete unused traces and datasets to manage storage
1549
7. **Prompt Versioning**: Use labels for environment promotion (dev → staging → production)
1550
8. **Score Configs**: Define score configurations before creating scores
1551
9. **Media Upload**: Use media upload URLs rather than inline base64 for large files
1552
10. **OpenTelemetry**: Prefer OpenTelemetry endpoint over legacy batch ingestion
1553