@posthog/ai 6.6.0 → 7.1.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 CHANGED
@@ -26,7 +26,7 @@ function _interopNamespaceDefault(e) {
26
26
 
27
27
  var uuid__namespace = /*#__PURE__*/_interopNamespaceDefault(uuid);
28
28
 
29
- var version = "6.6.0";
29
+ var version = "7.1.0";
30
30
 
31
31
  // Type guards for safer type checking
32
32
  const isString = value => {
@@ -69,7 +69,7 @@ const getModelParams = params => {
69
69
  return {};
70
70
  }
71
71
  const modelParams = {};
72
- const paramKeys = ['temperature', 'max_tokens', 'max_completion_tokens', 'top_p', 'frequency_penalty', 'presence_penalty', 'n', 'stop', 'stream', 'streaming'];
72
+ const paramKeys = ['temperature', 'max_tokens', 'max_completion_tokens', 'top_p', 'frequency_penalty', 'presence_penalty', 'n', 'stop', 'stream', 'streaming', 'language', 'response_format', 'timestamp_granularities'];
73
73
  for (const key of paramKeys) {
74
74
  if (key in params && params[key] !== undefined) {
75
75
  modelParams[key] = params[key];
@@ -339,13 +339,14 @@ function calculateWebSearchCount(result) {
339
339
  return 1;
340
340
  }
341
341
  }
342
- // Check for annotations with url_citation in choices[].message (OpenAI/Perplexity)
342
+ // Check for annotations with url_citation in choices[].message or choices[].delta (OpenAI/Perplexity)
343
343
  if ('choices' in result && Array.isArray(result.choices)) {
344
344
  for (const choice of result.choices) {
345
- if (typeof choice === 'object' && choice !== null && 'message' in choice) {
346
- const message = choice.message;
347
- if (typeof message === 'object' && message !== null && 'annotations' in message) {
348
- const annotations = message.annotations;
345
+ if (typeof choice === 'object' && choice !== null) {
346
+ // Check both message (non-streaming) and delta (streaming) for annotations
347
+ const content = ('message' in choice ? choice.message : null) || ('delta' in choice ? choice.delta : null);
348
+ if (typeof content === 'object' && content !== null && 'annotations' in content) {
349
+ const annotations = content.annotations;
349
350
  if (Array.isArray(annotations)) {
350
351
  const hasUrlCitation = annotations.some(ann => {
351
352
  return typeof ann === 'object' && ann !== null && 'type' in ann && ann.type === 'url_citation';
@@ -795,6 +796,8 @@ const Chat = openai.OpenAI.Chat;
795
796
  const Completions = Chat.Completions;
796
797
  const Responses = openai.OpenAI.Responses;
797
798
  const Embeddings = openai.OpenAI.Embeddings;
799
+ const Audio = openai.OpenAI.Audio;
800
+ const Transcriptions = openai.OpenAI.Audio.Transcriptions;
798
801
  class PostHogOpenAI extends openai.OpenAI {
799
802
  constructor(config) {
800
803
  const {
@@ -806,6 +809,7 @@ class PostHogOpenAI extends openai.OpenAI {
806
809
  this.chat = new WrappedChat$1(this, this.phClient);
807
810
  this.responses = new WrappedResponses$1(this, this.phClient);
808
811
  this.embeddings = new WrappedEmbeddings$1(this, this.phClient);
812
+ this.audio = new WrappedAudio(this, this.phClient);
809
813
  }
810
814
  }
811
815
  let WrappedChat$1 = class WrappedChat extends Chat {
@@ -1302,6 +1306,139 @@ let WrappedEmbeddings$1 = class WrappedEmbeddings extends Embeddings {
1302
1306
  return wrappedPromise;
1303
1307
  }
1304
1308
  };
1309
+ class WrappedAudio extends Audio {
1310
+ constructor(parentClient, phClient) {
1311
+ super(parentClient);
1312
+ this.transcriptions = new WrappedTranscriptions(parentClient, phClient);
1313
+ }
1314
+ }
1315
+ class WrappedTranscriptions extends Transcriptions {
1316
+ constructor(client, phClient) {
1317
+ super(client);
1318
+ this.phClient = phClient;
1319
+ this.baseURL = client.baseURL;
1320
+ }
1321
+ // --- Implementation Signature
1322
+ create(body, options) {
1323
+ const {
1324
+ providerParams: openAIParams,
1325
+ posthogParams
1326
+ } = extractPosthogParams(body);
1327
+ const startTime = Date.now();
1328
+ const parentPromise = openAIParams.stream ? super.create(openAIParams, options) : super.create(openAIParams, options);
1329
+ if (openAIParams.stream) {
1330
+ return parentPromise.then(value => {
1331
+ if ('tee' in value && typeof value.tee === 'function') {
1332
+ const [stream1, stream2] = value.tee();
1333
+ (async () => {
1334
+ try {
1335
+ let finalContent = '';
1336
+ let usage = {
1337
+ inputTokens: 0,
1338
+ outputTokens: 0
1339
+ };
1340
+ const doneEvent = 'transcript.text.done';
1341
+ for await (const chunk of stream1) {
1342
+ if (chunk.type === doneEvent && 'text' in chunk && chunk.text && chunk.text.length > 0) {
1343
+ finalContent = chunk.text;
1344
+ }
1345
+ if ('usage' in chunk && chunk.usage) {
1346
+ usage = {
1347
+ inputTokens: chunk.usage?.type === 'tokens' ? chunk.usage.input_tokens ?? 0 : 0,
1348
+ outputTokens: chunk.usage?.type === 'tokens' ? chunk.usage.output_tokens ?? 0 : 0
1349
+ };
1350
+ }
1351
+ }
1352
+ const latency = (Date.now() - startTime) / 1000;
1353
+ const availableTools = extractAvailableToolCalls('openai', openAIParams);
1354
+ await sendEventToPosthog({
1355
+ client: this.phClient,
1356
+ ...posthogParams,
1357
+ model: openAIParams.model,
1358
+ provider: 'openai',
1359
+ input: openAIParams.prompt,
1360
+ output: finalContent,
1361
+ latency,
1362
+ baseURL: this.baseURL,
1363
+ params: body,
1364
+ httpStatus: 200,
1365
+ usage,
1366
+ tools: availableTools
1367
+ });
1368
+ } catch (error) {
1369
+ const httpStatus = error && typeof error === 'object' && 'status' in error ? error.status ?? 500 : 500;
1370
+ await sendEventToPosthog({
1371
+ client: this.phClient,
1372
+ ...posthogParams,
1373
+ model: openAIParams.model,
1374
+ provider: 'openai',
1375
+ input: openAIParams.prompt,
1376
+ output: [],
1377
+ latency: 0,
1378
+ baseURL: this.baseURL,
1379
+ params: body,
1380
+ httpStatus,
1381
+ usage: {
1382
+ inputTokens: 0,
1383
+ outputTokens: 0
1384
+ },
1385
+ isError: true,
1386
+ error: JSON.stringify(error)
1387
+ });
1388
+ }
1389
+ })();
1390
+ return stream2;
1391
+ }
1392
+ return value;
1393
+ });
1394
+ } else {
1395
+ const wrappedPromise = parentPromise.then(async result => {
1396
+ if ('text' in result) {
1397
+ const latency = (Date.now() - startTime) / 1000;
1398
+ await sendEventToPosthog({
1399
+ client: this.phClient,
1400
+ ...posthogParams,
1401
+ model: String(openAIParams.model ?? ''),
1402
+ provider: 'openai',
1403
+ input: openAIParams.prompt,
1404
+ output: result.text,
1405
+ latency,
1406
+ baseURL: this.baseURL,
1407
+ params: body,
1408
+ httpStatus: 200,
1409
+ usage: {
1410
+ inputTokens: result.usage?.type === 'tokens' ? result.usage.input_tokens ?? 0 : 0,
1411
+ outputTokens: result.usage?.type === 'tokens' ? result.usage.output_tokens ?? 0 : 0
1412
+ }
1413
+ });
1414
+ return result;
1415
+ }
1416
+ }, async error => {
1417
+ const httpStatus = error && typeof error === 'object' && 'status' in error ? error.status ?? 500 : 500;
1418
+ await sendEventToPosthog({
1419
+ client: this.phClient,
1420
+ ...posthogParams,
1421
+ model: String(openAIParams.model ?? ''),
1422
+ provider: 'openai',
1423
+ input: openAIParams.prompt,
1424
+ output: [],
1425
+ latency: 0,
1426
+ baseURL: this.baseURL,
1427
+ params: body,
1428
+ httpStatus,
1429
+ usage: {
1430
+ inputTokens: 0,
1431
+ outputTokens: 0
1432
+ },
1433
+ isError: true,
1434
+ error: JSON.stringify(error)
1435
+ });
1436
+ throw error;
1437
+ });
1438
+ return wrappedPromise;
1439
+ }
1440
+ }
1441
+ }
1305
1442
 
1306
1443
  class PostHogAzureOpenAI extends openai.AzureOpenAI {
1307
1444
  constructor(config) {
@@ -2842,6 +2979,15 @@ function calculateGoogleWebSearchCount(response) {
2842
2979
  return hasGrounding ? 1 : 0;
2843
2980
  }
2844
2981
 
2982
+ //#region rolldown:runtime
2983
+ var __defProp = Object.defineProperty;
2984
+ var __export = (target, all) => {
2985
+ for (var name in all) __defProp(target, name, {
2986
+ get: all[name],
2987
+ enumerable: true
2988
+ });
2989
+ };
2990
+
2845
2991
  function getDefaultExportFromCjs (x) {
2846
2992
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
2847
2993
  }
@@ -2994,370 +3140,304 @@ function requireCamelcase () {
2994
3140
 
2995
3141
  requireCamelcase();
2996
3142
 
3143
+ //#region src/load/map_keys.ts
2997
3144
  function keyToJson(key, map) {
2998
- return map?.[key] || snakeCase(key);
3145
+ return map?.[key] || snakeCase(key);
2999
3146
  }
3000
3147
  function mapKeys(fields, mapper, map) {
3001
- const mapped = {};
3002
- for (const key in fields) {
3003
- if (Object.hasOwn(fields, key)) {
3004
- mapped[mapper(key, map)] = fields[key];
3005
- }
3006
- }
3007
- return mapped;
3148
+ const mapped = {};
3149
+ for (const key in fields) if (Object.hasOwn(fields, key)) mapped[mapper(key, map)] = fields[key];
3150
+ return mapped;
3008
3151
  }
3009
3152
 
3153
+ //#region src/load/serializable.ts
3154
+ var serializable_exports = {};
3155
+ __export(serializable_exports, {
3156
+ Serializable: () => Serializable,
3157
+ get_lc_unique_name: () => get_lc_unique_name
3158
+ });
3010
3159
  function shallowCopy(obj) {
3011
- return Array.isArray(obj) ? [...obj] : { ...obj };
3160
+ return Array.isArray(obj) ? [...obj] : { ...obj };
3012
3161
  }
3013
3162
  function replaceSecrets(root, secretsMap) {
3014
- const result = shallowCopy(root);
3015
- for (const [path, secretId] of Object.entries(secretsMap)) {
3016
- const [last, ...partsReverse] = path.split(".").reverse();
3017
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3018
- let current = result;
3019
- for (const part of partsReverse.reverse()) {
3020
- if (current[part] === undefined) {
3021
- break;
3022
- }
3023
- current[part] = shallowCopy(current[part]);
3024
- current = current[part];
3025
- }
3026
- if (current[last] !== undefined) {
3027
- current[last] = {
3028
- lc: 1,
3029
- type: "secret",
3030
- id: [secretId],
3031
- };
3032
- }
3033
- }
3034
- return result;
3163
+ const result = shallowCopy(root);
3164
+ for (const [path, secretId] of Object.entries(secretsMap)) {
3165
+ const [last, ...partsReverse] = path.split(".").reverse();
3166
+ let current = result;
3167
+ for (const part of partsReverse.reverse()) {
3168
+ if (current[part] === void 0) break;
3169
+ current[part] = shallowCopy(current[part]);
3170
+ current = current[part];
3171
+ }
3172
+ if (current[last] !== void 0) current[last] = {
3173
+ lc: 1,
3174
+ type: "secret",
3175
+ id: [secretId]
3176
+ };
3177
+ }
3178
+ return result;
3035
3179
  }
3036
3180
  /**
3037
- * Get a unique name for the module, rather than parent class implementations.
3038
- * Should not be subclassed, subclass lc_name above instead.
3039
- */
3040
- function get_lc_unique_name(
3041
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
3042
- serializableClass) {
3043
- // "super" here would refer to the parent class of Serializable,
3044
- // when we want the parent class of the module actually calling this method.
3045
- const parentClass = Object.getPrototypeOf(serializableClass);
3046
- const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" &&
3047
- (typeof parentClass.lc_name !== "function" ||
3048
- serializableClass.lc_name() !== parentClass.lc_name());
3049
- if (lcNameIsSubclassed) {
3050
- return serializableClass.lc_name();
3051
- }
3052
- else {
3053
- return serializableClass.name;
3054
- }
3055
- }
3056
- class Serializable {
3057
- /**
3058
- * The name of the serializable. Override to provide an alias or
3059
- * to preserve the serialized module name in minified environments.
3060
- *
3061
- * Implemented as a static method to support loading logic.
3062
- */
3063
- static lc_name() {
3064
- return this.name;
3065
- }
3066
- /**
3067
- * The final serialized identifier for the module.
3068
- */
3069
- get lc_id() {
3070
- return [
3071
- ...this.lc_namespace,
3072
- get_lc_unique_name(this.constructor),
3073
- ];
3074
- }
3075
- /**
3076
- * A map of secrets, which will be omitted from serialization.
3077
- * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz".
3078
- * Values are the secret ids, which will be used when deserializing.
3079
- */
3080
- get lc_secrets() {
3081
- return undefined;
3082
- }
3083
- /**
3084
- * A map of additional attributes to merge with constructor args.
3085
- * Keys are the attribute names, e.g. "foo".
3086
- * Values are the attribute values, which will be serialized.
3087
- * These attributes need to be accepted by the constructor as arguments.
3088
- */
3089
- get lc_attributes() {
3090
- return undefined;
3091
- }
3092
- /**
3093
- * A map of aliases for constructor args.
3094
- * Keys are the attribute names, e.g. "foo".
3095
- * Values are the alias that will replace the key in serialization.
3096
- * This is used to eg. make argument names match Python.
3097
- */
3098
- get lc_aliases() {
3099
- return undefined;
3100
- }
3101
- /**
3102
- * A manual list of keys that should be serialized.
3103
- * If not overridden, all fields passed into the constructor will be serialized.
3104
- */
3105
- get lc_serializable_keys() {
3106
- return undefined;
3107
- }
3108
- constructor(kwargs, ..._args) {
3109
- Object.defineProperty(this, "lc_serializable", {
3110
- enumerable: true,
3111
- configurable: true,
3112
- writable: true,
3113
- value: false
3114
- });
3115
- Object.defineProperty(this, "lc_kwargs", {
3116
- enumerable: true,
3117
- configurable: true,
3118
- writable: true,
3119
- value: void 0
3120
- });
3121
- if (this.lc_serializable_keys !== undefined) {
3122
- this.lc_kwargs = Object.fromEntries(Object.entries(kwargs || {}).filter(([key]) => this.lc_serializable_keys?.includes(key)));
3123
- }
3124
- else {
3125
- this.lc_kwargs = kwargs ?? {};
3126
- }
3127
- }
3128
- toJSON() {
3129
- if (!this.lc_serializable) {
3130
- return this.toJSONNotImplemented();
3131
- }
3132
- if (
3133
- // eslint-disable-next-line no-instanceof/no-instanceof
3134
- this.lc_kwargs instanceof Serializable ||
3135
- typeof this.lc_kwargs !== "object" ||
3136
- Array.isArray(this.lc_kwargs)) {
3137
- // We do not support serialization of classes with arg not a POJO
3138
- // I'm aware the check above isn't as strict as it could be
3139
- return this.toJSONNotImplemented();
3140
- }
3141
- const aliases = {};
3142
- const secrets = {};
3143
- const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => {
3144
- acc[key] = key in this ? this[key] : this.lc_kwargs[key];
3145
- return acc;
3146
- }, {});
3147
- // get secrets, attributes and aliases from all superclasses
3148
- for (
3149
- // eslint-disable-next-line @typescript-eslint/no-this-alias
3150
- let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) {
3151
- Object.assign(aliases, Reflect.get(current, "lc_aliases", this));
3152
- Object.assign(secrets, Reflect.get(current, "lc_secrets", this));
3153
- Object.assign(kwargs, Reflect.get(current, "lc_attributes", this));
3154
- }
3155
- // include all secrets used, even if not in kwargs,
3156
- // will be replaced with sentinel value in replaceSecrets
3157
- Object.keys(secrets).forEach((keyPath) => {
3158
- // eslint-disable-next-line @typescript-eslint/no-this-alias, @typescript-eslint/no-explicit-any
3159
- let read = this;
3160
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3161
- let write = kwargs;
3162
- const [last, ...partsReverse] = keyPath.split(".").reverse();
3163
- for (const key of partsReverse.reverse()) {
3164
- if (!(key in read) || read[key] === undefined)
3165
- return;
3166
- if (!(key in write) || write[key] === undefined) {
3167
- if (typeof read[key] === "object" && read[key] != null) {
3168
- write[key] = {};
3169
- }
3170
- else if (Array.isArray(read[key])) {
3171
- write[key] = [];
3172
- }
3173
- }
3174
- read = read[key];
3175
- write = write[key];
3176
- }
3177
- if (last in read && read[last] !== undefined) {
3178
- write[last] = write[last] || read[last];
3179
- }
3180
- });
3181
- return {
3182
- lc: 1,
3183
- type: "constructor",
3184
- id: this.lc_id,
3185
- kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases),
3186
- };
3187
- }
3188
- toJSONNotImplemented() {
3189
- return {
3190
- lc: 1,
3191
- type: "not_implemented",
3192
- id: this.lc_id,
3193
- };
3194
- }
3181
+ * Get a unique name for the module, rather than parent class implementations.
3182
+ * Should not be subclassed, subclass lc_name above instead.
3183
+ */
3184
+ function get_lc_unique_name(serializableClass) {
3185
+ const parentClass = Object.getPrototypeOf(serializableClass);
3186
+ const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && (typeof parentClass.lc_name !== "function" || serializableClass.lc_name() !== parentClass.lc_name());
3187
+ if (lcNameIsSubclassed) return serializableClass.lc_name();
3188
+ else return serializableClass.name;
3195
3189
  }
3190
+ var Serializable = class Serializable {
3191
+ lc_serializable = false;
3192
+ lc_kwargs;
3193
+ /**
3194
+ * The name of the serializable. Override to provide an alias or
3195
+ * to preserve the serialized module name in minified environments.
3196
+ *
3197
+ * Implemented as a static method to support loading logic.
3198
+ */
3199
+ static lc_name() {
3200
+ return this.name;
3201
+ }
3202
+ /**
3203
+ * The final serialized identifier for the module.
3204
+ */
3205
+ get lc_id() {
3206
+ return [...this.lc_namespace, get_lc_unique_name(this.constructor)];
3207
+ }
3208
+ /**
3209
+ * A map of secrets, which will be omitted from serialization.
3210
+ * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz".
3211
+ * Values are the secret ids, which will be used when deserializing.
3212
+ */
3213
+ get lc_secrets() {
3214
+ return void 0;
3215
+ }
3216
+ /**
3217
+ * A map of additional attributes to merge with constructor args.
3218
+ * Keys are the attribute names, e.g. "foo".
3219
+ * Values are the attribute values, which will be serialized.
3220
+ * These attributes need to be accepted by the constructor as arguments.
3221
+ */
3222
+ get lc_attributes() {
3223
+ return void 0;
3224
+ }
3225
+ /**
3226
+ * A map of aliases for constructor args.
3227
+ * Keys are the attribute names, e.g. "foo".
3228
+ * Values are the alias that will replace the key in serialization.
3229
+ * This is used to eg. make argument names match Python.
3230
+ */
3231
+ get lc_aliases() {
3232
+ return void 0;
3233
+ }
3234
+ /**
3235
+ * A manual list of keys that should be serialized.
3236
+ * If not overridden, all fields passed into the constructor will be serialized.
3237
+ */
3238
+ get lc_serializable_keys() {
3239
+ return void 0;
3240
+ }
3241
+ constructor(kwargs, ..._args) {
3242
+ if (this.lc_serializable_keys !== void 0) this.lc_kwargs = Object.fromEntries(Object.entries(kwargs || {}).filter(([key]) => this.lc_serializable_keys?.includes(key)));
3243
+ else this.lc_kwargs = kwargs ?? {};
3244
+ }
3245
+ toJSON() {
3246
+ if (!this.lc_serializable) return this.toJSONNotImplemented();
3247
+ if (this.lc_kwargs instanceof Serializable || typeof this.lc_kwargs !== "object" || Array.isArray(this.lc_kwargs)) return this.toJSONNotImplemented();
3248
+ const aliases = {};
3249
+ const secrets = {};
3250
+ const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => {
3251
+ acc[key] = key in this ? this[key] : this.lc_kwargs[key];
3252
+ return acc;
3253
+ }, {});
3254
+ for (let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) {
3255
+ Object.assign(aliases, Reflect.get(current, "lc_aliases", this));
3256
+ Object.assign(secrets, Reflect.get(current, "lc_secrets", this));
3257
+ Object.assign(kwargs, Reflect.get(current, "lc_attributes", this));
3258
+ }
3259
+ Object.keys(secrets).forEach((keyPath) => {
3260
+ let read = this;
3261
+ let write = kwargs;
3262
+ const [last, ...partsReverse] = keyPath.split(".").reverse();
3263
+ for (const key of partsReverse.reverse()) {
3264
+ if (!(key in read) || read[key] === void 0) return;
3265
+ if (!(key in write) || write[key] === void 0) {
3266
+ if (typeof read[key] === "object" && read[key] != null) write[key] = {};
3267
+ else if (Array.isArray(read[key])) write[key] = [];
3268
+ }
3269
+ read = read[key];
3270
+ write = write[key];
3271
+ }
3272
+ if (last in read && read[last] !== void 0) write[last] = write[last] || read[last];
3273
+ });
3274
+ return {
3275
+ lc: 1,
3276
+ type: "constructor",
3277
+ id: this.lc_id,
3278
+ kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases)
3279
+ };
3280
+ }
3281
+ toJSONNotImplemented() {
3282
+ return {
3283
+ lc: 1,
3284
+ type: "not_implemented",
3285
+ id: this.lc_id
3286
+ };
3287
+ }
3288
+ };
3196
3289
 
3197
- // Supabase Edge Function provides a `Deno` global object
3198
- // without `version` property
3290
+ //#region src/utils/env.ts
3291
+ var env_exports = {};
3292
+ __export(env_exports, {
3293
+ getEnv: () => getEnv,
3294
+ getEnvironmentVariable: () => getEnvironmentVariable,
3295
+ getRuntimeEnvironment: () => getRuntimeEnvironment,
3296
+ isBrowser: () => isBrowser,
3297
+ isDeno: () => isDeno,
3298
+ isJsDom: () => isJsDom,
3299
+ isNode: () => isNode,
3300
+ isWebWorker: () => isWebWorker
3301
+ });
3302
+ const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
3303
+ const isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope";
3304
+ const isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom");
3199
3305
  const isDeno = () => typeof Deno !== "undefined";
3306
+ const isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno();
3307
+ const getEnv = () => {
3308
+ let env;
3309
+ if (isBrowser()) env = "browser";
3310
+ else if (isNode()) env = "node";
3311
+ else if (isWebWorker()) env = "webworker";
3312
+ else if (isJsDom()) env = "jsdom";
3313
+ else if (isDeno()) env = "deno";
3314
+ else env = "other";
3315
+ return env;
3316
+ };
3317
+ let runtimeEnvironment;
3318
+ function getRuntimeEnvironment() {
3319
+ if (runtimeEnvironment === void 0) {
3320
+ const env = getEnv();
3321
+ runtimeEnvironment = {
3322
+ library: "langchain-js",
3323
+ runtime: env
3324
+ };
3325
+ }
3326
+ return runtimeEnvironment;
3327
+ }
3200
3328
  function getEnvironmentVariable(name) {
3201
- // Certain Deno setups will throw an error if you try to access environment variables
3202
- // https://github.com/langchain-ai/langchainjs/issues/1412
3203
- try {
3204
- if (typeof process !== "undefined") {
3205
- // eslint-disable-next-line no-process-env
3206
- return process.env?.[name];
3207
- }
3208
- else if (isDeno()) {
3209
- return Deno?.env.get(name);
3210
- }
3211
- else {
3212
- return undefined;
3213
- }
3214
- }
3215
- catch (e) {
3216
- return undefined;
3217
- }
3329
+ try {
3330
+ if (typeof process !== "undefined") return process.env?.[name];
3331
+ else if (isDeno()) return Deno?.env.get(name);
3332
+ else return void 0;
3333
+ } catch {
3334
+ return void 0;
3335
+ }
3218
3336
  }
3219
3337
 
3338
+ //#region src/callbacks/base.ts
3339
+ var base_exports = {};
3340
+ __export(base_exports, {
3341
+ BaseCallbackHandler: () => BaseCallbackHandler,
3342
+ callbackHandlerPrefersStreaming: () => callbackHandlerPrefersStreaming,
3343
+ isBaseCallbackHandler: () => isBaseCallbackHandler
3344
+ });
3220
3345
  /**
3221
- * Abstract class that provides a set of optional methods that can be
3222
- * overridden in derived classes to handle various events during the
3223
- * execution of a LangChain application.
3224
- */
3225
- class BaseCallbackHandlerMethodsClass {
3346
+ * Abstract class that provides a set of optional methods that can be
3347
+ * overridden in derived classes to handle various events during the
3348
+ * execution of a LangChain application.
3349
+ */
3350
+ var BaseCallbackHandlerMethodsClass = class {};
3351
+ function callbackHandlerPrefersStreaming(x) {
3352
+ return "lc_prefer_streaming" in x && x.lc_prefer_streaming;
3226
3353
  }
3227
3354
  /**
3228
- * Abstract base class for creating callback handlers in the LangChain
3229
- * framework. It provides a set of optional methods that can be overridden
3230
- * in derived classes to handle various events during the execution of a
3231
- * LangChain application.
3232
- */
3233
- class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass {
3234
- get lc_namespace() {
3235
- return ["langchain_core", "callbacks", this.name];
3236
- }
3237
- get lc_secrets() {
3238
- return undefined;
3239
- }
3240
- get lc_attributes() {
3241
- return undefined;
3242
- }
3243
- get lc_aliases() {
3244
- return undefined;
3245
- }
3246
- get lc_serializable_keys() {
3247
- return undefined;
3248
- }
3249
- /**
3250
- * The name of the serializable. Override to provide an alias or
3251
- * to preserve the serialized module name in minified environments.
3252
- *
3253
- * Implemented as a static method to support loading logic.
3254
- */
3255
- static lc_name() {
3256
- return this.name;
3257
- }
3258
- /**
3259
- * The final serialized identifier for the module.
3260
- */
3261
- get lc_id() {
3262
- return [
3263
- ...this.lc_namespace,
3264
- get_lc_unique_name(this.constructor),
3265
- ];
3266
- }
3267
- constructor(input) {
3268
- super();
3269
- Object.defineProperty(this, "lc_serializable", {
3270
- enumerable: true,
3271
- configurable: true,
3272
- writable: true,
3273
- value: false
3274
- });
3275
- Object.defineProperty(this, "lc_kwargs", {
3276
- enumerable: true,
3277
- configurable: true,
3278
- writable: true,
3279
- value: void 0
3280
- });
3281
- Object.defineProperty(this, "ignoreLLM", {
3282
- enumerable: true,
3283
- configurable: true,
3284
- writable: true,
3285
- value: false
3286
- });
3287
- Object.defineProperty(this, "ignoreChain", {
3288
- enumerable: true,
3289
- configurable: true,
3290
- writable: true,
3291
- value: false
3292
- });
3293
- Object.defineProperty(this, "ignoreAgent", {
3294
- enumerable: true,
3295
- configurable: true,
3296
- writable: true,
3297
- value: false
3298
- });
3299
- Object.defineProperty(this, "ignoreRetriever", {
3300
- enumerable: true,
3301
- configurable: true,
3302
- writable: true,
3303
- value: false
3304
- });
3305
- Object.defineProperty(this, "ignoreCustomEvent", {
3306
- enumerable: true,
3307
- configurable: true,
3308
- writable: true,
3309
- value: false
3310
- });
3311
- Object.defineProperty(this, "raiseError", {
3312
- enumerable: true,
3313
- configurable: true,
3314
- writable: true,
3315
- value: false
3316
- });
3317
- Object.defineProperty(this, "awaitHandlers", {
3318
- enumerable: true,
3319
- configurable: true,
3320
- writable: true,
3321
- value: getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false"
3322
- });
3323
- this.lc_kwargs = input || {};
3324
- if (input) {
3325
- this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM;
3326
- this.ignoreChain = input.ignoreChain ?? this.ignoreChain;
3327
- this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent;
3328
- this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever;
3329
- this.ignoreCustomEvent =
3330
- input.ignoreCustomEvent ?? this.ignoreCustomEvent;
3331
- this.raiseError = input.raiseError ?? this.raiseError;
3332
- this.awaitHandlers =
3333
- this.raiseError || (input._awaitHandler ?? this.awaitHandlers);
3334
- }
3335
- }
3336
- copy() {
3337
- return new this.constructor(this);
3338
- }
3339
- toJSON() {
3340
- return Serializable.prototype.toJSON.call(this);
3341
- }
3342
- toJSONNotImplemented() {
3343
- return Serializable.prototype.toJSONNotImplemented.call(this);
3344
- }
3345
- static fromMethods(methods) {
3346
- class Handler extends BaseCallbackHandler {
3347
- constructor() {
3348
- super();
3349
- Object.defineProperty(this, "name", {
3350
- enumerable: true,
3351
- configurable: true,
3352
- writable: true,
3353
- value: uuid__namespace.v4()
3354
- });
3355
- Object.assign(this, methods);
3356
- }
3357
- }
3358
- return new Handler();
3359
- }
3360
- }
3355
+ * Abstract base class for creating callback handlers in the LangChain
3356
+ * framework. It provides a set of optional methods that can be overridden
3357
+ * in derived classes to handle various events during the execution of a
3358
+ * LangChain application.
3359
+ */
3360
+ var BaseCallbackHandler = class extends BaseCallbackHandlerMethodsClass {
3361
+ lc_serializable = false;
3362
+ get lc_namespace() {
3363
+ return [
3364
+ "langchain_core",
3365
+ "callbacks",
3366
+ this.name
3367
+ ];
3368
+ }
3369
+ get lc_secrets() {
3370
+ return void 0;
3371
+ }
3372
+ get lc_attributes() {
3373
+ return void 0;
3374
+ }
3375
+ get lc_aliases() {
3376
+ return void 0;
3377
+ }
3378
+ get lc_serializable_keys() {
3379
+ return void 0;
3380
+ }
3381
+ /**
3382
+ * The name of the serializable. Override to provide an alias or
3383
+ * to preserve the serialized module name in minified environments.
3384
+ *
3385
+ * Implemented as a static method to support loading logic.
3386
+ */
3387
+ static lc_name() {
3388
+ return this.name;
3389
+ }
3390
+ /**
3391
+ * The final serialized identifier for the module.
3392
+ */
3393
+ get lc_id() {
3394
+ return [...this.lc_namespace, get_lc_unique_name(this.constructor)];
3395
+ }
3396
+ lc_kwargs;
3397
+ ignoreLLM = false;
3398
+ ignoreChain = false;
3399
+ ignoreAgent = false;
3400
+ ignoreRetriever = false;
3401
+ ignoreCustomEvent = false;
3402
+ raiseError = false;
3403
+ awaitHandlers = getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false";
3404
+ constructor(input) {
3405
+ super();
3406
+ this.lc_kwargs = input || {};
3407
+ if (input) {
3408
+ this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM;
3409
+ this.ignoreChain = input.ignoreChain ?? this.ignoreChain;
3410
+ this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent;
3411
+ this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever;
3412
+ this.ignoreCustomEvent = input.ignoreCustomEvent ?? this.ignoreCustomEvent;
3413
+ this.raiseError = input.raiseError ?? this.raiseError;
3414
+ this.awaitHandlers = this.raiseError || (input._awaitHandler ?? this.awaitHandlers);
3415
+ }
3416
+ }
3417
+ copy() {
3418
+ return new this.constructor(this);
3419
+ }
3420
+ toJSON() {
3421
+ return Serializable.prototype.toJSON.call(this);
3422
+ }
3423
+ toJSONNotImplemented() {
3424
+ return Serializable.prototype.toJSONNotImplemented.call(this);
3425
+ }
3426
+ static fromMethods(methods) {
3427
+ class Handler extends BaseCallbackHandler {
3428
+ name = uuid__namespace.v4();
3429
+ constructor() {
3430
+ super();
3431
+ Object.assign(this, methods);
3432
+ }
3433
+ }
3434
+ return new Handler();
3435
+ }
3436
+ };
3437
+ const isBaseCallbackHandler = (x) => {
3438
+ const callbackHandler = x;
3439
+ return callbackHandler !== void 0 && typeof callbackHandler.copy === "function" && typeof callbackHandler.name === "string" && typeof callbackHandler.awaitHandlers === "boolean";
3440
+ };
3361
3441
 
3362
3442
  class LangChainCallbackHandler extends BaseCallbackHandler {
3363
3443
  constructor(options) {