Setup
setupObservability()
Initializes the LangWatch observability system for Node.js environments, enabling data collection and tracing for your LLM application. This is typically the first function you’ll call when integrating LangWatch.
SetupObservabilityOptions
default:"{}"
Configuration options for the LangWatch observability system.
ObservabilityHandle
An object containing a
shutdown() method for graceful cleanup.SetupObservabilityOptions
Configuration options for setting up LangWatch observability.
Optional<LangWatchConfig | 'disabled'>
LangWatch configuration. Set to ‘disabled’ to completely disable LangWatch integration.
Optional<string>
Name of the service being instrumented.
Optional<SemConvAttributes>
Global attributes added to all telemetry data.
Optional<DataCaptureOptions>
Configuration for automatic data capture. Can be “all”, “input”, “output”, “none”, or a configuration object.
Optional<SpanProcessor[]>
Custom span processors for advanced trace processing.
Optional<DebugOptions>
Debug and development options.
Optional<AdvancedOptions>
Advanced and potentially unsafe configuration options.
LangWatchConfig
Configuration for LangWatch integration.
Optional<string>
default:"process.env.LANGWATCH_API_KEY"
LangWatch API key for authentication.
Optional<string>
default:"https://app.langwatch.ai"
LangWatch endpoint URL for sending traces and logs.
Optional<'simple' | 'batch'>
default:"'simple'"
Type of span processor to use for LangWatch exporter.
DebugOptions
Debug and development options.
Optional<boolean>
default:"false"
Enable console output for traces (debugging).
Optional<boolean>
default:"false"
Enable console output for logs (debugging).
Optional<'debug' | 'info' | 'warn' | 'error'>
default:"'warn'"
Log level for LangWatch SDK internal logging.
Optional<Logger>
Custom logger for LangWatch SDK internal logging.
ObservabilityHandle
Handle returned from observability setup.
() => Promise<void>
Gracefully shuts down the observability system.
Tracing
getLangWatchTracer()
Returns a LangWatch tracer instance that provides enhanced tracing capabilities for LLM applications.
string
required
The name of the tracer/service.
Optional<string>
default:"undefined"
The version of the tracer/service.
LangWatchTracer
A
LangWatchTracer instance with enhanced methods for LLM observability.getLangWatchTracerFromProvider()
Get a LangWatch tracer from a specific OpenTelemetry tracer provider.
TracerProvider
required
The OpenTelemetry tracer provider to use.
string
required
The name of the tracer/service.
Optional<string>
default:"undefined"
The version of the tracer/service.
LangWatchTracer
The LangWatchTracer extends the standard OpenTelemetry Tracer with additional methods for LLM observability.
Methods
(name: string, options?: SpanOptions, context?: Context) => LangWatchSpan
Starts a new
LangWatchSpan without setting it on context. This method does NOT modify the current Context.(name: string, fn: (span: LangWatchSpan) => T) => T
Starts a new
LangWatchSpan and calls the given function passing it the created span as first argument. The new span gets set in context and this context is activated for the duration of the function call.(name: string, fn: (span: LangWatchSpan) => Promise<T> | T) => Promise<T>
Starts a new
LangWatchSpan, runs the provided async function, and automatically handles error recording, status setting, and span ending. This is a safer and more ergonomic alternative to manually using try/catch/finally blocks.createLangWatchSpan()
Creates a LangWatchSpan, which adds additional methods to an OpenTelemetry Span. You probably don’t need to use this directly, but it’s here for completeness.
Span
required
The OpenTelemetry Span to add LangWatch methods to.
LangWatchSpan
A LangWatchSpan with additional methods for LLM/GenAI observability.
LangWatchSpan
The LangWatchSpan extends the standard OpenTelemetry Span with additional methods for LLM observability.
Span Configuration Methods
(type: SpanType) => this
Set the type of the span (e.g., ‘llm’, ‘rag’, ‘tool’, etc). This is used for downstream filtering and analytics.
(model: string) => this
Set the request model name for the span. This is typically the model name sent in the API request (e.g., ‘gpt-5’, ‘claude-3’).
(model: string) => this
Set the response model name for the span. This is the model name returned in the API response, if different from the request.
(ragContexts: LangWatchSpanRAGContext[]) => this
Set multiple RAG contexts for the span. Use this to record all retrieved documents/chunks used as context for a generation.
(ragContext: LangWatchSpanRAGContext) => this
Set a single RAG context for the span. Use this if only one context was retrieved.
(metrics: LangWatchSpanMetrics) => this
Set the metrics for the span.
(prompt: Prompt) => this
Set the selected prompt for the span. This will attach this prompt to the trace. If this is set on multiple spans, the last one will be used.
Input/Output Methods
(input: unknown) => this
Record the input to the span with automatic type detection.
(type: InputOutputType, input: unknown) => this
Record the input to the span with explicit type control. Supports “text”, “raw”, “chat_messages”, “list”, “json”, “guardrail_result”, and “evaluation_result” types.
(output: unknown) => this
Record the output from the span with automatic type detection.
(type: InputOutputType, output: unknown) => this
Record the output from the span with explicit type control. Supports “text”, “raw”, “chat_messages”, “list”, “json”, “guardrail_result”, and “evaluation_result” types.
Client SDK
LangWatch
The main LangWatch client class that provides access to LangWatch services.
LangWatchConstructorOptions
default:"{}"
Configuration options for the LangWatch client.
Properties
PromptsFacade
Access to prompt management functionality.
TracesFacade
Access to trace management functionality.
Prompt Management
langwatch.prompts.get()
Retrieves a prompt from the LangWatch platform.
string
required
The ID of the prompt to retrieve.
Prompt
The prompt or compiled prompt object.
Error
Throws an error if the specified prompt version is not found.
langwatch.prompts.create()
Creates a new prompt in the LangWatch platform.
CreatePromptOptions
required
Configuration options for creating the prompt.
Prompt
The newly created prompt object.
langwatch.prompts.update()
Updates an existing prompt, creating a new version automatically.
string
required
The handle (identifier) of the prompt to update.
UpdatePromptOptions
required
Configuration options for updating the prompt.
Prompt
The updated prompt object (new version).
langwatch.prompts.delete()
Deletes a prompt and all its versions from the LangWatch platform.
string
required
The handle (identifier) of the prompt to delete.
DeletePromptResult
Confirmation of the deletion operation.
Prompt Compilation
prompt.compile()
Compiles a prompt template with provided variables, using lenient compilation that handles missing variables gracefully.
Record<string, any>
required
Variables to substitute into the prompt template.
CompiledPrompt
The compiled prompt with resolved variables and messages.
Lenient compilation will not throw errors for missing variables, making it suitable for dynamic content where some variables may be optional.
prompt.compileStrict()
Compiles a prompt template with strict variable validation, throwing an error if any required variables are missing.
Record<string, any>
required
Variables to substitute into the prompt template. All template variables must be provided.
CompiledPrompt
The compiled prompt with resolved variables and messages.
PromptCompilationError
Throws an error if any template variables are missing or invalid.
Processors
FilterableBatchSpanProcessor
A span processor that filters spans before processing them.
SpanExporter
required
The span exporter to use.
SpanProcessingExcludeRule[]
required
Rules to exclude spans from processing.
LangChain Integration
LangWatchCallbackHandler
A LangChain callback handler that automatically traces LangChain operations and integrates them with LangWatch.
LangWatchCallbackHandler automatically:
- Creates spans for LLM calls, chains, tools, and retrievers
- Captures input/output data
- Sets appropriate span types and metadata
- Handles errors and status codes
- Integrates with the LangWatch tracing system
convertFromLangChainMessages
Utility function to convert LangChain messages to a format compatible with LangWatch GenAI events.
Exporters
LangWatchExporter
A LangWatch exporter for sending traces to the LangWatch platform. Extends the OpenTelemetry OTLP HTTP trace exporter with proper authentication and metadata headers.
Optional<string>
default:"process.env.LANGWATCH_API_KEY"
Optional API key for LangWatch authentication. If not provided, will use environment variables or fallback configuration.
Optional<string>
Optional custom endpoint URL for LangWatch ingestion. If not provided, will use environment variables or fallback configuration.
LangWatchTraceExporter
A LangWatch trace exporter with configuration options.
LangWatchLogsExporter
A LangWatch logs exporter with configuration options.
Data Capture
DataCaptureOptions
Configuration for automatic data capture.
DataCapturePresets
Predefined data capture configurations.
Logging
getLangWatchLogger()
Returns a LangWatch logger instance for structured logging.
getLangWatchLoggerFromProvider()
Get a LangWatch logger from a specific logger provider.
ConsoleLogger
A console-based logger with configurable log levels and prefixes.
ConsoleLoggerOptions
default:"{ level: 'warn' }"
Logger configuration options.
NoOpLogger
A no-operation logger that discards all log messages.
CLI
The LangWatch CLI provides command-line tools for managing prompts and interacting with the LangWatch platform.Core Data Types
SpanType
Supported types of spans for LangWatch observability:
InputOutputType
Supported input/output types for span data:
LangWatchSpanRAGContext
Context for a RAG (Retrieval-Augmented Generation) span.
string
required
Unique identifier for the source document.
string
required
Unique identifier for the chunk within the document.
string
required
The actual content of the chunk provided to the model.
LangWatchSpanMetrics
Metrics for a LangWatch span.
Optional<number>
The number of prompt tokens used.
Optional<number>
The number of completion tokens used.
Optional<number>
The cost of the span.
SpanProcessingExcludeRule
Defines a rule to filter out spans before they are exported to LangWatch.
'span_name'
required
The field of the span to match against. Currently, only
"span_name" is supported.string
required
The value to match for the specified
fieldName.'includes' | 'exact_match' | 'starts_with' | 'ends_with'
required
The operation to use for matching.
PromptResponse
The raw prompt response type extracted from the OpenAPI schema.
Prompt
A prompt object retrieved from the LangWatch platform with compilation capabilities.
string
Unique identifier for the prompt.
string
Project identifier the prompt belongs to.
string
Organization identifier the prompt belongs to.
string | null
Optional handle/slug for the prompt.
'ORGANIZATION' | 'PROJECT'
Scope of the prompt - either organization-wide or project-specific.
string
Name of the prompt.
string
Last update timestamp.
number
Version number.
string
Version identifier.
string
Model used for the prompt.
string
The prompt template.
Array
Array of message objects.
object
Response format configuration.
string | null
ID of the prompt author.
string
Creation timestamp.
Array
Input definitions for the prompt.
Array
Output definitions for the prompt.
CompiledPrompt
A compiled prompt that extends Prompt with reference to the original template.
Prompt
The original prompt object before compilation.
TemplateVariables
Template variables for prompt compilation.
PromptCompilationError
Error thrown when prompt compilation fails.
string
The template that failed to compile.
any
The original compilation error.
LangWatchConstructorOptions
Configuration options for the LangWatch client.
Optional<string>
Your LangWatch API key. Defaults to
process.env.LANGWATCH_API_KEY.Optional<string>
The LangWatch endpoint URL. Defaults to
process.env.LANGWATCH_ENDPOINT.Optional<{ logger?: Logger }>
Additional options including custom logger.
Usage Examples
Basic Tracing
RAG Operations
Using Semantic Conventions
Prompt Management
LangChain Integration
Custom Span Processing
Advanced Setup with Data Capture
Graceful Shutdown
Related Documentation
For practical examples and advanced usage patterns, see:- Integration Guide - Get started with LangWatch TypeScript SDK
- Manual Instrumentation - Advanced span management techniques
- Semantic Conventions - Standardized attribute naming guidelines
- Debugging and Troubleshooting - Troubleshoot integration issues
- Framework Integrations - Framework-specific setup and examples