CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-langfuse--client

Langfuse API client for universal JavaScript environments providing observability, prompt management, datasets, experiments, and scoring capabilities

Moderation error
Malicious code detected in tile.json: This tile.json exhibits signs of a supply chain attack through typosquatting/dependency confusion. The package name 'tessl/npm-langfuse--client' (with double hyphen) mimics the legitimate '@langfuse/client' package. The 'describes' field references the real package 'pkg:npm/%40langfuse/client@4.2.0' but the tile name uses a different format with 'npm-langfuse--client', suggesting an attempt to intercept or impersonate the legitimate Langfuse client package. This pattern is consistent with dependency confusion attacks where malicious packages use similar names to legitimate ones.
Overview
Eval results
Files

client.mddocs/

Client Initialization

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

Capabilities

Create Client Instance

Initialize a LangfuseClient with credentials and configuration.

/**
 * Creates a new Langfuse client instance
 * @param params - Optional configuration parameters
 */
function LangfuseClient(params?: LangfuseClientParams): LangfuseClient;

interface LangfuseClientParams {
  /** Public API key (or use LANGFUSE_PUBLIC_KEY env var) */
  publicKey?: string;
  /** Secret API key (or use LANGFUSE_SECRET_KEY env var) */
  secretKey?: string;
  /** Langfuse instance URL (default: "https://cloud.langfuse.com") */
  baseUrl?: string;
  /** Request timeout in seconds (default: 5) */
  timeout?: number;
  /** Additional HTTP headers to include with requests */
  additionalHeaders?: Record<string, string>;
}

Usage Examples:

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

// Initialize with explicit credentials
const langfuse = new LangfuseClient({
  publicKey: 'pk_...',
  secretKey: 'sk_...',
  baseUrl: 'https://cloud.langfuse.com'
});

// Initialize using environment variables
// LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, LANGFUSE_BASE_URL
const langfuse = new LangfuseClient();

// With custom timeout and headers
const langfuse = new LangfuseClient({
  publicKey: 'pk_...',
  secretKey: 'sk_...',
  timeout: 10,
  additionalHeaders: {
    'X-Custom-Header': 'value'
  }
});

// Self-hosted instance
const langfuse = new LangfuseClient({
  publicKey: 'pk_...',
  secretKey: 'sk_...',
  baseUrl: 'https://langfuse.example.com'
});

Access Managers

The client provides access to specialized managers for different capabilities.

class LangfuseClient {
  /** Direct access to Langfuse API client for advanced operations */
  readonly api: LangfuseAPIClient;

  /** Manager for prompt operations (fetch, create, update, caching) */
  readonly prompt: PromptManager;

  /** Manager for dataset operations (fetch datasets with items) */
  readonly dataset: DatasetManager;

  /** Manager for score operations (create, batch, flush) */
  readonly score: ScoreManager;

  /** Manager for media operations (resolve media references) */
  readonly media: MediaManager;

  /** Manager for experiment execution and evaluation */
  readonly experiment: ExperimentManager;
}

Usage Examples:

const langfuse = new LangfuseClient();

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

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

// Use score manager
langfuse.score.create({
  name: 'quality',
  value: 0.85,
  traceId: 'trace-123'
});

// Use media manager
const resolved = await langfuse.media.resolveReferences({
  obj: myObject,
  resolveWith: 'base64DataUri'
});

// Use experiment manager
const result = await langfuse.experiment.run({
  name: 'Evaluation',
  data: items,
  task: myTask,
  evaluators: [myEvaluator]
});

// Use API client directly for advanced operations
const traces = await langfuse.api.trace.list({ limit: 10 });
const observations = await langfuse.api.observations.getMany({ limit: 20 });

Flush Pending Data

Ensure all queued scores are sent to the API immediately.

/**
 * Flushes all pending score events to the Langfuse API
 * @returns Promise that resolves when all pending scores have been sent
 */
flush(): Promise<void>;

Usage Examples:

const langfuse = new LangfuseClient();

// Create some scores (queued automatically)
langfuse.score.create({ name: 'quality', value: 0.8, traceId: 'abc' });
langfuse.score.create({ name: 'latency', value: 120, traceId: 'abc' });

// Force immediate send
await langfuse.flush();

// Before application exit
async function cleanup() {
  await langfuse.flush();
  process.exit(0);
}

Graceful Shutdown

Shut down the client gracefully by flushing all pending data.

/**
 * Gracefully shuts down the client by flushing all pending data
 * @returns Promise that resolves when shutdown is complete
 */
shutdown(): Promise<void>;

Usage Examples:

const langfuse = new LangfuseClient();

// ... use the client ...

// Before application exit, ensure all data is sent
await langfuse.shutdown();

// In an Express.js app
process.on('SIGTERM', async () => {
  console.log('SIGTERM received, shutting down gracefully');
  await langfuse.shutdown();
  process.exit(0);
});

// In a Next.js API route
export default async function handler(req, res) {
  const langfuse = new LangfuseClient();

  // ... handle request ...

  // Flush before response
  await langfuse.shutdown();
  res.status(200).json({ success: true });
}

Generate Trace URL

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

/**
 * Generates a URL to view a trace in the Langfuse UI
 * @param traceId - The ID of the trace
 * @returns Promise resolving to the trace URL
 */
getTraceUrl(traceId: string): Promise<string>;

Usage Examples:

const langfuse = new LangfuseClient();

// Generate URL for a specific trace
const traceId = 'trace-abc-123';
const url = await langfuse.getTraceUrl(traceId);
console.log(`View trace at: ${url}`);
// Output: View trace at: https://cloud.langfuse.com/project/proj-123/traces/trace-abc-123

// After running an experiment
const result = await langfuse.experiment.run({
  name: 'Model Test',
  data: items,
  task: myTask
});

// Get URLs for all experiment traces
for (const itemResult of result.itemResults) {
  if (itemResult.traceId) {
    const traceUrl = await langfuse.getTraceUrl(itemResult.traceId);
    console.log(`Item trace: ${traceUrl}`);
  }
}

// In error logging
try {
  await riskyOperation(traceId);
} catch (error) {
  const traceUrl = await langfuse.getTraceUrl(traceId);
  console.error(`Operation failed. Debug at: ${traceUrl}`);
  throw error;
}

Configuration

Environment Variables

The client can be configured using environment variables:

VariableDescriptionDefault
LANGFUSE_PUBLIC_KEYPublic API keyRequired if not in constructor
LANGFUSE_SECRET_KEYSecret API keyRequired if not in constructor
LANGFUSE_BASE_URLLangfuse instance URLhttps://cloud.langfuse.com
LANGFUSE_BASEURLLegacy alias for BASE_URLDeprecated, use BASE_URL
LANGFUSE_TIMEOUTRequest timeout (seconds)5

Usage Example:

# .env file
LANGFUSE_PUBLIC_KEY=pk_...
LANGFUSE_SECRET_KEY=sk_...
LANGFUSE_BASE_URL=https://cloud.langfuse.com
LANGFUSE_TIMEOUT=10
// Client will use environment variables
const langfuse = new LangfuseClient();

Constructor Parameters vs Environment Variables

Constructor parameters take precedence over environment variables:

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

const langfuse = new LangfuseClient({
  publicKey: 'pk_...',
  secretKey: 'sk_...',
  baseUrl: 'https://custom.langfuse.com'  // Overrides env var
});
// Uses https://custom.langfuse.com

Error Handling

Missing Credentials

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

const langfuse = new LangfuseClient();
// Logs warnings:
// "No public key provided in constructor or as LANGFUSE_PUBLIC_KEY env var..."
// "No secret key provided in constructor or as LANGFUSE_SECRET_KEY env var..."
// Client operations will fail until credentials are available

Network Errors

API operations may throw errors on network failures:

const langfuse = new LangfuseClient({
  publicKey: 'pk_...',
  secretKey: 'sk_...',
  timeout: 1  // Very short timeout
});

try {
  const prompt = await langfuse.prompt.get('my-prompt');
} catch (error) {
  console.error('Failed to fetch prompt:', error.message);
  // Handle timeout or network error
}

Advanced Usage

Direct API Access

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

const langfuse = new LangfuseClient();

// Access raw API endpoints
const projects = await langfuse.api.projects.get();
const traces = await langfuse.api.trace.list({ limit: 100 });
const trace = await langfuse.api.trace.get('trace-id');
const observations = await langfuse.api.observations.getMany({
  traceId: 'trace-id',
  limit: 50
});
const sessions = await langfuse.api.sessions.get({ limit: 20 });

// Dataset operations
const datasets = await langfuse.api.datasets.list();
const dataset = await langfuse.api.datasets.create({
  name: 'new-dataset',
  description: 'My dataset'
});
const run = await langfuse.api.datasets.getRun('dataset-name', 'run-id');
const runs = await langfuse.api.datasets.getRuns('dataset-name');

// Dataset items
const items = await langfuse.api.datasetItems.list({ datasetName: 'my-dataset' });
const item = await langfuse.api.datasetItems.get('item-id');
const newItem = await langfuse.api.datasetItems.create({
  datasetName: 'my-dataset',
  input: { question: 'What is AI?' },
  expectedOutput: 'AI is...'
});

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

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

Multiple Client Instances

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

const prodClient = new LangfuseClient({
  publicKey: 'pk_prod_...',
  secretKey: 'sk_prod_...',
  baseUrl: 'https://cloud.langfuse.com'
});

const devClient = new LangfuseClient({
  publicKey: 'pk_dev_...',
  secretKey: 'sk_dev_...',
  baseUrl: 'https://dev.langfuse.com'
});

// Use different clients for different purposes
const prodPrompt = await prodClient.prompt.get('production-prompt');
const devPrompt = await devClient.prompt.get('experimental-prompt');

TypeScript Support

The package provides full TypeScript support with detailed type definitions:

import type {
  LangfuseClient,
  LangfuseClientParams,
  TextPromptClient,
  ChatPromptClient,
  FetchedDataset,
  ExperimentResult,
  Evaluation
} from '@langfuse/client';

// Type-safe configuration
const config: LangfuseClientParams = {
  publicKey: process.env.LANGFUSE_PUBLIC_KEY,
  secretKey: process.env.LANGFUSE_SECRET_KEY,
  baseUrl: 'https://cloud.langfuse.com',
  timeout: 10
};

const langfuse = new LangfuseClient(config);

// Type inference works automatically
const prompt = await langfuse.prompt.get('my-prompt', { type: 'text' });
// prompt is inferred as TextPromptClient

const chatPrompt = await langfuse.prompt.get('chat-prompt', { type: 'chat' });
// chatPrompt is inferred as ChatPromptClient

Install with Tessl CLI

npx tessl i tessl/npm-langfuse--client

docs

autoevals-adapter.md

client.md

datasets.md

experiments.md

index.md

media.md

prompts.md

scores.md

tile.json