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