CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-langfuse--core

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

Overview
Eval results
Files

api-resources.mddocs/

API Resources

Comprehensive documentation for all 23 API resource clients providing access to traces, observations, prompts, datasets, scores, and platform management features.

Overview

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.

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

const client = new LangfuseAPIClient({
  environment: 'https://cloud.langfuse.com',
  username: 'pk-lf-...',
  password: 'sk-lf-...'
});

// Access any resource
const trace = await client.trace.get('trace-id');
const prompts = await client.prompts.list();

Core Observability Resources

Trace Resource

Complete trace lifecycle management including creation, retrieval, deletion, and querying.

interface Trace {
  get(traceId: string, options?: RequestOptions): Promise<TraceWithFullDetails>;
  list(request?: GetTracesRequest, options?: RequestOptions): Promise<Traces>;
  delete(traceId: string, options?: RequestOptions): Promise<DeleteTraceResponse>;
  deleteMultiple(request: DeleteTracesRequest, options?: RequestOptions): Promise<DeleteTraceResponse>;
}

interface GetTracesRequest {
  page?: number;
  limit?: number;
  userId?: string;
  name?: string;
  sessionId?: string;
  fromTimestamp?: string;
  toTimestamp?: string;
  orderBy?: string;
  tags?: string | string[];
  version?: string;
  release?: string;
  environment?: string | string[];
  fields?: string;
}

interface TraceWithFullDetails {
  id: string;
  timestamp: string;
  name?: string;
  input?: unknown;
  output?: unknown;
  sessionId?: string;
  release?: string;
  version?: string;
  userId?: string;
  metadata?: unknown;
  tags?: string[];
  public?: boolean;
  environment?: string;
  observations?: Observation[];
  scores?: Score[];
}

interface Traces {
  data: TraceWithFullDetails[];
  meta: MetaResponse;
}

interface DeleteTraceResponse {
  message: string;
}

Usage Examples:

// Get a specific trace with full details
const trace = await client.trace.get('trace-123');
console.log(trace.name, trace.userId, trace.observations);

// List traces with filters
const traces = await client.trace.list({
  page: 1,
  limit: 50,
  userId: 'user-123',
  sessionId: 'session-456',
  fromTimestamp: '2024-01-01T00:00:00Z',
  toTimestamp: '2024-12-31T23:59:59Z',
  tags: ['production', 'api'],
  environment: 'production',
  orderBy: 'timestamp.desc',
  fields: 'core,scores,metrics'  // Optimize response size
});

// Iterate through paginated results
for (const trace of traces.data) {
  console.log(`${trace.id}: ${trace.name}`);
}

// Delete a trace
await client.trace.delete('trace-123');

// Delete multiple traces
await client.trace.deleteMultiple({
  traceIds: ['trace-1', 'trace-2', 'trace-3']
});

Observations Resource

Query observations (spans, generations, events) with detailed filtering.

interface Observations {
  get(observationId: string, options?: RequestOptions): Promise<Observation>;
  getMany(request?: GetObservationsRequest, options?: RequestOptions): Promise<ObservationsViews>;
}

interface GetObservationsRequest {
  page?: number;
  limit?: number;
  name?: string;
  userId?: string;
  type?: string;
  traceId?: string;
  parentObservationId?: string;
  fromStartTime?: string;
  toStartTime?: string;
  version?: string;
}

interface Observation {
  id: string;
  traceId?: string;
  type: string;
  name?: string;
  startTime: string;
  endTime?: string;
  completionStartTime?: string;
  model?: string;
  modelParameters?: Record<string, MapValue>;
  input?: unknown;
  output?: unknown;
  version?: string;
  metadata?: unknown;
  usage?: Usage;
  usageDetails?: Record<string, number>;
  costDetails?: Record<string, number>;
  level: ObservationLevel;
  statusMessage?: string;
  parentObservationId?: string;
  promptId?: string;
  environment?: string;
}

enum ObservationLevel {
  DEBUG = "DEBUG",
  DEFAULT = "DEFAULT",
  WARNING = "WARNING",
  ERROR = "ERROR"
}

interface ObservationsViews {
  data: ObservationView[];
  meta: MetaResponse;
}

Usage Examples:

// Get a single observation
const observation = await client.observations.get('obs-123');
console.log(observation.name, observation.type, observation.model);

// List all observations for a trace
const observations = await client.observations.getMany({
  traceId: 'trace-123',
  page: 1,
  limit: 100
});

// Filter by observation type
const generations = await client.observations.getMany({
  type: 'GENERATION',
  fromStartTime: '2024-01-01T00:00:00Z'
});

// Find errors
const errors = await client.observations.getMany({
  level: 'ERROR',
  limit: 50
});

// Get observations for a specific user
const userObservations = await client.observations.getMany({
  userId: 'user-123',
  name: 'chat-completion'
});

Sessions Resource

Session grouping and analytics for organizing related traces.

interface Sessions {
  list(request?: GetSessionsRequest, options?: RequestOptions): Promise<PaginatedSessions>;
}

interface Session {
  id: string;
  createdAt: string;
  projectId: string;
}

interface PaginatedSessions {
  data: Session[];
  meta: MetaResponse;
}

Usage Examples:

// List sessions
const sessions = await client.sessions.list({
  page: 1,
  limit: 50,
  fromTimestamp: '2024-01-01T00:00:00Z'
});

// Find sessions for a user
const userSessions = await client.sessions.list({
  userId: 'user-123'
});

Prompt Management Resources

Prompts Resource

Version-controlled prompt template management with labels and tags.

interface Prompts {
  get(promptName: string, request?: GetPromptRequest, options?: RequestOptions): Promise<Prompt>;
  list(request?: ListPromptsMetaRequest, options?: RequestOptions): Promise<PromptMetaListResponse>;
  create(request: CreatePromptRequest, options?: RequestOptions): Promise<Prompt>;
}

interface GetPromptRequest {
  version?: number;
  label?: string;
}

interface ListPromptsMetaRequest {
  name?: string;
  label?: string;
  tag?: string;
  page?: number;
  limit?: number;
  fromUpdatedAt?: string;
  toUpdatedAt?: string;
}

type Prompt = TextPrompt | ChatPrompt;

interface TextPrompt {
  type: 'text';
  name: string;
  prompt: string;
  config?: Record<string, unknown>;
  labels?: string[];
  tags?: string[];
  version: number;
}

interface ChatPrompt {
  type: 'chat';
  name: string;
  prompt: ChatMessage[];
  config?: Record<string, unknown>;
  labels?: string[];
  tags?: string[];
  version: number;
}

interface ChatMessage {
  role: string;
  content: string;
}

type CreatePromptRequest = CreateTextPromptRequest | CreateChatPromptRequest;

interface CreateTextPromptRequest {
  type: 'text';
  name: string;
  prompt: string;
  config?: Record<string, unknown>;
  labels?: string[];
  tags?: string[];
}

interface CreateChatPromptRequest {
  type: 'chat';
  name: string;
  prompt: ChatMessage[];
  config?: Record<string, unknown>;
  labels?: string[];
  tags?: string[];
}

Usage Examples:

// Get latest version of a prompt
const prompt = await client.prompts.get('chat-assistant');

// Get specific version
const promptV2 = await client.prompts.get('chat-assistant', { version: 2 });

// Get by label
const prodPrompt = await client.prompts.get('chat-assistant', { label: 'production' });

// List prompts
const prompts = await client.prompts.list({
  page: 1,
  limit: 50,
  tag: 'gpt-4',
  label: 'production'
});

// Create text prompt
await client.prompts.create({
  type: 'text',
  name: 'summarize-text',
  prompt: 'Summarize the following text:\n\n{{text}}',
  config: {
    temperature: 0.7,
    max_tokens: 500
  },
  labels: ['production'],
  tags: ['summarization']
});

// Create chat prompt
await client.prompts.create({
  type: 'chat',
  name: 'customer-support',
  prompt: [
    {
      role: 'system',
      content: 'You are a helpful customer support assistant.'
    },
    {
      role: 'user',
      content: '{{user_message}}'
    }
  ],
  config: {
    temperature: 0.7,
    model: 'gpt-4'
  },
  labels: ['latest'],
  tags: ['support', 'gpt-4']
});

Evaluation Resources

Datasets Resource

Test dataset management for evaluation and testing.

interface Datasets {
  list(request?: ListDatasetsRequest, options?: RequestOptions): Promise<PaginatedDatasets>;
  get(datasetName: string, options?: RequestOptions): Promise<Dataset>;
  create(request: CreateDatasetRequest, options?: RequestOptions): Promise<Dataset>;
  getRun(datasetName: string, runName: string, options?: RequestOptions): Promise<DatasetRunWithItems>;
  deleteRun(datasetName: string, runName: string, options?: RequestOptions): Promise<DeleteDatasetRunResponse>;
  getRuns(datasetName: string, request?: GetDatasetRunsRequest, options?: RequestOptions): Promise<PaginatedDatasetRuns>;
}

interface Dataset {
  id: string;
  name: string;
  description?: string;
  metadata?: unknown;
  projectId: string;
  createdAt: string;
  updatedAt: string;
  status: DatasetStatus;
}

enum DatasetStatus {
  ACTIVE = "ACTIVE",
  ARCHIVED = "ARCHIVED"
}

interface CreateDatasetRequest {
  name: string;
  description?: string;
  metadata?: unknown;
}

interface PaginatedDatasets {
  data: Dataset[];
  meta: MetaResponse;
}

interface PaginatedDatasetRuns {
  data: DatasetRun[];
  meta: MetaResponse;
}

Usage Examples:

// List datasets
const datasets = await client.datasets.list({
  page: 1,
  limit: 50
});

// Get a specific dataset by name
const dataset = await client.datasets.get('customer-support-eval');

// Create dataset
const newDataset = await client.datasets.create({
  name: 'Customer Support Eval',
  description: 'Test cases for customer support chatbot',
  metadata: {
    category: 'support',
    version: '1.0'
  }
});

// Get a specific dataset run
const run = await client.datasets.getRun('customer-support-eval', 'run-2024-01');

// Delete a dataset run
await client.datasets.deleteRun('customer-support-eval', 'run-2024-01');

// Get all dataset runs
const runs = await client.datasets.getRuns('customer-support-eval', {
  page: 1,
  limit: 25
});

Dataset Items Resource

Individual dataset entries for test cases.

interface DatasetItems {
  create(request: CreateDatasetItemRequest, options?: RequestOptions): Promise<DatasetItem>;
  get(id: string, options?: RequestOptions): Promise<DatasetItem>;
  list(request?: GetDatasetItemsRequest, options?: RequestOptions): Promise<PaginatedDatasetItems>;
  delete(id: string, options?: RequestOptions): Promise<DeleteDatasetItemResponse>;
}

interface DatasetItem {
  id: string;
  datasetId: string;
  input: unknown;
  expectedOutput?: unknown;
  metadata?: unknown;
  sourceTraceId?: string;
  sourceObservationId?: string;
  createdAt: string;
  updatedAt: string;
}

interface CreateDatasetItemRequest {
  datasetId: string;
  input: unknown;
  expectedOutput?: unknown;
  metadata?: unknown;
  sourceTraceId?: string;
  sourceObservationId?: string;
}

Usage Examples:

// Create dataset item
const item = await client.datasetItems.create({
  datasetName: 'customer-support-eval',
  input: {
    message: 'How do I reset my password?'
  },
  expectedOutput: {
    response: 'Click on "Forgot Password" on the login page...',
    category: 'account'
  },
  metadata: {
    difficulty: 'easy',
    language: 'en'
  }
});

// Get a specific dataset item
const datasetItem = await client.datasetItems.get('item-456');

// List dataset items
const items = await client.datasetItems.list({
  datasetName: 'customer-support-eval',
  page: 1,
  limit: 50
});

// Delete dataset item
await client.datasetItems.delete('item-456');

Dataset Run Items Resource

Track individual test case executions within a dataset run.

interface DatasetRunItems {
  create(request: CreateDatasetRunItemRequest, options?: RequestOptions): Promise<DatasetRunItem>;
}

interface DatasetRunItem {
  id: string;
  datasetRunId: string;
  datasetItemId: string;
  traceId: string;
  observationId?: string;
  createdAt: string;
}

interface CreateDatasetRunItemRequest {
  datasetRunId: string;
  datasetItemId: string;
  traceId: string;
  observationId?: string;
}

Usage Examples:

// Create dataset run item (link trace to test case)
await client.datasetRunItems.create({
  datasetRunId: 'run-789',
  datasetItemId: 'item-456',
  traceId: 'trace-123',
  observationId: 'obs-abc'
});

Score Resource

Score creation for evaluation and feedback.

interface Score {
  create(request: CreateScoreRequest, options?: RequestOptions): Promise<CreateScoreResponse>;
}

interface CreateScoreRequest {
  name: string;
  value: CreateScoreValue;
  traceId: string;
  observationId?: string;
  comment?: string;
  dataType?: ScoreDataType;
  configId?: string;
}

type CreateScoreValue = number | string | boolean;

enum ScoreDataType {
  NUMERIC = "NUMERIC",
  CATEGORICAL = "CATEGORICAL",
  BOOLEAN = "BOOLEAN"
}

Usage Examples:

// Create numeric score
await client.score.create({
  name: 'accuracy',
  value: 0.95,
  dataType: 'NUMERIC',
  traceId: 'trace-123',
  comment: 'High accuracy response'
});

// Create boolean score
await client.score.create({
  name: 'hallucination',
  value: false,
  dataType: 'BOOLEAN',
  traceId: 'trace-123',
  observationId: 'obs-456'
});

// Create categorical score
await client.score.create({
  name: 'sentiment',
  value: 'positive',
  dataType: 'CATEGORICAL',
  traceId: 'trace-123'
});

Score V2 Resource

Query scores with detailed filtering and pagination.

interface ScoreV2 {
  list(request?: GetScoresRequest, options?: RequestOptions): Promise<GetScoresResponse>;
}

interface GetScoresResponse {
  data: GetScoresResponseData[];
  meta: MetaResponse;
}

type GetScoresResponseData =
  | GetScoresResponseDataNumeric
  | GetScoresResponseDataCategorical
  | GetScoresResponseDataBoolean;

Usage Examples:

// List scores for a trace
const scores = await client.scoreV2.list({
  traceId: 'trace-123'
});

// List scores by name
const accuracyScores = await client.scoreV2.list({
  name: 'accuracy',
  fromTimestamp: '2024-01-01T00:00:00Z'
});

Score Configs Resource

Score configuration and schema management.

interface ScoreConfigs {
  create(request: CreateScoreConfigRequest, options?: RequestOptions): Promise<ScoreConfig>;
  get(request?: GetScoreConfigsRequest, options?: RequestOptions): Promise<ScoreConfigs>;
  getById(configId: string, options?: RequestOptions): Promise<ScoreConfig>;
}

interface ScoreConfig {
  id: string;
  name: string;
  dataType: ScoreDataType;
  isArchived: boolean;
  categories?: ConfigCategory[];
  description?: string;
  minValue?: number;
  maxValue?: number;
}

interface CreateScoreConfigRequest {
  name: string;
  dataType: ScoreDataType;
  categories?: ConfigCategory[];
  description?: string;
  minValue?: number;
  maxValue?: number;
}

Usage Examples:

// Get all score configs
const configs = await client.scoreConfigs.get();

// Get a specific score config by ID
const config = await client.scoreConfigs.getById('config-id-123');

// Create numeric score config
await client.scoreConfigs.create({
  name: 'relevance',
  dataType: 'NUMERIC',
  minValue: 0,
  maxValue: 1,
  description: 'Response relevance score'
});

// Create categorical score config
await client.scoreConfigs.create({
  name: 'category',
  dataType: 'CATEGORICAL',
  categories: [
    { value: 'technical', label: 'Technical' },
    { value: 'billing', label: 'Billing' },
    { value: 'general', label: 'General' }
  ],
  description: 'Request category classification'
});

Platform Management Resources

Projects Resource

Project administration and API key management. Organization-scoped API keys required for create, update, delete, and API key management operations.

interface Projects {
  get(options?: RequestOptions): Promise<Projects>;
  create(request: CreateProjectRequest, options?: RequestOptions): Promise<Project>;
  update(projectId: string, request: UpdateProjectRequest, options?: RequestOptions): Promise<Project>;
  delete(projectId: string, options?: RequestOptions): Promise<ProjectDeletionResponse>;
  getApiKeys(projectId: string, options?: RequestOptions): Promise<ApiKeyList>;
  createApiKey(projectId: string, request?: CreateApiKeyRequest, options?: RequestOptions): Promise<ApiKeyResponse>;
  deleteApiKey(projectId: string, apiKeyId: string, options?: RequestOptions): Promise<ApiKeyDeletionResponse>;
}

interface Project {
  id: string;
  name: string;
  createdAt: string;
  updatedAt: string;
}

Usage Examples:

// Get project associated with API key
const projects = await client.projects.get();

// Create a new project (requires org-scoped API key)
const newProject = await client.projects.create({
  name: 'My New Project',
  retention: 30
});

// Update a project (requires org-scoped API key)
const updatedProject = await client.projects.update('project-123', {
  name: 'Updated Project Name',
  retention: 60
});

// Delete project (requires org-scoped API key)
await client.projects.delete('project-123');

// Get API keys for a project (requires org-scoped API key)
const apiKeys = await client.projects.getApiKeys('project-123');

// Create new API key (requires org-scoped API key)
const newApiKey = await client.projects.createApiKey('project-123', {
  note: 'Production API key'
});

// Delete API key (requires org-scoped API key)
await client.projects.deleteApiKey('project-123', 'api-key-id-456');

Organizations Resource

Multi-tenant organization management and membership. Requires organization-scoped API keys.

interface Organizations {
  getOrganizationMemberships(options?: RequestOptions): Promise<MembershipsResponse>;
  updateOrganizationMembership(request: MembershipRequest, options?: RequestOptions): Promise<MembershipResponse>;
  deleteOrganizationMembership(request: DeleteMembershipRequest, options?: RequestOptions): Promise<MembershipDeletionResponse>;
  getProjectMemberships(projectId: string, options?: RequestOptions): Promise<MembershipsResponse>;
  updateProjectMembership(projectId: string, request: MembershipRequest, options?: RequestOptions): Promise<MembershipResponse>;
  deleteProjectMembership(projectId: string, request: DeleteMembershipRequest, options?: RequestOptions): Promise<MembershipDeletionResponse>;
  getOrganizationProjects(options?: RequestOptions): Promise<OrganizationProjectsResponse>;
}

enum MembershipRole {
  OWNER = "OWNER",
  ADMIN = "ADMIN",
  MEMBER = "MEMBER",
  VIEWER = "VIEWER"
}

interface MembershipRequest {
  email: string;
  role: MembershipRole;
  organizationId: string;
}

Usage Examples:

// Get organization memberships
const orgMemberships = await client.organizations.getOrganizationMemberships();

// Update organization membership (create or update)
await client.organizations.updateOrganizationMembership({
  userId: 'user-456',
  role: 'ADMIN'
});

// Delete organization membership
await client.organizations.deleteOrganizationMembership({
  userId: 'user-456'
});

// Get project memberships
const projectMemberships = await client.organizations.getProjectMemberships('project-123');

// Update project membership
await client.organizations.updateProjectMembership('project-123', {
  userId: 'user-789',
  role: 'MEMBER'
});

// Delete project membership
await client.organizations.deleteProjectMembership('project-123', {
  userId: 'user-789'
});

// Get organization projects
const projects = await client.organizations.getOrganizationProjects();

Models Resource

Model configuration and pricing management.

interface Models {
  list(request?: ListModelsRequest, options?: RequestOptions): Promise<PaginatedModels>;
  create(request: CreateModelRequest, options?: RequestOptions): Promise<Model>;
}

interface Model {
  id: string;
  modelName: string;
  matchPattern: string;
  unit: ModelUsageUnit;
  inputPrice?: number;
  outputPrice?: number;
  totalPrice?: number;
  tokenizerId?: string;
  tokenizerConfig?: Record<string, unknown>;
}

enum ModelUsageUnit {
  TOKENS = "TOKENS",
  CHARACTERS = "CHARACTERS",
  SECONDS = "SECONDS",
  IMAGES = "IMAGES"
}

interface CreateModelRequest {
  modelName: string;
  matchPattern: string;
  unit: ModelUsageUnit;
  inputPrice?: number;
  outputPrice?: number;
  totalPrice?: number;
  tokenizerId?: string;
  tokenizerConfig?: Record<string, unknown>;
}

Usage Examples:

// List models
const models = await client.models.list({
  page: 1,
  limit: 50
});

// Create model configuration
await client.models.create({
  modelName: 'gpt-4-turbo',
  matchPattern: 'gpt-4-turbo*',
  unit: 'TOKENS',
  inputPrice: 0.00001,   // $0.01 per 1k tokens
  outputPrice: 0.00003   // $0.03 per 1k tokens
});

Media Resource

Media upload and retrieval for rich content.

interface Media {
  get(mediaId: string, options?: RequestOptions): Promise<GetMediaResponse>;
  getUploadUrl(request: GetMediaUploadUrlRequest, options?: RequestOptions): Promise<GetMediaUploadUrlResponse>;
  patch(mediaId: string, body: PatchMediaBody, options?: RequestOptions): Promise<void>;
}

interface GetMediaResponse {
  mediaId: string;
  contentType: MediaContentType;
  contentLength: number;
  uploadedAt: string;
}

interface GetMediaUploadUrlRequest {
  traceId: string;
  observationId?: string;
  contentType: MediaContentType;
  contentLength: number;
  sha256Hash: string;
  field: string;
}

interface GetMediaUploadUrlResponse {
  mediaId: string;
  uploadUrl: string;
}

Usage Examples:

// Get media info
const media = await client.media.get('media-123');

// Get upload URL
const { mediaId, uploadUrl } = await client.media.getUploadUrl({
  contentType: 'image/png',
  contentLength: 102400,
  sha256Hash: 'abc123...'
});

// Upload to URL (using fetch)
await fetch(uploadUrl, {
  method: 'PUT',
  headers: { 'Content-Type': 'image/png' },
  body: imageBytes
});

Additional Resources

Health Resource

Health check endpoint for monitoring.

interface Health {
  health(options?: RequestOptions): Promise<HealthResponse>;
}

interface HealthResponse {
  status: string;
  version: string;
}

Usage Examples:

// Check API health
const health = await client.health.health();
console.log(`Status: ${health.status}, Version: ${health.version}`);

Metrics Resource

Analytics and metrics queries.

interface Metrics {
  metrics(request: GetMetricsRequest, options?: RequestOptions): Promise<MetricsResponse>;
}

Usage Examples:

// Get metrics
const metrics = await client.metrics.metrics({
  query: 'traces-count'
});

Comments Resource

Comment management for traces and observations.

interface Comments {
  create(request: CreateCommentRequest, options?: RequestOptions): Promise<CreateCommentResponse>;
  get(request?: GetCommentsRequest, options?: RequestOptions): Promise<GetCommentsResponse>;
}

interface CreateCommentRequest {
  projectId: string;
  objectType: CommentObjectType;
  objectId: string;
  content: string;
  authorUserId?: string;
}

interface CreateCommentResponse {
  id: string;
}

interface GetCommentsRequest {
  projectId?: string;
  objectType?: string;
  objectId?: string;
  authorUserId?: string;
}

interface GetCommentsResponse {
  data: Comment[];
  meta: MetaResponse;
}

interface Comment {
  id: string;
  projectId: string;
  objectType: string;
  objectId: string;
  content: string;
  authorUserId?: string;
  createdAt: string;
  updatedAt: string;
}

enum CommentObjectType {
  TRACE = "TRACE",
  OBSERVATION = "OBSERVATION"
}

Usage Examples:

// Create comment on trace
await client.comments.create({
  projectId: 'project-123',
  objectType: 'TRACE',
  objectId: 'trace-123',
  content: 'This trace shows an interesting edge case'
});

// Get comments with filtering
const comments = await client.comments.get({
  projectId: 'project-123',
  objectType: 'TRACE',
  objectId: 'trace-123'
});

// Get all comments for a project
const allComments = await client.comments.get({
  projectId: 'project-123'
});

Annotation Queues Resource

Annotation workflow management for human review.

interface AnnotationQueues {
  listQueues(request?: GetAnnotationQueuesRequest, options?: RequestOptions): Promise<PaginatedAnnotationQueues>;
  createQueue(request: CreateAnnotationQueueRequest, options?: RequestOptions): Promise<AnnotationQueue>;
  getQueue(queueId: string, options?: RequestOptions): Promise<AnnotationQueue>;
  listQueueItems(queueId: string, request?: GetAnnotationQueueItemsRequest, options?: RequestOptions): Promise<PaginatedAnnotationQueueItems>;
  getQueueItem(queueId: string, itemId: string, options?: RequestOptions): Promise<AnnotationQueueItem>;
  createQueueItem(queueId: string, request: CreateAnnotationQueueItemRequest, options?: RequestOptions): Promise<AnnotationQueueItem>;
  updateQueueItem(queueId: string, itemId: string, request: UpdateAnnotationQueueItemRequest, options?: RequestOptions): Promise<AnnotationQueueItem>;
  deleteQueueItem(queueId: string, itemId: string, options?: RequestOptions): Promise<void>;
  createQueueAssignment(queueId: string, request: AnnotationQueueAssignmentRequest, options?: RequestOptions): Promise<AnnotationQueueAssignment>;
  deleteQueueAssignment(queueId: string, request: AnnotationQueueAssignmentRequest, options?: RequestOptions): Promise<void>;
}

interface GetAnnotationQueuesRequest {
  page?: number;
  limit?: number;
}

interface CreateAnnotationQueueRequest {
  name: string;
  description?: string;
  scoreConfigIds: string[];
}

interface GetAnnotationQueueItemsRequest {
  page?: number;
  limit?: number;
}

interface CreateAnnotationQueueItemRequest {
  objectId: string;
  objectType: string;
}

interface UpdateAnnotationQueueItemRequest {
  status?: string;
  assignedTo?: string;
}

interface AnnotationQueueAssignmentRequest {
  userId: string;
}

interface AnnotationQueue {
  id: string;
  name: string;
  description?: string;
  projectId: string;
  scoreConfigIds: string[];
  createdAt: string;
  updatedAt: string;
}

interface AnnotationQueueItem {
  id: string;
  queueId: string;
  objectId: string;
  objectType: string;
  status?: string;
  assignedTo?: string;
  createdAt: string;
  updatedAt: string;
}

interface AnnotationQueueAssignment {
  queueId: string;
  userId: string;
  createdAt: string;
}

interface PaginatedAnnotationQueues {
  data: AnnotationQueue[];
  meta: MetaResponse;
}

interface PaginatedAnnotationQueueItems {
  data: AnnotationQueueItem[];
  meta: MetaResponse;
}

Usage Examples:

// List all annotation queues
const queues = await client.annotationQueues.listQueues({
  page: 1,
  limit: 50
});

// Create annotation queue
const queue = await client.annotationQueues.createQueue({
  name: 'Manual Review',
  description: 'Traces requiring manual review',
  scoreConfigIds: ['score-config-1', 'score-config-2']
});

// Get a specific queue
const queue = await client.annotationQueues.getQueue('queue-123');

// List items in a queue
const items = await client.annotationQueues.listQueueItems('queue-123', {
  page: 1,
  limit: 50
});

// Get a specific queue item
const item = await client.annotationQueues.getQueueItem('queue-123', 'item-456');

// Add an item to a queue
await client.annotationQueues.createQueueItem('queue-123', {
  objectId: 'trace-789',
  objectType: 'TRACE'
});

// Update a queue item
await client.annotationQueues.updateQueueItem('queue-123', 'item-456', {
  status: 'IN_PROGRESS',
  assignedTo: 'user-123'
});

// Remove an item from a queue
await client.annotationQueues.deleteQueueItem('queue-123', 'item-456');

// Create queue assignment
await client.annotationQueues.createQueueAssignment('queue-123', {
  userId: 'user-456'
});

// Delete queue assignment
await client.annotationQueues.deleteQueueAssignment('queue-123', {
  userId: 'user-456'
});

LLM Connections Resource

LLM integration configuration management.

interface LlmConnections {
  list(request?: GetLlmConnectionsRequest, options?: RequestOptions): Promise<PaginatedLlmConnections>;
  upsert(request: UpsertLlmConnectionRequest, options?: RequestOptions): Promise<LlmConnection>;
}

interface GetLlmConnectionsRequest {
  page?: number;
  limit?: number;
}

interface UpsertLlmConnectionRequest {
  provider: string;
  adapter: "anthropic" | "openai" | "azure";
  secretKey: string;
  baseURL?: string;
  customModels?: LlmConnectionModel[];
  withDefaultModels?: boolean;
  extraHeaders?: Record<string, string>;
}

interface LlmConnectionModel {
  id: string;
  modelName: string;
  inputPrice?: number;
  outputPrice?: number;
}

interface LlmConnection {
  id: string;
  provider: string;
  adapter: string;
  baseURL?: string;
  customModels?: LlmConnectionModel[];
  withDefaultModels?: boolean;
  createdAt: string;
  updatedAt: string;
}

interface PaginatedLlmConnections {
  data: LlmConnection[];
  meta: MetaResponse;
}

Usage Examples:

// List LLM connections
const connections = await client.llmConnections.list({
  page: 1,
  limit: 50
});

// Create/update OpenAI connection
await client.llmConnections.upsert({
  provider: 'openai-production',
  adapter: 'openai',
  secretKey: process.env.OPENAI_API_KEY,
  withDefaultModels: true
});

// Create/update Anthropic connection with custom models
await client.llmConnections.upsert({
  provider: 'anthropic-production',
  adapter: 'anthropic',
  secretKey: process.env.ANTHROPIC_API_KEY,
  customModels: [
    {
      id: 'custom-claude',
      modelName: 'claude-3-5-sonnet-20241022',
      inputPrice: 0.000003,
      outputPrice: 0.000015
    }
  ]
});

// Create/update Azure OpenAI connection
await client.llmConnections.upsert({
  provider: 'azure-production',
  adapter: 'azure',
  secretKey: process.env.AZURE_API_KEY,
  baseURL: 'https://my-resource.openai.azure.com',
  extraHeaders: {
    'api-version': '2024-02-15-preview'
  }
});

Blob Storage Integrations Resource

Blob storage configuration for data export.

interface BlobStorageIntegrations {
  getBlobStorageIntegrations(options?: RequestOptions): Promise<BlobStorageIntegrationsResponse>;
  upsertBlobStorageIntegration(request: CreateBlobStorageIntegrationRequest, options?: RequestOptions): Promise<BlobStorageIntegrationResponse>;
  deleteBlobStorageIntegration(id: string, options?: RequestOptions): Promise<void>;
}

interface CreateBlobStorageIntegrationRequest {
  projectId: string;
  type: "S3";
  bucketName: string;
  endpoint?: string;
  region: string;
  accessKeyId?: string;
  secretAccessKey?: string;
  prefix?: string;
  exportFrequency: "hourly" | "daily";
  enabled: boolean;
  forcePathStyle: boolean;
  fileType: "JSON";
  exportMode: "FULL_HISTORY" | "INCREMENTAL";
  exportStartDate?: string;
}

interface BlobStorageIntegrationResponse {
  id: string;
  projectId: string;
  type: string;
  bucketName: string;
  region: string;
  prefix?: string;
  exportFrequency: string;
  enabled: boolean;
  fileType: string;
  exportMode: string;
  createdAt: string;
  updatedAt: string;
}

interface BlobStorageIntegrationsResponse {
  data: BlobStorageIntegrationResponse[];
}

Usage Examples:

// List all blob storage integrations
const integrations = await client.blobStorageIntegrations.getBlobStorageIntegrations();

// Create or update S3 integration with full history export
await client.blobStorageIntegrations.upsertBlobStorageIntegration({
  projectId: 'project-123',
  type: 'S3',
  bucketName: 'langfuse-exports',
  region: 'us-east-1',
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  prefix: 'production/',
  exportFrequency: 'daily',
  enabled: true,
  forcePathStyle: false,
  fileType: 'JSON',
  exportMode: 'FULL_HISTORY'
});

// Create or update S3 integration with incremental export
await client.blobStorageIntegrations.upsertBlobStorageIntegration({
  projectId: 'project-123',
  type: 'S3',
  bucketName: 'langfuse-incremental',
  region: 'eu-west-1',
  exportFrequency: 'hourly',
  enabled: true,
  forcePathStyle: false,
  fileType: 'JSON',
  exportMode: 'INCREMENTAL',
  exportStartDate: '2024-01-01T00:00:00Z'
});

// Create S3-compatible integration (e.g., MinIO)
await client.blobStorageIntegrations.upsertBlobStorageIntegration({
  projectId: 'project-123',
  type: 'S3',
  bucketName: 'my-bucket',
  endpoint: 'https://minio.example.com',
  region: 'us-east-1',
  accessKeyId: 'minioadmin',
  secretAccessKey: 'minioadmin',
  exportFrequency: 'daily',
  enabled: true,
  forcePathStyle: true,
  fileType: 'JSON',
  exportMode: 'FULL_HISTORY'
});

// Delete blob storage integration
await client.blobStorageIntegrations.deleteBlobStorageIntegration('integration-id-123');

SCIM Resource

SCIM (System for Cross-domain Identity Management) endpoints for identity management.

interface Scim {
  getServiceProviderConfig(options?: RequestOptions): Promise<ServiceProviderConfig>;
  listUsers(request?: ListUsersRequest, options?: RequestOptions): Promise<ScimUsersListResponse>;
}

Usage Examples:

// Get SCIM configuration
const config = await client.scim.getServiceProviderConfig();

// List SCIM users
const users = await client.scim.listUsers();

Ingestion Resource (Legacy)

Legacy batch ingestion endpoint for high-volume data ingestion.

Note: The OpenTelemetry endpoint (/api/public/otel) is preferred over this legacy endpoint.

interface Ingestion {
  batch(request: IngestionRequest, options?: RequestOptions): Promise<IngestionResponse>;
}

interface IngestionRequest {
  batch: IngestionEvent[];
  metadata?: Record<string, unknown>;
}

type IngestionEvent =
  | TraceEvent
  | CreateObservationEvent
  | UpdateObservationEvent
  | CreateGenerationEvent
  | UpdateGenerationEvent
  | CreateSpanEvent
  | UpdateSpanEvent
  | CreateEventEvent
  | ScoreEvent
  | SdkLogEvent;

interface IngestionResponse {
  successes: IngestionSuccess[];
  errors: IngestionError[];
}

Usage Examples:

// Batch ingest events (legacy)
const response = await client.ingestion.batch({
  batch: [
    {
      type: 'trace-create',
      id: 'event-1',
      timestamp: '2024-01-01T00:00:00Z',
      body: {
        id: 'trace-1',
        name: 'Chat Request',
        userId: 'user-123',
        input: { message: 'Hello' },
        output: { response: 'Hi there!' }
      }
    },
    {
      type: 'generation-create',
      id: 'event-2',
      timestamp: '2024-01-01T00:00:01Z',
      body: {
        id: 'gen-1',
        traceId: 'trace-1',
        name: 'OpenAI Call',
        model: 'gpt-4',
        input: { messages: [{ role: 'user', content: 'Hello' }] },
        output: { message: { role: 'assistant', content: 'Hi there!' } },
        usageDetails: {
          promptTokens: 10,
          completionTokens: 5,
          totalTokens: 15
        }
      }
    }
  ]
});

console.log(`Successes: ${response.successes.length}`);
console.log(`Errors: ${response.errors.length}`);

Common Types

Pagination

interface MetaResponse {
  page: number;
  limit: number;
  totalItems: number;
  totalPages: number;
}

Usage and Cost (Deprecated)

Note: Prefer usageDetails and costDetails for new implementations.

interface Usage {
  input?: number;
  output?: number;
  total?: number;
  unit?: ModelUsageUnit;
  inputCost?: number;
  outputCost?: number;
  totalCost?: number;
}

Best Practices

  1. Pagination: Always implement pagination for list operations
  2. Field Selection: Use fields parameter on traces to reduce payload
  3. Filtering: Apply filters at the API level rather than in application code
  4. Batch Operations: Use batch ingestion for high-volume scenarios
  5. Error Handling: Catch and handle specific error types for each operation
  6. Resource Cleanup: Delete unused traces and datasets to manage storage
  7. Prompt Versioning: Use labels for environment promotion (dev → staging → production)
  8. Score Configs: Define score configurations before creating scores
  9. Media Upload: Use media upload URLs rather than inline base64 for large files
  10. OpenTelemetry: Prefer OpenTelemetry endpoint over legacy batch ingestion

Install with Tessl CLI

npx tessl i tessl/npm-langfuse--core

docs

api-client.md

api-resources.md

constants.md

errors.md

index.md

logger.md

media.md

utils.md

tile.json