@langfuse/core 4.2.1 → 4.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +409 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +212 -1
- package/dist/index.d.ts +212 -1
- package/dist/index.mjs +407 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { Context } from '@opentelemetry/api';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Enumeration of log levels in order of severity (lowest to highest).
|
|
3
5
|
*/
|
|
@@ -179,6 +181,7 @@ declare const resetGlobalLogger: () => void;
|
|
|
179
181
|
declare const LANGFUSE_TRACER_NAME = "langfuse-sdk";
|
|
180
182
|
declare const LANGFUSE_SDK_VERSION: string;
|
|
181
183
|
declare const LANGFUSE_SDK_NAME = "javascript";
|
|
184
|
+
declare const LANGFUSE_SDK_EXPERIMENT_ENVIRONMENT = "sdk-experiment";
|
|
182
185
|
declare enum LangfuseOtelSpanAttributes {
|
|
183
186
|
TRACE_NAME = "langfuse.trace.name",
|
|
184
187
|
TRACE_USER_ID = "user.id",
|
|
@@ -205,6 +208,15 @@ declare enum LangfuseOtelSpanAttributes {
|
|
|
205
208
|
RELEASE = "langfuse.release",
|
|
206
209
|
VERSION = "langfuse.version",
|
|
207
210
|
AS_ROOT = "langfuse.internal.as_root",
|
|
211
|
+
EXPERIMENT_ID = "langfuse.experiment.id",
|
|
212
|
+
EXPERIMENT_NAME = "langfuse.experiment.name",
|
|
213
|
+
EXPERIMENT_DESCRIPTION = "langfuse.experiment.description",
|
|
214
|
+
EXPERIMENT_METADATA = "langfuse.experiment.metadata",
|
|
215
|
+
EXPERIMENT_DATASET_ID = "langfuse.experiment.dataset.id",
|
|
216
|
+
EXPERIMENT_ITEM_ID = "langfuse.experiment.item.id",
|
|
217
|
+
EXPERIMENT_ITEM_EXPECTED_OUTPUT = "langfuse.experiment.item.expected_output",
|
|
218
|
+
EXPERIMENT_ITEM_METADATA = "langfuse.experiment.item.metadata",
|
|
219
|
+
EXPERIMENT_ITEM_ROOT_OBSERVATION_ID = "langfuse.experiment.item.root_observation_id",
|
|
208
220
|
TRACE_COMPAT_USER_ID = "langfuse.user.id",
|
|
209
221
|
TRACE_COMPAT_SESSION_ID = "langfuse.session.id"
|
|
210
222
|
}
|
|
@@ -6770,6 +6782,23 @@ declare function base64ToBytes(base64: string): Uint8Array;
|
|
|
6770
6782
|
declare function bytesToBase64(bytes: Uint8Array): string;
|
|
6771
6783
|
declare function base64Encode(input: string): string;
|
|
6772
6784
|
declare function base64Decode(input: string): string;
|
|
6785
|
+
/**
|
|
6786
|
+
* Generate a random experiment ID (16 hex characters from 8 random bytes).
|
|
6787
|
+
* @internal
|
|
6788
|
+
*/
|
|
6789
|
+
declare function createExperimentId(): Promise<string>;
|
|
6790
|
+
/**
|
|
6791
|
+
* Generate experiment item ID from input hash (first 16 hex chars of SHA-256).
|
|
6792
|
+
* Skips serialization if input is already a string.
|
|
6793
|
+
* @internal
|
|
6794
|
+
*/
|
|
6795
|
+
declare function createExperimentItemId(input: any): Promise<string>;
|
|
6796
|
+
/**
|
|
6797
|
+
* Serialize a value to JSON string, handling undefined/null.
|
|
6798
|
+
* Skips serialization if value is already a string.
|
|
6799
|
+
* @internal
|
|
6800
|
+
*/
|
|
6801
|
+
declare function serializeValue(value: any): string | undefined;
|
|
6773
6802
|
|
|
6774
6803
|
type ParsedMediaReference = {
|
|
6775
6804
|
mediaId: string;
|
|
@@ -6925,4 +6954,186 @@ declare class LangfuseMedia {
|
|
|
6925
6954
|
toJSON(): string | null;
|
|
6926
6955
|
}
|
|
6927
6956
|
|
|
6928
|
-
|
|
6957
|
+
/**
|
|
6958
|
+
* Attribute propagation utilities for Langfuse OpenTelemetry integration.
|
|
6959
|
+
*
|
|
6960
|
+
* This module provides the `propagateAttributes` function for setting trace-level
|
|
6961
|
+
* attributes (userId, sessionId, metadata) that automatically propagate to all child spans
|
|
6962
|
+
* within the context.
|
|
6963
|
+
*/
|
|
6964
|
+
|
|
6965
|
+
type CorrelatedKey = "userId" | "sessionId" | "metadata" | "version" | "tags";
|
|
6966
|
+
declare const experimentKeys: readonly ["experimentId", "experimentName", "experimentMetadata", "experimentDatasetId", "experimentItemId", "experimentItemMetadata", "experimentItemRootObservationId"];
|
|
6967
|
+
type ExperimentKey = (typeof experimentKeys)[number];
|
|
6968
|
+
type PropagatedKey = CorrelatedKey | ExperimentKey;
|
|
6969
|
+
type PropagatedExperimentAttributes = {
|
|
6970
|
+
experimentId: string;
|
|
6971
|
+
experimentName: string;
|
|
6972
|
+
experimentMetadata?: string;
|
|
6973
|
+
experimentDatasetId?: string;
|
|
6974
|
+
experimentItemId: string;
|
|
6975
|
+
experimentItemMetadata?: string;
|
|
6976
|
+
experimentItemRootObservationId: string;
|
|
6977
|
+
};
|
|
6978
|
+
declare const LangfuseOtelContextKeys: Record<PropagatedKey, symbol>;
|
|
6979
|
+
/**
|
|
6980
|
+
* Parameters for propagateAttributes function.
|
|
6981
|
+
*
|
|
6982
|
+
* @public
|
|
6983
|
+
*/
|
|
6984
|
+
interface PropagateAttributesParams {
|
|
6985
|
+
/**
|
|
6986
|
+
* User identifier to associate with all spans in this context.
|
|
6987
|
+
* Must be a string ≤200 characters. Use this to track which user
|
|
6988
|
+
* generated each trace and enable e.g. per-user cost/performance analysis.
|
|
6989
|
+
*/
|
|
6990
|
+
userId?: string;
|
|
6991
|
+
/**
|
|
6992
|
+
* Session identifier to associate with all spans in this context.
|
|
6993
|
+
* Must be a string ≤200 characters. Use this to group related traces
|
|
6994
|
+
* within a user session (e.g., a conversation thread, multi-turn interaction).
|
|
6995
|
+
*/
|
|
6996
|
+
sessionId?: string;
|
|
6997
|
+
/**
|
|
6998
|
+
* Additional key-value metadata to propagate to all spans.
|
|
6999
|
+
* - Keys and values must be strings
|
|
7000
|
+
* - All values must be ≤200 characters
|
|
7001
|
+
* - Use for dimensions like internal correlating identifiers
|
|
7002
|
+
* - AVOID: large payloads, sensitive data, non-string values (will be dropped with warning)
|
|
7003
|
+
*/
|
|
7004
|
+
metadata?: Record<string, string>;
|
|
7005
|
+
/**
|
|
7006
|
+
* Version identifier for parts of your application that are independently versioned, e.g. agents
|
|
7007
|
+
*/
|
|
7008
|
+
version?: string;
|
|
7009
|
+
/**
|
|
7010
|
+
* List of tags to categorize the group of observations
|
|
7011
|
+
*/
|
|
7012
|
+
tags?: string[];
|
|
7013
|
+
/**
|
|
7014
|
+
* If true, propagates attributes using OpenTelemetry baggage for
|
|
7015
|
+
* cross-process/service propagation.
|
|
7016
|
+
*
|
|
7017
|
+
* **Security warning**: When enabled, attribute values are added to HTTP headers
|
|
7018
|
+
* on ALL outbound requests. Only enable if values are safe to transmit via HTTP
|
|
7019
|
+
* headers and you need cross-service tracing.
|
|
7020
|
+
*
|
|
7021
|
+
* @defaultValue false
|
|
7022
|
+
*/
|
|
7023
|
+
asBaggage?: boolean;
|
|
7024
|
+
/**
|
|
7025
|
+
* **INTERNAL USE ONLY** - For Langfuse experiment framework.
|
|
7026
|
+
*
|
|
7027
|
+
* This parameter is used internally by the Langfuse experiment system to propagate
|
|
7028
|
+
* experiment context to child spans. It should NOT be used by external code.
|
|
7029
|
+
*
|
|
7030
|
+
* @internal
|
|
7031
|
+
*/
|
|
7032
|
+
_internalExperiment?: PropagatedExperimentAttributes;
|
|
7033
|
+
}
|
|
7034
|
+
/**
|
|
7035
|
+
* Propagate trace-level attributes to all spans created within this context.
|
|
7036
|
+
*
|
|
7037
|
+
* This function sets attributes on the currently active span AND automatically
|
|
7038
|
+
* propagates them to all new child spans created within the callback. This is the
|
|
7039
|
+
* recommended way to set trace-level attributes like userId, sessionId, and metadata
|
|
7040
|
+
* dimensions that should be consistently applied across all observations in a trace.
|
|
7041
|
+
*
|
|
7042
|
+
* **IMPORTANT**: Call this as early as possible within your trace/workflow. Only the
|
|
7043
|
+
* currently active span and spans created after entering this context will have these
|
|
7044
|
+
* attributes. Pre-existing spans will NOT be retroactively updated.
|
|
7045
|
+
*
|
|
7046
|
+
* **Why this matters**: Langfuse aggregation queries (e.g., total cost by userId,
|
|
7047
|
+
* filtering by sessionId) only include observations that have the attribute set.
|
|
7048
|
+
* If you call `propagateAttributes` late in your workflow, earlier spans won't be
|
|
7049
|
+
* included in aggregations for that attribute.
|
|
7050
|
+
*
|
|
7051
|
+
* @param params - Configuration for attributes to propagate
|
|
7052
|
+
* @param fn - Callback function (sync or async) within which attributes are propagated
|
|
7053
|
+
* @returns The result of the callback function
|
|
7054
|
+
*
|
|
7055
|
+
* @example
|
|
7056
|
+
* Basic usage with user and session tracking:
|
|
7057
|
+
*
|
|
7058
|
+
* ```typescript
|
|
7059
|
+
* import { startActiveObservation, propagateAttributes } from '@langfuse/tracing';
|
|
7060
|
+
*
|
|
7061
|
+
* // Set attributes early in the trace
|
|
7062
|
+
* await startActiveObservation('user_workflow', async (span) => {
|
|
7063
|
+
* await propagateAttributes({
|
|
7064
|
+
* userId: 'user_123',
|
|
7065
|
+
* sessionId: 'session_abc',
|
|
7066
|
+
* metadata: { experiment: 'variant_a', environment: 'production' }
|
|
7067
|
+
* }, async () => {
|
|
7068
|
+
* // All spans created here will have userId, sessionId, and metadata
|
|
7069
|
+
* const llmSpan = startObservation('llm_call', { input: 'Hello' });
|
|
7070
|
+
* // This span inherits: userId, sessionId, experiment, environment
|
|
7071
|
+
* llmSpan.end();
|
|
7072
|
+
*
|
|
7073
|
+
* const gen = startObservation('completion', {}, { asType: 'generation' });
|
|
7074
|
+
* // This span also inherits all attributes
|
|
7075
|
+
* gen.end();
|
|
7076
|
+
* });
|
|
7077
|
+
* });
|
|
7078
|
+
* ```
|
|
7079
|
+
*
|
|
7080
|
+
* @example
|
|
7081
|
+
* Late propagation (anti-pattern):
|
|
7082
|
+
*
|
|
7083
|
+
* ```typescript
|
|
7084
|
+
* await startActiveObservation('workflow', async (span) => {
|
|
7085
|
+
* // These spans WON'T have userId
|
|
7086
|
+
* const earlySpan = startObservation('early_work', { input: 'data' });
|
|
7087
|
+
* earlySpan.end();
|
|
7088
|
+
*
|
|
7089
|
+
* // Set attributes in the middle
|
|
7090
|
+
* await propagateAttributes({ userId: 'user_123' }, async () => {
|
|
7091
|
+
* // Only spans created AFTER this point will have userId
|
|
7092
|
+
* const lateSpan = startObservation('late_work', { input: 'more' });
|
|
7093
|
+
* lateSpan.end();
|
|
7094
|
+
* });
|
|
7095
|
+
*
|
|
7096
|
+
* // Result: Aggregations by userId will miss "early_work" span
|
|
7097
|
+
* });
|
|
7098
|
+
* ```
|
|
7099
|
+
*
|
|
7100
|
+
* @example
|
|
7101
|
+
* Cross-service propagation with baggage (advanced):
|
|
7102
|
+
*
|
|
7103
|
+
* ```typescript
|
|
7104
|
+
* import fetch from 'node-fetch';
|
|
7105
|
+
*
|
|
7106
|
+
* // Service A - originating service
|
|
7107
|
+
* await startActiveObservation('api_request', async () => {
|
|
7108
|
+
* await propagateAttributes({
|
|
7109
|
+
* userId: 'user_123',
|
|
7110
|
+
* sessionId: 'session_abc',
|
|
7111
|
+
* asBaggage: true // Propagate via HTTP headers
|
|
7112
|
+
* }, async () => {
|
|
7113
|
+
* // Make HTTP request to Service B
|
|
7114
|
+
* const response = await fetch('https://service-b.example.com/api');
|
|
7115
|
+
* // userId and sessionId are now in HTTP headers
|
|
7116
|
+
* });
|
|
7117
|
+
* });
|
|
7118
|
+
*
|
|
7119
|
+
* // Service B - downstream service
|
|
7120
|
+
* // OpenTelemetry will automatically extract baggage from HTTP headers
|
|
7121
|
+
* // and propagate to spans in Service B
|
|
7122
|
+
* ```
|
|
7123
|
+
*
|
|
7124
|
+
* @remarks
|
|
7125
|
+
* - **Validation**: All attribute values (userId, sessionId, metadata values)
|
|
7126
|
+
* must be strings ≤200 characters. Invalid values will be dropped with a
|
|
7127
|
+
* warning logged. Ensure values meet constraints before calling.
|
|
7128
|
+
* - **OpenTelemetry**: This uses OpenTelemetry context propagation under the hood,
|
|
7129
|
+
* making it compatible with other OTel-instrumented libraries.
|
|
7130
|
+
* - **Baggage Security**: When `asBaggage=true`, attribute values are added to HTTP
|
|
7131
|
+
* headers on outbound requests. Only use for non-sensitive values and when you
|
|
7132
|
+
* need cross-service tracing.
|
|
7133
|
+
*
|
|
7134
|
+
* @public
|
|
7135
|
+
*/
|
|
7136
|
+
declare function propagateAttributes<A extends unknown[], F extends (...args: A) => ReturnType<F>>(params: PropagateAttributesParams, fn: F): ReturnType<F>;
|
|
7137
|
+
declare function getPropagatedAttributesFromContext(context: Context): Record<string, string | string[]>;
|
|
7138
|
+
|
|
7139
|
+
export { AccessDeniedError, type AnnotationQueue, type AnnotationQueueAssignmentRequest, type AnnotationQueueItem, AnnotationQueueObjectType, AnnotationQueueStatus, type ApiKeyDeletionResponse, type ApiKeyList, type ApiKeyResponse, type ApiKeySummary, type AuthenticationScheme, type BaseEvent, type BasePrompt, type BaseScore, type BaseScoreV1, BlobStorageExportFrequency, BlobStorageExportMode, type BlobStorageIntegrationDeletionResponse, BlobStorageIntegrationFileType, type BlobStorageIntegrationResponse, BlobStorageIntegrationType, type BlobStorageIntegrationsResponse, type BooleanScore, type BooleanScoreV1, type BulkConfig, type CategoricalScore, type CategoricalScoreV1, type ChatMessage, ChatMessageWithPlaceholders, type ChatPrompt, type Comment, CommentObjectType, type ConfigCategory, type CreateAnnotationQueueAssignmentResponse, type CreateAnnotationQueueItemRequest, type CreateAnnotationQueueRequest, type CreateApiKeyRequest, type CreateBlobStorageIntegrationRequest, type CreateChatPromptRequest, type CreateCommentRequest, type CreateCommentResponse, type CreateDatasetItemRequest, type CreateDatasetRequest, type CreateDatasetRunItemRequest, type CreateEventBody, type CreateEventEvent, type CreateGenerationBody, type CreateGenerationEvent, type CreateModelRequest, type CreateObservationEvent, type CreateProjectRequest, CreatePromptRequest, type CreateScoreConfigRequest, type CreateScoreRequest, type CreateScoreResponse, type CreateScoreValue, type CreateSpanBody, type CreateSpanEvent, type CreateTextPromptRequest, type CreateUserRequest, type Dataset, type DatasetItem, type DatasetRun, type DatasetRunItem, type DatasetRunWithItems, DatasetStatus, type DeleteAnnotationQueueAssignmentResponse, type DeleteAnnotationQueueItemResponse, type DeleteDatasetItemResponse, type DeleteDatasetRunResponse, type DeleteMembershipRequest, type DeleteTraceResponse, type DeleteTracesRequest, type EmptyResponse, Error$1 as Error, type FilterConfig, type GetAnnotationQueueItemsRequest, type GetAnnotationQueuesRequest, type GetCommentsRequest, type GetCommentsResponse, type GetDatasetItemsRequest, type GetDatasetRunsRequest, type GetDatasetsRequest, type GetLlmConnectionsRequest, type GetMediaResponse, type GetMediaUploadUrlRequest, type GetMediaUploadUrlResponse, type GetMetricsRequest, type GetModelsRequest, type GetObservationsRequest, type GetPromptRequest, type GetScoreConfigsRequest, type GetScoresRequest, type GetScoresResponse, GetScoresResponseData, type GetScoresResponseDataBoolean, type GetScoresResponseDataCategorical, type GetScoresResponseDataNumeric, type GetScoresResponseTraceData, type GetSessionsRequest, type GetTracesRequest, type HealthResponse, type IngestionError, IngestionEvent, type IngestionRequest, type IngestionResponse, type IngestionSuccess, type IngestionUsage, LANGFUSE_SDK_EXPERIMENT_ENVIRONMENT, LANGFUSE_SDK_NAME, LANGFUSE_SDK_VERSION, LANGFUSE_TRACER_NAME, LangfuseAPIClient, LangfuseAPIError, LangfuseAPITimeoutError, LangfuseMedia, type LangfuseMediaParams, LangfuseOtelContextKeys, LangfuseOtelSpanAttributes, type ListDatasetRunItemsRequest, type ListPromptsMetaRequest, type ListUsersRequest, LlmAdapter, type LlmConnection, LogLevel, Logger, type LoggerConfig, type MapValue, MediaContentType, type MembershipDeletionResponse, type MembershipRequest, type MembershipResponse, MembershipRole, type MembershipsResponse, MethodNotAllowedError, type MetricsResponse, type Model, type ModelPrice, ModelUsageUnit, NotFoundError, type NumericScore, type NumericScoreV1, type Observation, type ObservationBody, ObservationLevel, ObservationType, type Observations$1 as Observations, type ObservationsView, type ObservationsViews, type OpenAiCompletionUsageSchema, type OpenAiResponseUsageSchema, type OpenAiUsage, type OptionalObservationBody, type OrganizationProject, type OrganizationProjectsResponse, type OtelAttribute, type OtelAttributeValue, type OtelResource, type OtelResourceSpan, type OtelScope, type OtelScopeSpan, type OtelSpan, type OtelTraceRequest, type OtelTraceResponse, type PaginatedAnnotationQueueItems, type PaginatedAnnotationQueues, type PaginatedDatasetItems, type PaginatedDatasetRunItems, type PaginatedDatasetRuns, type PaginatedDatasets, type PaginatedLlmConnections, type PaginatedModels, type PaginatedSessions, type ParsedMediaReference, type PatchMediaBody, type PlaceholderMessage, type Project, type ProjectDeletionResponse, type Projects$1 as Projects, Prompt, type PromptMeta, type PromptMetaListResponse, PromptType, type PropagateAttributesParams, type ResourceMeta, type ResourceType, type ResourceTypesResponse, type SchemaExtension, type SchemaResource, type SchemasResponse, type ScimEmail, type ScimFeatureSupport, type ScimName, type ScimUser, type ScimUsersListResponse, Score$1 as Score, type ScoreBody, type ScoreConfig, type ScoreConfigs$1 as ScoreConfigs, ScoreDataType, type ScoreEvent, ScoreSource, ScoreV1, type SdkLogBody, type SdkLogEvent, type ServiceProviderConfig, ServiceUnavailableError, type Session, type SessionWithTraces, type Sort, type TextPrompt, type Trace$1 as Trace, type TraceBody, type TraceEvent, type TraceWithDetails, type TraceWithFullDetails, type Traces, UnauthorizedError, type UpdateAnnotationQueueItemRequest, type UpdateEventBody, type UpdateGenerationBody, type UpdateGenerationEvent, type UpdateObservationEvent, type UpdateProjectRequest, type UpdatePromptRequest, type UpdateScoreConfigRequest, type UpdateSpanBody, type UpdateSpanEvent, type UpsertLlmConnectionRequest, type Usage, type UsageDetails, type UserMeta, index$q as annotationQueues, base64Decode, base64Encode, base64ToBytes, index$p as blobStorageIntegrations, bytesToBase64, index$o as comments, index$n as commons, configureGlobalLogger, createExperimentId, createExperimentItemId, createLogger, index$m as datasetItems, index$l as datasetRunItems, index$k as datasets, generateUUID, getEnv, getGlobalLogger, getPropagatedAttributesFromContext, index$j as health, index$i as ingestion, index$h as llmConnections, LoggerSingleton as logger, index$g as media, index$f as metrics, index$e as models, index$d as observations, index$c as opentelemetry, index$b as organizations, index$a as projects, index as promptVersion, index$9 as prompts, propagateAttributes, resetGlobalLogger, safeSetTimeout, index$8 as scim, index$5 as score, index$7 as scoreConfigs, index$6 as scoreV2, serializeValue, index$4 as sessions, index$3 as trace, index$1 as utils };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { Context } from '@opentelemetry/api';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Enumeration of log levels in order of severity (lowest to highest).
|
|
3
5
|
*/
|
|
@@ -179,6 +181,7 @@ declare const resetGlobalLogger: () => void;
|
|
|
179
181
|
declare const LANGFUSE_TRACER_NAME = "langfuse-sdk";
|
|
180
182
|
declare const LANGFUSE_SDK_VERSION: string;
|
|
181
183
|
declare const LANGFUSE_SDK_NAME = "javascript";
|
|
184
|
+
declare const LANGFUSE_SDK_EXPERIMENT_ENVIRONMENT = "sdk-experiment";
|
|
182
185
|
declare enum LangfuseOtelSpanAttributes {
|
|
183
186
|
TRACE_NAME = "langfuse.trace.name",
|
|
184
187
|
TRACE_USER_ID = "user.id",
|
|
@@ -205,6 +208,15 @@ declare enum LangfuseOtelSpanAttributes {
|
|
|
205
208
|
RELEASE = "langfuse.release",
|
|
206
209
|
VERSION = "langfuse.version",
|
|
207
210
|
AS_ROOT = "langfuse.internal.as_root",
|
|
211
|
+
EXPERIMENT_ID = "langfuse.experiment.id",
|
|
212
|
+
EXPERIMENT_NAME = "langfuse.experiment.name",
|
|
213
|
+
EXPERIMENT_DESCRIPTION = "langfuse.experiment.description",
|
|
214
|
+
EXPERIMENT_METADATA = "langfuse.experiment.metadata",
|
|
215
|
+
EXPERIMENT_DATASET_ID = "langfuse.experiment.dataset.id",
|
|
216
|
+
EXPERIMENT_ITEM_ID = "langfuse.experiment.item.id",
|
|
217
|
+
EXPERIMENT_ITEM_EXPECTED_OUTPUT = "langfuse.experiment.item.expected_output",
|
|
218
|
+
EXPERIMENT_ITEM_METADATA = "langfuse.experiment.item.metadata",
|
|
219
|
+
EXPERIMENT_ITEM_ROOT_OBSERVATION_ID = "langfuse.experiment.item.root_observation_id",
|
|
208
220
|
TRACE_COMPAT_USER_ID = "langfuse.user.id",
|
|
209
221
|
TRACE_COMPAT_SESSION_ID = "langfuse.session.id"
|
|
210
222
|
}
|
|
@@ -6770,6 +6782,23 @@ declare function base64ToBytes(base64: string): Uint8Array;
|
|
|
6770
6782
|
declare function bytesToBase64(bytes: Uint8Array): string;
|
|
6771
6783
|
declare function base64Encode(input: string): string;
|
|
6772
6784
|
declare function base64Decode(input: string): string;
|
|
6785
|
+
/**
|
|
6786
|
+
* Generate a random experiment ID (16 hex characters from 8 random bytes).
|
|
6787
|
+
* @internal
|
|
6788
|
+
*/
|
|
6789
|
+
declare function createExperimentId(): Promise<string>;
|
|
6790
|
+
/**
|
|
6791
|
+
* Generate experiment item ID from input hash (first 16 hex chars of SHA-256).
|
|
6792
|
+
* Skips serialization if input is already a string.
|
|
6793
|
+
* @internal
|
|
6794
|
+
*/
|
|
6795
|
+
declare function createExperimentItemId(input: any): Promise<string>;
|
|
6796
|
+
/**
|
|
6797
|
+
* Serialize a value to JSON string, handling undefined/null.
|
|
6798
|
+
* Skips serialization if value is already a string.
|
|
6799
|
+
* @internal
|
|
6800
|
+
*/
|
|
6801
|
+
declare function serializeValue(value: any): string | undefined;
|
|
6773
6802
|
|
|
6774
6803
|
type ParsedMediaReference = {
|
|
6775
6804
|
mediaId: string;
|
|
@@ -6925,4 +6954,186 @@ declare class LangfuseMedia {
|
|
|
6925
6954
|
toJSON(): string | null;
|
|
6926
6955
|
}
|
|
6927
6956
|
|
|
6928
|
-
|
|
6957
|
+
/**
|
|
6958
|
+
* Attribute propagation utilities for Langfuse OpenTelemetry integration.
|
|
6959
|
+
*
|
|
6960
|
+
* This module provides the `propagateAttributes` function for setting trace-level
|
|
6961
|
+
* attributes (userId, sessionId, metadata) that automatically propagate to all child spans
|
|
6962
|
+
* within the context.
|
|
6963
|
+
*/
|
|
6964
|
+
|
|
6965
|
+
type CorrelatedKey = "userId" | "sessionId" | "metadata" | "version" | "tags";
|
|
6966
|
+
declare const experimentKeys: readonly ["experimentId", "experimentName", "experimentMetadata", "experimentDatasetId", "experimentItemId", "experimentItemMetadata", "experimentItemRootObservationId"];
|
|
6967
|
+
type ExperimentKey = (typeof experimentKeys)[number];
|
|
6968
|
+
type PropagatedKey = CorrelatedKey | ExperimentKey;
|
|
6969
|
+
type PropagatedExperimentAttributes = {
|
|
6970
|
+
experimentId: string;
|
|
6971
|
+
experimentName: string;
|
|
6972
|
+
experimentMetadata?: string;
|
|
6973
|
+
experimentDatasetId?: string;
|
|
6974
|
+
experimentItemId: string;
|
|
6975
|
+
experimentItemMetadata?: string;
|
|
6976
|
+
experimentItemRootObservationId: string;
|
|
6977
|
+
};
|
|
6978
|
+
declare const LangfuseOtelContextKeys: Record<PropagatedKey, symbol>;
|
|
6979
|
+
/**
|
|
6980
|
+
* Parameters for propagateAttributes function.
|
|
6981
|
+
*
|
|
6982
|
+
* @public
|
|
6983
|
+
*/
|
|
6984
|
+
interface PropagateAttributesParams {
|
|
6985
|
+
/**
|
|
6986
|
+
* User identifier to associate with all spans in this context.
|
|
6987
|
+
* Must be a string ≤200 characters. Use this to track which user
|
|
6988
|
+
* generated each trace and enable e.g. per-user cost/performance analysis.
|
|
6989
|
+
*/
|
|
6990
|
+
userId?: string;
|
|
6991
|
+
/**
|
|
6992
|
+
* Session identifier to associate with all spans in this context.
|
|
6993
|
+
* Must be a string ≤200 characters. Use this to group related traces
|
|
6994
|
+
* within a user session (e.g., a conversation thread, multi-turn interaction).
|
|
6995
|
+
*/
|
|
6996
|
+
sessionId?: string;
|
|
6997
|
+
/**
|
|
6998
|
+
* Additional key-value metadata to propagate to all spans.
|
|
6999
|
+
* - Keys and values must be strings
|
|
7000
|
+
* - All values must be ≤200 characters
|
|
7001
|
+
* - Use for dimensions like internal correlating identifiers
|
|
7002
|
+
* - AVOID: large payloads, sensitive data, non-string values (will be dropped with warning)
|
|
7003
|
+
*/
|
|
7004
|
+
metadata?: Record<string, string>;
|
|
7005
|
+
/**
|
|
7006
|
+
* Version identifier for parts of your application that are independently versioned, e.g. agents
|
|
7007
|
+
*/
|
|
7008
|
+
version?: string;
|
|
7009
|
+
/**
|
|
7010
|
+
* List of tags to categorize the group of observations
|
|
7011
|
+
*/
|
|
7012
|
+
tags?: string[];
|
|
7013
|
+
/**
|
|
7014
|
+
* If true, propagates attributes using OpenTelemetry baggage for
|
|
7015
|
+
* cross-process/service propagation.
|
|
7016
|
+
*
|
|
7017
|
+
* **Security warning**: When enabled, attribute values are added to HTTP headers
|
|
7018
|
+
* on ALL outbound requests. Only enable if values are safe to transmit via HTTP
|
|
7019
|
+
* headers and you need cross-service tracing.
|
|
7020
|
+
*
|
|
7021
|
+
* @defaultValue false
|
|
7022
|
+
*/
|
|
7023
|
+
asBaggage?: boolean;
|
|
7024
|
+
/**
|
|
7025
|
+
* **INTERNAL USE ONLY** - For Langfuse experiment framework.
|
|
7026
|
+
*
|
|
7027
|
+
* This parameter is used internally by the Langfuse experiment system to propagate
|
|
7028
|
+
* experiment context to child spans. It should NOT be used by external code.
|
|
7029
|
+
*
|
|
7030
|
+
* @internal
|
|
7031
|
+
*/
|
|
7032
|
+
_internalExperiment?: PropagatedExperimentAttributes;
|
|
7033
|
+
}
|
|
7034
|
+
/**
|
|
7035
|
+
* Propagate trace-level attributes to all spans created within this context.
|
|
7036
|
+
*
|
|
7037
|
+
* This function sets attributes on the currently active span AND automatically
|
|
7038
|
+
* propagates them to all new child spans created within the callback. This is the
|
|
7039
|
+
* recommended way to set trace-level attributes like userId, sessionId, and metadata
|
|
7040
|
+
* dimensions that should be consistently applied across all observations in a trace.
|
|
7041
|
+
*
|
|
7042
|
+
* **IMPORTANT**: Call this as early as possible within your trace/workflow. Only the
|
|
7043
|
+
* currently active span and spans created after entering this context will have these
|
|
7044
|
+
* attributes. Pre-existing spans will NOT be retroactively updated.
|
|
7045
|
+
*
|
|
7046
|
+
* **Why this matters**: Langfuse aggregation queries (e.g., total cost by userId,
|
|
7047
|
+
* filtering by sessionId) only include observations that have the attribute set.
|
|
7048
|
+
* If you call `propagateAttributes` late in your workflow, earlier spans won't be
|
|
7049
|
+
* included in aggregations for that attribute.
|
|
7050
|
+
*
|
|
7051
|
+
* @param params - Configuration for attributes to propagate
|
|
7052
|
+
* @param fn - Callback function (sync or async) within which attributes are propagated
|
|
7053
|
+
* @returns The result of the callback function
|
|
7054
|
+
*
|
|
7055
|
+
* @example
|
|
7056
|
+
* Basic usage with user and session tracking:
|
|
7057
|
+
*
|
|
7058
|
+
* ```typescript
|
|
7059
|
+
* import { startActiveObservation, propagateAttributes } from '@langfuse/tracing';
|
|
7060
|
+
*
|
|
7061
|
+
* // Set attributes early in the trace
|
|
7062
|
+
* await startActiveObservation('user_workflow', async (span) => {
|
|
7063
|
+
* await propagateAttributes({
|
|
7064
|
+
* userId: 'user_123',
|
|
7065
|
+
* sessionId: 'session_abc',
|
|
7066
|
+
* metadata: { experiment: 'variant_a', environment: 'production' }
|
|
7067
|
+
* }, async () => {
|
|
7068
|
+
* // All spans created here will have userId, sessionId, and metadata
|
|
7069
|
+
* const llmSpan = startObservation('llm_call', { input: 'Hello' });
|
|
7070
|
+
* // This span inherits: userId, sessionId, experiment, environment
|
|
7071
|
+
* llmSpan.end();
|
|
7072
|
+
*
|
|
7073
|
+
* const gen = startObservation('completion', {}, { asType: 'generation' });
|
|
7074
|
+
* // This span also inherits all attributes
|
|
7075
|
+
* gen.end();
|
|
7076
|
+
* });
|
|
7077
|
+
* });
|
|
7078
|
+
* ```
|
|
7079
|
+
*
|
|
7080
|
+
* @example
|
|
7081
|
+
* Late propagation (anti-pattern):
|
|
7082
|
+
*
|
|
7083
|
+
* ```typescript
|
|
7084
|
+
* await startActiveObservation('workflow', async (span) => {
|
|
7085
|
+
* // These spans WON'T have userId
|
|
7086
|
+
* const earlySpan = startObservation('early_work', { input: 'data' });
|
|
7087
|
+
* earlySpan.end();
|
|
7088
|
+
*
|
|
7089
|
+
* // Set attributes in the middle
|
|
7090
|
+
* await propagateAttributes({ userId: 'user_123' }, async () => {
|
|
7091
|
+
* // Only spans created AFTER this point will have userId
|
|
7092
|
+
* const lateSpan = startObservation('late_work', { input: 'more' });
|
|
7093
|
+
* lateSpan.end();
|
|
7094
|
+
* });
|
|
7095
|
+
*
|
|
7096
|
+
* // Result: Aggregations by userId will miss "early_work" span
|
|
7097
|
+
* });
|
|
7098
|
+
* ```
|
|
7099
|
+
*
|
|
7100
|
+
* @example
|
|
7101
|
+
* Cross-service propagation with baggage (advanced):
|
|
7102
|
+
*
|
|
7103
|
+
* ```typescript
|
|
7104
|
+
* import fetch from 'node-fetch';
|
|
7105
|
+
*
|
|
7106
|
+
* // Service A - originating service
|
|
7107
|
+
* await startActiveObservation('api_request', async () => {
|
|
7108
|
+
* await propagateAttributes({
|
|
7109
|
+
* userId: 'user_123',
|
|
7110
|
+
* sessionId: 'session_abc',
|
|
7111
|
+
* asBaggage: true // Propagate via HTTP headers
|
|
7112
|
+
* }, async () => {
|
|
7113
|
+
* // Make HTTP request to Service B
|
|
7114
|
+
* const response = await fetch('https://service-b.example.com/api');
|
|
7115
|
+
* // userId and sessionId are now in HTTP headers
|
|
7116
|
+
* });
|
|
7117
|
+
* });
|
|
7118
|
+
*
|
|
7119
|
+
* // Service B - downstream service
|
|
7120
|
+
* // OpenTelemetry will automatically extract baggage from HTTP headers
|
|
7121
|
+
* // and propagate to spans in Service B
|
|
7122
|
+
* ```
|
|
7123
|
+
*
|
|
7124
|
+
* @remarks
|
|
7125
|
+
* - **Validation**: All attribute values (userId, sessionId, metadata values)
|
|
7126
|
+
* must be strings ≤200 characters. Invalid values will be dropped with a
|
|
7127
|
+
* warning logged. Ensure values meet constraints before calling.
|
|
7128
|
+
* - **OpenTelemetry**: This uses OpenTelemetry context propagation under the hood,
|
|
7129
|
+
* making it compatible with other OTel-instrumented libraries.
|
|
7130
|
+
* - **Baggage Security**: When `asBaggage=true`, attribute values are added to HTTP
|
|
7131
|
+
* headers on outbound requests. Only use for non-sensitive values and when you
|
|
7132
|
+
* need cross-service tracing.
|
|
7133
|
+
*
|
|
7134
|
+
* @public
|
|
7135
|
+
*/
|
|
7136
|
+
declare function propagateAttributes<A extends unknown[], F extends (...args: A) => ReturnType<F>>(params: PropagateAttributesParams, fn: F): ReturnType<F>;
|
|
7137
|
+
declare function getPropagatedAttributesFromContext(context: Context): Record<string, string | string[]>;
|
|
7138
|
+
|
|
7139
|
+
export { AccessDeniedError, type AnnotationQueue, type AnnotationQueueAssignmentRequest, type AnnotationQueueItem, AnnotationQueueObjectType, AnnotationQueueStatus, type ApiKeyDeletionResponse, type ApiKeyList, type ApiKeyResponse, type ApiKeySummary, type AuthenticationScheme, type BaseEvent, type BasePrompt, type BaseScore, type BaseScoreV1, BlobStorageExportFrequency, BlobStorageExportMode, type BlobStorageIntegrationDeletionResponse, BlobStorageIntegrationFileType, type BlobStorageIntegrationResponse, BlobStorageIntegrationType, type BlobStorageIntegrationsResponse, type BooleanScore, type BooleanScoreV1, type BulkConfig, type CategoricalScore, type CategoricalScoreV1, type ChatMessage, ChatMessageWithPlaceholders, type ChatPrompt, type Comment, CommentObjectType, type ConfigCategory, type CreateAnnotationQueueAssignmentResponse, type CreateAnnotationQueueItemRequest, type CreateAnnotationQueueRequest, type CreateApiKeyRequest, type CreateBlobStorageIntegrationRequest, type CreateChatPromptRequest, type CreateCommentRequest, type CreateCommentResponse, type CreateDatasetItemRequest, type CreateDatasetRequest, type CreateDatasetRunItemRequest, type CreateEventBody, type CreateEventEvent, type CreateGenerationBody, type CreateGenerationEvent, type CreateModelRequest, type CreateObservationEvent, type CreateProjectRequest, CreatePromptRequest, type CreateScoreConfigRequest, type CreateScoreRequest, type CreateScoreResponse, type CreateScoreValue, type CreateSpanBody, type CreateSpanEvent, type CreateTextPromptRequest, type CreateUserRequest, type Dataset, type DatasetItem, type DatasetRun, type DatasetRunItem, type DatasetRunWithItems, DatasetStatus, type DeleteAnnotationQueueAssignmentResponse, type DeleteAnnotationQueueItemResponse, type DeleteDatasetItemResponse, type DeleteDatasetRunResponse, type DeleteMembershipRequest, type DeleteTraceResponse, type DeleteTracesRequest, type EmptyResponse, Error$1 as Error, type FilterConfig, type GetAnnotationQueueItemsRequest, type GetAnnotationQueuesRequest, type GetCommentsRequest, type GetCommentsResponse, type GetDatasetItemsRequest, type GetDatasetRunsRequest, type GetDatasetsRequest, type GetLlmConnectionsRequest, type GetMediaResponse, type GetMediaUploadUrlRequest, type GetMediaUploadUrlResponse, type GetMetricsRequest, type GetModelsRequest, type GetObservationsRequest, type GetPromptRequest, type GetScoreConfigsRequest, type GetScoresRequest, type GetScoresResponse, GetScoresResponseData, type GetScoresResponseDataBoolean, type GetScoresResponseDataCategorical, type GetScoresResponseDataNumeric, type GetScoresResponseTraceData, type GetSessionsRequest, type GetTracesRequest, type HealthResponse, type IngestionError, IngestionEvent, type IngestionRequest, type IngestionResponse, type IngestionSuccess, type IngestionUsage, LANGFUSE_SDK_EXPERIMENT_ENVIRONMENT, LANGFUSE_SDK_NAME, LANGFUSE_SDK_VERSION, LANGFUSE_TRACER_NAME, LangfuseAPIClient, LangfuseAPIError, LangfuseAPITimeoutError, LangfuseMedia, type LangfuseMediaParams, LangfuseOtelContextKeys, LangfuseOtelSpanAttributes, type ListDatasetRunItemsRequest, type ListPromptsMetaRequest, type ListUsersRequest, LlmAdapter, type LlmConnection, LogLevel, Logger, type LoggerConfig, type MapValue, MediaContentType, type MembershipDeletionResponse, type MembershipRequest, type MembershipResponse, MembershipRole, type MembershipsResponse, MethodNotAllowedError, type MetricsResponse, type Model, type ModelPrice, ModelUsageUnit, NotFoundError, type NumericScore, type NumericScoreV1, type Observation, type ObservationBody, ObservationLevel, ObservationType, type Observations$1 as Observations, type ObservationsView, type ObservationsViews, type OpenAiCompletionUsageSchema, type OpenAiResponseUsageSchema, type OpenAiUsage, type OptionalObservationBody, type OrganizationProject, type OrganizationProjectsResponse, type OtelAttribute, type OtelAttributeValue, type OtelResource, type OtelResourceSpan, type OtelScope, type OtelScopeSpan, type OtelSpan, type OtelTraceRequest, type OtelTraceResponse, type PaginatedAnnotationQueueItems, type PaginatedAnnotationQueues, type PaginatedDatasetItems, type PaginatedDatasetRunItems, type PaginatedDatasetRuns, type PaginatedDatasets, type PaginatedLlmConnections, type PaginatedModels, type PaginatedSessions, type ParsedMediaReference, type PatchMediaBody, type PlaceholderMessage, type Project, type ProjectDeletionResponse, type Projects$1 as Projects, Prompt, type PromptMeta, type PromptMetaListResponse, PromptType, type PropagateAttributesParams, type ResourceMeta, type ResourceType, type ResourceTypesResponse, type SchemaExtension, type SchemaResource, type SchemasResponse, type ScimEmail, type ScimFeatureSupport, type ScimName, type ScimUser, type ScimUsersListResponse, Score$1 as Score, type ScoreBody, type ScoreConfig, type ScoreConfigs$1 as ScoreConfigs, ScoreDataType, type ScoreEvent, ScoreSource, ScoreV1, type SdkLogBody, type SdkLogEvent, type ServiceProviderConfig, ServiceUnavailableError, type Session, type SessionWithTraces, type Sort, type TextPrompt, type Trace$1 as Trace, type TraceBody, type TraceEvent, type TraceWithDetails, type TraceWithFullDetails, type Traces, UnauthorizedError, type UpdateAnnotationQueueItemRequest, type UpdateEventBody, type UpdateGenerationBody, type UpdateGenerationEvent, type UpdateObservationEvent, type UpdateProjectRequest, type UpdatePromptRequest, type UpdateScoreConfigRequest, type UpdateSpanBody, type UpdateSpanEvent, type UpsertLlmConnectionRequest, type Usage, type UsageDetails, type UserMeta, index$q as annotationQueues, base64Decode, base64Encode, base64ToBytes, index$p as blobStorageIntegrations, bytesToBase64, index$o as comments, index$n as commons, configureGlobalLogger, createExperimentId, createExperimentItemId, createLogger, index$m as datasetItems, index$l as datasetRunItems, index$k as datasets, generateUUID, getEnv, getGlobalLogger, getPropagatedAttributesFromContext, index$j as health, index$i as ingestion, index$h as llmConnections, LoggerSingleton as logger, index$g as media, index$f as metrics, index$e as models, index$d as observations, index$c as opentelemetry, index$b as organizations, index$a as projects, index as promptVersion, index$9 as prompts, propagateAttributes, resetGlobalLogger, safeSetTimeout, index$8 as scim, index$5 as score, index$7 as scoreConfigs, index$6 as scoreV2, serializeValue, index$4 as sessions, index$3 as trace, index$1 as utils };
|