Tracing Langfuse API Reference
Complete type definitions for @helix-agents/tracing-langfuse.
Installation
bash
npm install @helix-agents/tracing-langfuse langfuseFunctions
createLangfuseHooks
Creates Langfuse tracing hooks for use with Helix Agents.
typescript
function createLangfuseHooks<TState = unknown, TOutput = unknown>(
options?: LangfuseHooksOptions
): LangfuseHooksResult<TState, TOutput>;Parameters:
options- Configuration options (optional, uses env vars if not provided)
Returns: LangfuseHooksResult containing hooks and utility methods
Example:
typescript
import { createLangfuseHooks } from '@helix-agents/tracing-langfuse';
// Basic usage (reads from env vars)
const { hooks, flush, shutdown } = createLangfuseHooks();
// With configuration
const { hooks } = createLangfuseHooks({
publicKey: 'pk-lf-...',
secretKey: 'sk-lf-...',
release: '1.0.0',
defaultTags: ['production'],
});tracingContext
Creates a fluent builder for execution context with tracing metadata.
typescript
function tracingContext(): TracingContextBuilder;Returns: TracingContextBuilder instance
Example:
typescript
import { tracingContext } from '@helix-agents/tracing-langfuse';
const context = tracingContext()
.user('user-123')
.session('session-456')
.tags('premium')
.environment('production')
.build();
await executor.execute(agent, input, context);createTracingMetadata
Creates typed metadata for tracing, filtering out undefined values.
typescript
function createTracingMetadata(metadata: TracingMetadata): Record<string, string>;Parameters:
metadata- Object with typed metadata fields
Returns: Clean Record<string, string> with no undefined values
Example:
typescript
import { createTracingMetadata } from '@helix-agents/tracing-langfuse';
const metadata = createTracingMetadata({
environment: 'production',
version: '1.0.0',
region: 'us-west-2',
tier: undefined, // Will be filtered out
});
// Result: { environment: 'production', version: '1.0.0', region: 'us-west-2' }Types
LangfuseHooksResult
Result returned by createLangfuseHooks().
typescript
interface LangfuseHooksResult<TState = unknown, TOutput = unknown> {
/** Agent hooks to pass to defineAgent */
hooks: AgentHooks<TState, TOutput>;
/** Flush all pending observations to Langfuse */
flush: () => Promise<void>;
/** Shutdown the client and flush pending observations */
shutdown: () => Promise<void>;
}LangfuseHooksOptions
Configuration options for createLangfuseHooks().
typescript
interface LangfuseHooksOptions {
// ---------------------------------------------------------------------------
// Core Configuration
// ---------------------------------------------------------------------------
/**
* Langfuse public key.
* If not provided, reads from LANGFUSE_PUBLIC_KEY env var.
*/
publicKey?: string;
/**
* Langfuse secret key.
* If not provided, reads from LANGFUSE_SECRET_KEY env var.
*/
secretKey?: string;
/**
* Langfuse base URL.
* @default "https://cloud.langfuse.com"
*/
baseUrl?: string;
// ---------------------------------------------------------------------------
// Data Capture Options
// ---------------------------------------------------------------------------
/**
* Include agent state snapshots in observations.
* Warning: State may be large and contain sensitive data.
* @default false
*/
includeState?: boolean;
/**
* Include message content in observations.
* Warning: Messages may contain sensitive user data.
* @default false
*/
includeMessages?: boolean;
/**
* Include tool arguments in observations.
* @default true
*/
includeToolArgs?: boolean;
/**
* Include tool results in observations.
* Warning: Results may be large.
* @default false
*/
includeToolResults?: boolean;
/**
* Include LLM input (messages) in generation observations.
* Required for seeing prompts in Langfuse UI.
* @default true
*/
includeGenerationInput?: boolean;
/**
* Include LLM output in generation observations.
* Required for seeing responses in Langfuse UI.
* @default true
*/
includeGenerationOutput?: boolean;
// ---------------------------------------------------------------------------
// Trace Metadata Defaults
// ---------------------------------------------------------------------------
/**
* Default release/version tag for all traces.
*/
release?: string;
/**
* Default tags applied to all traces.
* Merged with per-execution tags from ExecuteOptions.
*/
defaultTags?: string[];
/**
* Default metadata applied to all traces.
* Merged with per-execution metadata from ExecuteOptions.
*/
defaultMetadata?: Record<string, unknown>;
// ---------------------------------------------------------------------------
// Lifecycle Hooks
// ---------------------------------------------------------------------------
/**
* Called when an agent trace is created.
*/
onAgentTraceCreated?: (params: AgentTraceCreatedParams) => void | Promise<void>;
/**
* Called when a generation observation is created.
*/
onGenerationCreated?: (params: GenerationCreatedParams) => void | Promise<void>;
/**
* Called when a tool observation is created.
*/
onToolCreated?: (params: ToolCreatedParams) => void | Promise<void>;
/**
* Called when any observation is about to be ended.
*/
onObservationEnding?: (params: ObservationEndingParams) => void | Promise<void>;
/**
* Custom attribute extractor called for each hook invocation.
*/
extractAttributes?: (
context: HookContext
) => Record<string, string | number | boolean> | undefined;
/**
* Enable debug logging.
* @default false
*/
debug?: boolean;
}TracingMetadata
Common metadata fields with type safety.
typescript
interface TracingMetadata {
/** Application environment (e.g., 'production', 'staging', 'development') */
environment?: string;
/** Application version or release tag */
version?: string;
/** Service or component name */
service?: string;
/** Geographic region */
region?: string;
/** User tier or subscription level */
tier?: string;
/** Feature flags active for this execution */
features?: string;
/** Request source (e.g., 'web', 'mobile', 'api') */
source?: string;
/** Allow additional custom fields */
[key: string]: string | undefined;
}TracingContextBuilder
Fluent builder for creating execution context.
typescript
class TracingContextBuilder {
/** Set user ID for attribution */
user(userId: string): this;
/** Set session ID for conversation grouping */
session(sessionId: string): this;
/** Add tags for filtering */
tags(...tags: string[]): this;
/** Set environment metadata */
environment(env: 'production' | 'staging' | 'development'): this;
/** Set version metadata */
version(version: string): this;
/** Set custom metadata (key-value or object) */
metadata(key: string, value: string): this;
metadata(obj: TracingMetadata): this;
/** Build the execution options */
build(): Pick<ExecuteOptions, 'userId' | 'sessionId' | 'tags' | 'metadata'>;
}Lifecycle Hook Parameters
AgentTraceCreatedParams
typescript
interface AgentTraceCreatedParams {
/** Run ID */
runId: string;
/** Agent name */
agentName: string;
/** Session ID if provided */
sessionId?: string;
/** User ID if provided */
userId?: string;
/** Tags from options merged with defaults */
tags: string[];
/** Metadata from options merged with defaults */
metadata: Record<string, unknown>;
/** Hook context */
hookContext: HookContext;
/** Update the trace with additional attributes */
updateTrace: (updates: TraceUpdateParams) => void;
}GenerationCreatedParams
typescript
interface GenerationCreatedParams {
/** Generation observation ID */
observationId: string;
/** Model identifier */
model?: string;
/** Model parameters */
modelParameters?: Record<string, unknown>;
/** Input messages if includeGenerationInput is true */
input?: unknown;
/** Hook context */
hookContext: HookContext;
/** Update the generation with additional attributes */
updateGeneration: (updates: GenerationUpdateParams) => void;
}ToolCreatedParams
typescript
interface ToolCreatedParams {
/** Tool observation ID */
observationId: string;
/** Tool name */
toolName: string;
/** Tool call ID */
toolCallId: string;
/** Tool arguments if includeToolArgs is true */
arguments?: unknown;
/** Hook context */
hookContext: HookContext;
/** Update the tool observation with additional attributes */
updateTool: (updates: ToolUpdateParams) => void;
}ObservationEndingParams
typescript
interface ObservationEndingParams {
/** Observation type */
type: 'agent' | 'generation' | 'tool' | 'span';
/** Observation ID */
observationId: string;
/** Duration in milliseconds */
durationMs: number;
/** Whether the observation succeeded */
success: boolean;
/** Error if failed */
error?: Error;
/** Hook context */
hookContext: HookContext;
}Update Parameter Types
TraceUpdateParams
typescript
interface TraceUpdateParams {
/** User ID for the trace */
userId?: string;
/** Session ID for grouping traces */
sessionId?: string;
/** Tags for filtering */
tags?: string[];
/** Additional metadata */
metadata?: Record<string, unknown>;
/** Release/version identifier */
release?: string;
}GenerationUpdateParams
typescript
interface GenerationUpdateParams {
/** Model identifier */
model?: string;
/** Model parameters */
modelParameters?: LangfuseModelParametersType;
/** Additional metadata */
metadata?: unknown;
}ToolUpdateParams
typescript
interface ToolUpdateParams {
/** Additional metadata */
metadata?: Record<string, unknown>;
}LangfuseObservationType
typescript
type LangfuseObservationType = 'agent' | 'generation' | 'tool' | 'span';Environment Variables
| Variable | Description | Required |
|---|---|---|
LANGFUSE_PUBLIC_KEY | Langfuse public key | Yes (or pass in options) |
LANGFUSE_SECRET_KEY | Langfuse secret key | Yes (or pass in options) |
LANGFUSE_BASEURL | Langfuse API URL | No (defaults to cloud.langfuse.com) |
See Also
- Tracing Guide - Getting started with tracing
- Hooks API Reference - Core hooks system
- Langfuse Documentation - Langfuse platform docs