import { BatchSpanProcessor, SpanExporter, ReadableSpan } from '@opentelemetry/sdk-trace-base'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; import { ExportResult } from '@opentelemetry/core'; import { Logger, LogRecord, LoggerProvider } from '@opentelemetry/api-logs'; import { b as SemConvLogRecordAttributes, S as SemConvAttributes } from './types-BvCQH8F1.js'; import { TracerProvider } from '@opentelemetry/api'; import { L as LangWatchTracer } from './types-CmMOt86P.js'; /** * Filterable Batch Span Exporter for OpenTelemetry * * This module provides a BatchSpanProcessor subclass that allows filtering of spans before export * based on configurable rules. Spans matching any exclude rule are dropped and not exported. * * @module filterable-batch-span-exporter */ /** * A rule for excluding spans from export based on their name or instrumentation scope name. * * @property fieldName - The span field to match against ('span_name' or 'instrumentation_scope_name'). * @property matchValue - The value to match against the field. * @property matchOperation - The operation to use for matching ('includes', 'exact_match', 'starts_with', 'ends_with'). * * @example * const rule: SpanProcessingExcludeRule = { * fieldName: 'span_name', * matchValue: 'heartbeat', * matchOperation: 'exact_match', * }; */ interface SpanProcessingExcludeRule { fieldName: "span_name" | "instrumentation_scope_name"; matchValue: string; matchOperation: "includes" | "exact_match" | "starts_with" | "ends_with"; } /** * A BatchSpanProcessor that filters out spans matching any of the provided exclude rules before export. * * This is useful for dropping noisy or irrelevant spans (e.g., health checks, heartbeats) from being exported to your tracing backend. * * @example * import { FilterableBatchSpanProcessor } from './filterable-batch-span-exporter'; * import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; * * const exporter = new OTLPTraceExporter({ url: '...' }); * const filters = [ * { fieldName: 'span_name', matchValue: 'heartbeat', matchOperation: 'exact_match' }, * { fieldName: 'instrumentation_scope_name', matchValue: 'internal', matchOperation: 'starts_with' }, * ]; * provider.addSpanProcessor(new FilterableBatchSpanProcessor(exporter, filters)); */ declare class FilterableBatchSpanProcessor extends BatchSpanProcessor { private readonly _filters; /** * Create a new FilterableBatchSpanProcessor. * * @param exporter - The underlying SpanExporter to use for exporting spans. * @param filters - An array of rules for excluding spans from export. */ constructor(exporter: SpanExporter, filters: SpanProcessingExcludeRule[]); /** * Called when a span ends. If the span matches any exclude rule, it is dropped and not exported. * * @param span - The ReadableSpan that has ended. */ onEnd(span: ReadableSpan): void; } interface Criteria { instrumentationScopeName?: Match[]; name?: Match[]; } interface Match { equals?: string; startsWith?: string; matches?: RegExp; ignoreCase?: boolean; } type TraceFilter = { preset: "vercelAIOnly" | "excludeHttpRequests"; } | { include: Criteria; } | { exclude: Criteria; }; /** * Configuration options for the LangWatchTraceExporter. * * @property endpoint - Custom LangWatch endpoint URL. Falls back to LANGWATCH_ENDPOINT env var or default. * @property apiKey - API key for authentication. Falls back to LANGWATCH_API_KEY env var. * @property filters - Array of filters applied sequentially to spans before export. * Default: `[{ preset: "excludeHttpRequests" }]` to reduce framework noise. * Pass `null` or `[]` to disable all filtering. */ interface LangWatchTraceExporterOptions { endpoint?: string; apiKey?: string; /** * Project identifier. Required when `apiKey` is a Personal Access Token * (`pat-lw-*`); ignored for legacy `sk-lw-*` keys. Falls back to * `LANGWATCH_PROJECT_ID`. */ projectId?: string; filters?: TraceFilter[] | null; } /** * LangWatchTraceExporter extends the OpenTelemetry OTLP HTTP trace exporter * to send trace data to LangWatch with proper authentication and metadata headers. * * ## Features * - Automatic authorization header configuration via API key * - SDK version and runtime identification headers * - Proper endpoint URL construction for LangWatch ingestion * - Intent-based span filtering with presets and custom criteria * * ## Filtering Behavior * - **Default**: HTTP request spans are excluded to reduce framework noise * - **Pipeline**: Filters are applied sequentially with AND semantics * - **Matching**: All string comparisons are case-sensitive by default * - **Array Syntax**: All criteria require arrays of Match objects for explicit filtering * * ## Filter Types * - **Presets**: Pre-configured common filters (`vercelAIOnly`, `excludeHttpRequests`) * - **Include**: Keep only spans matching criteria (OR within field, AND across fields) * - **Exclude**: Remove spans matching criteria (OR within field, AND across fields) * * @example Basic usage with default filtering * ```typescript * import { LangWatchTraceExporter } from '@langwatch/observability'; * * // Default: excludes HTTP request spans * const exporter = new LangWatchTraceExporter(); * ``` * * @example Using presets * ```typescript * // Keep only Vercel AI SDK spans * const exporterAI = new LangWatchTraceExporter({ * filters: [{ preset: 'vercelAIOnly' }], * }); * * // Explicitly exclude HTTP requests (same as default) * const exporterNoHttp = new LangWatchTraceExporter({ * filters: [{ preset: 'excludeHttpRequests' }], * }); * * // No filtering at all (send all spans) * const exporterAll = new LangWatchTraceExporter({ * filters: null, // or filters: [] * }); * ``` * * @example Custom filtering with criteria * ```typescript * // Include only spans with specific scope * const exporter1 = new LangWatchTraceExporter({ * filters: [ * { include: { instrumentationScopeName: [{ equals: 'ai' }] } } * ], * }); * * // Exclude spans by name pattern * const exporter2 = new LangWatchTraceExporter({ * filters: [ * { exclude: { name: [{ startsWith: 'internal.' }] } } * ], * }); * * // Case-insensitive matching * const exporter3 = new LangWatchTraceExporter({ * filters: [ * { include: { name: [{ equals: 'chat.completion', ignoreCase: true }] } } * ], * }); * ``` * * @example Filter pipelines (AND semantics) * ```typescript * // Keep AI spans, then remove HTTP requests * const exporter = new LangWatchTraceExporter({ * filters: [ * { include: { instrumentationScopeName: [{ equals: 'ai' }] } }, * { preset: 'excludeHttpRequests' }, * ], * }); * ``` * * @example OR semantics within a field * ```typescript * // Include spans with name starting with 'chat.' OR 'llm.' * const exporter = new LangWatchTraceExporter({ * filters: [ * { * include: { * name: [ * { startsWith: 'chat.' }, * { startsWith: 'llm.' } * ] * } * } * ], * }); * ``` * * @example Using regex patterns * ```typescript * const exporter = new LangWatchTraceExporter({ * filters: [ * { * include: { * name: [{ matches: /^(chat|llm)\./i }] * } * } * ], * }); * ``` */ declare class LangWatchTraceExporter extends OTLPTraceExporter { private readonly filters; /** * Creates a new LangWatchTraceExporter instance. * * @param opts - Configuration options for the exporter * @param opts.apiKey - API key for LangWatch authentication. * Falls back to `LANGWATCH_API_KEY` environment variable, then empty string. * @param opts.endpoint - Custom endpoint URL for LangWatch ingestion. * Falls back to `LANGWATCH_ENDPOINT` environment variable, then default endpoint. * @param opts.filters - Array of filters applied sequentially to spans before export (AND semantics). * When omitted, defaults to `[{ preset: "excludeHttpRequests" }]`. * Pass `null` or `[]` to disable all filtering and send all spans. * * @example * ```typescript * // With API key and default filtering * const exporter = new LangWatchTraceExporter({ * apiKey: 'your-api-key' * }); * * // With custom endpoint and no filtering * const exporter = new LangWatchTraceExporter({ * endpoint: 'https://custom.langwatch.ai', * filters: null * }); * ``` */ constructor(opts?: LangWatchTraceExporterOptions); export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void; } /** * Anthropic AI system identifier * Used to identify Anthropic's Claude models */ declare const VAL_GEN_AI_SYSTEM_ANTHROPIC = "anthropic"; /** * AWS Bedrock system identifier * Used to identify AWS Bedrock AI services */ declare const VAL_GEN_AI_SYSTEM_AWS_BEDROCK = "aws.bedrock"; /** * Azure AI Inference system identifier * Used to identify Azure AI Inference services */ declare const VAL_GEN_AI_SYSTEM_AZURE_AI_INFERENCE = "azure.ai.inference"; /** * Azure AI OpenAI system identifier * Used to identify Azure OpenAI services */ declare const VAL_GEN_AI_SYSTEM_AZURE_AI_OPENAI = "azure.ai.openai"; /** * Cohere system identifier * Used to identify Cohere AI models */ declare const VAL_GEN_AI_SYSTEM_COHERE = "cohere"; /** * DeepSeek system identifier * Used to identify DeepSeek AI models */ declare const VAL_GEN_AI_SYSTEM_DEEPSEEK = "deepseek"; /** * GCP Gemini system identifier * Used to identify Google Cloud Gemini models */ declare const VAL_GEN_AI_SYSTEM_GCP_GEMINI = "gcp.gemini"; /** * GCP Gen AI system identifier * Used to identify Google Cloud Generative AI services */ declare const VAL_GEN_AI_SYSTEM_GCP_GEN_AI = "gcp.gen_ai"; /** * GCP Vertex AI system identifier * Used to identify Google Cloud Vertex AI services */ declare const VAL_GEN_AI_SYSTEM_GCP_VERTEX_AI = "gcp.vertex_ai"; /** * Groq system identifier * Used to identify Groq AI models */ declare const VAL_GEN_AI_SYSTEM_GROQ = "groq"; /** * IBM WatsonX AI system identifier * Used to identify IBM WatsonX AI services */ declare const VAL_GEN_AI_SYSTEM_IBM_WATSONX_AI = "ibm.watsonx.ai"; /** * Mistral AI system identifier * Used to identify Mistral AI models */ declare const VAL_GEN_AI_SYSTEM_MISTRAL_AI = "mistral_ai"; /** * OpenAI system identifier * Used to identify OpenAI models and services */ declare const VAL_GEN_AI_SYSTEM_OPENAI = "openai"; /** * Perplexity system identifier * Used to identify Perplexity AI models */ declare const VAL_GEN_AI_SYSTEM_PERPLEXITY = "perplexity"; /** * XAI system identifier * Used to identify XAI models and services */ declare const VAL_GEN_AI_SYSTEM_XAI = "xai"; /** * Content filter finish reason * Used when generation stops due to content filtering */ declare const VAL_GEN_AI_FINISH_REASON_CONTENT_FILTER = "content_filter"; /** * Error finish reason * Used when generation stops due to an error */ declare const VAL_GEN_AI_FINISH_REASON_ERROR = "error"; /** * Length finish reason * Used when generation stops due to length limits */ declare const VAL_GEN_AI_FINISH_REASON_LENGTH = "length"; /** * Stop finish reason * Used when generation stops due to stop tokens */ declare const VAL_GEN_AI_FINISH_REASON_STOP = "stop"; /** * Tool calls finish reason * Used when generation stops due to tool calls */ declare const VAL_GEN_AI_FINISH_REASON_TOOL_CALLS = "tool_calls"; /** * Union type of all supported GenAI system identifiers * Used for type safety when working with system identification */ type VAL_GEN_AI_SYSTEMS = typeof VAL_GEN_AI_SYSTEM_ANTHROPIC | typeof VAL_GEN_AI_SYSTEM_AWS_BEDROCK | typeof VAL_GEN_AI_SYSTEM_AZURE_AI_INFERENCE | typeof VAL_GEN_AI_SYSTEM_AZURE_AI_OPENAI | typeof VAL_GEN_AI_SYSTEM_COHERE | typeof VAL_GEN_AI_SYSTEM_DEEPSEEK | typeof VAL_GEN_AI_SYSTEM_GCP_GEMINI | typeof VAL_GEN_AI_SYSTEM_GCP_GEN_AI | typeof VAL_GEN_AI_SYSTEM_GCP_VERTEX_AI | typeof VAL_GEN_AI_SYSTEM_GROQ | typeof VAL_GEN_AI_SYSTEM_IBM_WATSONX_AI | typeof VAL_GEN_AI_SYSTEM_MISTRAL_AI | typeof VAL_GEN_AI_SYSTEM_OPENAI | typeof VAL_GEN_AI_SYSTEM_PERPLEXITY | typeof VAL_GEN_AI_SYSTEM_XAI; /** * Union type of all supported GenAI finish reasons * Used for type safety when working with generation completion reasons */ type VAL_GEN_AI_FINISH_REASONS = typeof VAL_GEN_AI_FINISH_REASON_CONTENT_FILTER | typeof VAL_GEN_AI_FINISH_REASON_ERROR | typeof VAL_GEN_AI_FINISH_REASON_LENGTH | typeof VAL_GEN_AI_FINISH_REASON_STOP | typeof VAL_GEN_AI_FINISH_REASON_TOOL_CALLS; /** * Body for a system message event in a GenAI span. * * Used to log system/instruction messages sent to the model. * * @property content - The message content. * @property role - The role of the message, typically 'system' or 'instruction'. * * @example * logger.emitGenAISystemMessageEvent({ content: 'You are a helpful assistant.' }); */ interface LangWatchSpanGenAISystemMessageEventBody { /** Content of the system message */ content?: string; /** Role of the message (system or instruction) */ role?: "system" | "instruction"; } /** * Body for a user message event in a GenAI span. * * Used to log user/customer messages sent to the model. * * @property content - The message content. * @property role - The role of the message, typically 'user' or 'customer'. * * @example * logger.emitGenAIUserMessageEvent({ content: 'What is the weather today?' }); */ interface LangWatchSpanGenAIUserMessageEventBody { /** Content of the user message */ content?: string; /** Role of the message (user or customer) */ role?: "user" | "customer"; } /** * Body for an assistant message event in a GenAI span. * * Used to log assistant/bot responses, including tool calls. * * @property content - The message content. * @property role - The role of the message, typically 'assistant' or 'bot'. * @property tool_calls - Array of tool call objects, if the assistant invoked tools/functions. * * @example * logger.emitGenAIAssistantMessageEvent({ content: 'The weather is sunny.', role: 'assistant' }); */ interface LangWatchSpanGenAIAssistantMessageEventBody { /** Content of the assistant message */ content?: string; /** Role of the message (assistant or bot) */ role?: "assistant" | "bot"; /** Tool calls made by the assistant */ tool_calls?: { function: { /** Name of the function called */ name: string; /** Arguments passed to the function */ arguments?: string; }; /** Tool call identifier */ id: string; /** Type of tool call */ type: "function"; }[]; } /** * Body for a tool message event in a GenAI span. * * Used to log messages from tools/functions invoked by the assistant. * * @property content - The message content. * @property id - Unique identifier for the tool call. * @property role - The role, typically 'tool' or 'function'. * * @example * logger.emitGenAIToolMessageEvent({ content: 'Result from tool', id: 'tool-1', role: 'tool' }); */ interface LangWatchSpanGenAIToolMessageEventBody { /** Content of the tool message */ content?: string; /** Tool call identifier */ id: string; /** Role of the message (tool or function) */ role?: "tool" | "function"; } /** * Body for a choice event in a GenAI span. * * Used to log the model's output choices, including finish reason and message content. * * @property finish_reason - Why the generation finished (e.g., 'stop', 'length'). * @property index - Index of the choice (for multi-choice outputs). * @property message - The message content and tool calls for this choice. * * @example * logger.emitGenAIChoiceEvent({ finish_reason: 'stop', index: 0, message: { content: 'Hello!' } }); */ interface LangWatchSpanGenAIChoiceEventBody { /** Reason the generation finished */ finish_reason: VAL_GEN_AI_FINISH_REASONS | (string & {}); /** Index of the choice */ index: number; /** Message content for the choice */ message?: { /** Content of the message */ content?: string; /** Role of the message (assistant or bot) */ role?: "assistant" | "bot"; /** Tool calls made by the assistant */ tool_calls?: { function: { /** Name of the function called */ name: string; /** Arguments passed to the function */ arguments?: string; }; /** Tool call identifier */ id: string; /** Type of tool call */ type: "function"; }[]; }; } /** * Extension of OpenTelemetry's LogRecord with LangWatch and GenAI-specific attributes. */ interface LangWatchLogRecord extends LogRecord { /** * Additional attributes to add to the log record. * * @default {} */ attributes?: SemConvLogRecordAttributes; } /** * Options for emitting a log record. */ interface EmitOptions { /** * Whether to not include the OTel context on the log record. * * With standard OpenTelemetry, the context is not included on the log record by * default, so this is useful if you want to emit a lot without having to manually * set the context on each log record. * * @default false */ excludeContext?: boolean; } /** * Extension of OpenTelemetry's Logger with LangWatch and GenAI-specific methods. */ interface LangWatchLogger extends Logger { /** * Emit a log record with LangWatch and GenAI-specific attributes. * * @param logRecord - The log record to emit * @param options - Optional options for emitting the log record */ emit(logRecord: LangWatchLogRecord, options?: EmitOptions): void; /** * Emit a GenAI system message event to the logger. * * This logs a system/instruction message sent to the model. * * @param body - The event body (content and role) * @param system - The GenAI system (optional, e.g., 'openai', 'anthropic') * @param attributes - Additional OpenTelemetry attributes (optional) * @returns this */ emitGenAISystemMessageEvent(body: LangWatchSpanGenAISystemMessageEventBody, system?: VAL_GEN_AI_SYSTEMS | (string & {}), attributes?: SemConvAttributes): void; /** * Emit a GenAI user message event to the logger. * * This logs a user/customer message sent to the model. * * @param body - The event body (content and role) * @param system - The GenAI system (optional) * @param attributes - Additional OpenTelemetry attributes (optional) * @returns this */ emitGenAIUserMessageEvent(body: LangWatchSpanGenAIUserMessageEventBody, system?: VAL_GEN_AI_SYSTEMS | (string & {}), attributes?: SemConvAttributes): void; /** * Emit a GenAI assistant message event to the logger. * * This logs an assistant/bot response, including tool calls if present. * * @param body - The event body (content, role, tool_calls) * @param system - The GenAI system (optional) * @param attributes - Additional OpenTelemetry attributes (optional) * @returns this */ emitGenAIAssistantMessageEvent(body: LangWatchSpanGenAIAssistantMessageEventBody, system?: VAL_GEN_AI_SYSTEMS | (string & {}), attributes?: SemConvAttributes): void; /** * Emit a GenAI tool message event to the logger. * * This logs a message from a tool/function invoked by the assistant. * * @param body - The event body (content, id, role) * @param system - The GenAI system (optional) * @param attributes - Additional OpenTelemetry attributes (optional) * @returns this */ emitGenAIToolMessageEvent(body: LangWatchSpanGenAIToolMessageEventBody, system?: VAL_GEN_AI_SYSTEMS | (string & {}), attributes?: SemConvAttributes): void; /** * Emit a GenAI choice event to the logger. * * This logs a model output choice, including finish reason and message content. * * @param body - The event body (finish_reason, index, message) * @param system - The GenAI system (optional) * @param attributes - Additional OpenTelemetry attributes (optional) * @returns this */ emitGenAIChoiceEvent(body: LangWatchSpanGenAIChoiceEventBody, system?: VAL_GEN_AI_SYSTEMS | (string & {}), attributes?: SemConvAttributes): void; } /** * Retrieves a LangWatch logger with the specified name and optional version. * * @param name - The name of the logger (typically your service or module name). * @param version - (Optional) The version of the logger. * @returns A {@link LangWatchLogger} instance. * * @remarks * Uses the logger provider set during observability setup. If no provider is set, returns * a NoOp logger. * * @example * ```ts * const logger = getLangWatchLogger("my-service"); * logger.info("Service started"); * ``` * * @see {@link setLangWatchLoggerProvider} */ declare function getLangWatchLogger(name: string, version?: string): LangWatchLogger; /** * Retrieves a LangWatch logger from a specific OpenTelemetry logger provider. * * @param loggerProvider - The OpenTelemetry logger provider to use. * @param name - The name of the logger. * @param version - (Optional) The version of the logger. * @returns A {@link LangWatchLogger} instance. * * @remarks * Use this function if you want to use a custom logger provider instead of the global one. * * @example * ```ts * const customProvider = new LoggerProvider(); * const logger = getLangWatchLoggerFromProvider(customProvider, "custom-service"); * ``` */ declare function getLangWatchLoggerFromProvider(loggerProvider: LoggerProvider, name: string, version?: string): LangWatchLogger; /** * Get a LangWatch tracer from the global OpenTelemetry tracer provider. * * This is the primary entry point for obtaining a LangWatch tracer instance. * It uses the globally configured OpenTelemetry tracer provider and wraps * the resulting tracer with LangWatch-specific enhancements. * * **Prerequisites**: Ensure that LangWatch's observability setup has been * initialized before calling this function, otherwise the global tracer * provider may not be properly configured. * * @param name - The name of the tracer, typically your service or library name * @param version - Optional version identifier for the tracer * @returns A LangWatch tracer with enhanced functionality * * @example Basic usage * ```typescript * import { getLangWatchTracer } from '@langwatch/typescript-sdk'; * * const tracer = getLangWatchTracer('my-service', '1.0.0'); * * // Use the tracer to create spans * const result = await tracer.withActiveSpan('operation', async (span) => { * span.setAttributes({ userId: '123' }); * return await performOperation(); * }); * ``` * * @example Multiple tracers for different components * ```typescript * const apiTracer = getLangWatchTracer('api-server', '2.1.0'); * const dbTracer = getLangWatchTracer('database-client', '1.5.2'); * * // Each tracer can be used independently * await apiTracer.withActiveSpan('handle-request', async (span) => { * await dbTracer.withActiveSpan('query-users', async (dbSpan) => { * // Nested spans with proper parent-child relationships * }); * }); * ``` */ declare function getLangWatchTracer(name: string, version?: string): LangWatchTracer; /** * Get a LangWatch tracer from a specific OpenTelemetry tracer provider. * * This function provides more control over which tracer provider is used, * allowing you to work with custom or multiple tracer provider instances. * This is useful in advanced scenarios where you need to: * - Use different tracer providers for different parts of your application * - Work with custom tracer provider configurations * - Test with mock tracer providers * * @param tracerProvider - The OpenTelemetry tracer provider to use * @param name - The name of the tracer, typically your service or library name * @param version - Optional version identifier for the tracer * @returns A LangWatch tracer with enhanced functionality * * @example Custom tracer provider * ```typescript * import { NodeTracerProvider } from '@opentelemetry/sdk-node'; * import { getLangWatchTracerFromProvider } from '@langwatch/typescript-sdk'; * * // Create a custom tracer provider with specific configuration * const customProvider = new NodeTracerProvider({ * resource: Resource.default().merge( * new Resource({ * [SemanticResourceAttributes.SERVICE_NAME]: 'custom-service', * }) * ) * }); * * const tracer = getLangWatchTracerFromProvider( * customProvider, * 'custom-tracer', * '1.0.0' * ); * ``` * * @example Testing with mock provider * ```typescript * import { InMemorySpanExporter } from '@opentelemetry/sdk-trace-base'; * * const mockExporter = new InMemorySpanExporter(); * const testProvider = new NodeTracerProvider(); * testProvider.addSpanProcessor(new SimpleSpanProcessor(mockExporter)); * * const testTracer = getLangWatchTracerFromProvider( * testProvider, * 'test-tracer' * ); * * // Use testTracer in tests and verify spans via mockExporter * ``` */ declare function getLangWatchTracerFromProvider(tracerProvider: TracerProvider, name: string, version?: string): LangWatchTracer; export { FilterableBatchSpanProcessor as F, LangWatchTraceExporter as L, type SpanProcessingExcludeRule as S, type LangWatchTraceExporterOptions as a, type LangWatchLogger as b, getLangWatchLoggerFromProvider as c, getLangWatchTracer as d, getLangWatchTracerFromProvider as e, getLangWatchLogger as g };