@posthog/ai 7.3.1 → 7.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.
@@ -1,7 +1,8 @@
1
1
  import 'buffer';
2
2
  import * as uuid from 'uuid';
3
+ import '@posthog/core';
3
4
 
4
- var version = "7.3.1";
5
+ var version = "7.4.0";
5
6
 
6
7
  // Type guards for safer type checking
7
8
 
@@ -225,6 +226,64 @@ function mapKeys(fields, mapper, map) {
225
226
  return mapped;
226
227
  }
227
228
 
229
+ //#region src/load/validation.ts
230
+ /**
231
+ * Sentinel key used to mark escaped user objects during serialization.
232
+ *
233
+ * When a plain object contains 'lc' key (which could be confused with LC objects),
234
+ * we wrap it as `{"__lc_escaped__": {...original...}}`.
235
+ */
236
+ const LC_ESCAPED_KEY = "__lc_escaped__";
237
+ /**
238
+ * Check if an object needs escaping to prevent confusion with LC objects.
239
+ *
240
+ * An object needs escaping if:
241
+ * 1. It has an `'lc'` key (could be confused with LC serialization format)
242
+ * 2. It has only the escape key (would be mistaken for an escaped object)
243
+ */
244
+ function needsEscaping(obj) {
245
+ return "lc" in obj || Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj;
246
+ }
247
+ /**
248
+ * Wrap an object in the escape marker.
249
+ *
250
+ * @example
251
+ * ```typescript
252
+ * {"key": "value"} // becomes {"__lc_escaped__": {"key": "value"}}
253
+ * ```
254
+ */
255
+ function escapeObject(obj) {
256
+ return { [LC_ESCAPED_KEY]: obj };
257
+ }
258
+ /**
259
+ * Check if an object looks like a Serializable instance (duck typing).
260
+ */
261
+ function isSerializableLike(obj) {
262
+ return obj !== null && typeof obj === "object" && "lc_serializable" in obj && typeof obj.toJSON === "function";
263
+ }
264
+ /**
265
+ * Escape a value if it needs escaping (contains `lc` key).
266
+ *
267
+ * This is a simpler version of `serializeValue` that doesn't handle Serializable
268
+ * objects - it's meant to be called on kwargs values that have already been
269
+ * processed by `toJSON()`.
270
+ *
271
+ * @param value - The value to potentially escape.
272
+ * @returns The value with any `lc`-containing objects wrapped in escape markers.
273
+ */
274
+ function escapeIfNeeded(value) {
275
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
276
+ if (isSerializableLike(value)) return value;
277
+ const record = value;
278
+ if (needsEscaping(record)) return escapeObject(record);
279
+ const result = {};
280
+ for (const [key, val] of Object.entries(record)) result[key] = escapeIfNeeded(val);
281
+ return result;
282
+ }
283
+ if (Array.isArray(value)) return value.map((item) => escapeIfNeeded(item));
284
+ return value;
285
+ }
286
+
228
287
  //#region src/load/serializable.ts
229
288
  var serializable_exports = {};
230
289
  __export(serializable_exports, {
@@ -346,11 +405,15 @@ var Serializable = class Serializable {
346
405
  }
347
406
  if (last in read && read[last] !== void 0) write[last] = write[last] || read[last];
348
407
  });
408
+ const escapedKwargs = {};
409
+ for (const [key, value] of Object.entries(kwargs)) escapedKwargs[key] = escapeIfNeeded(value);
410
+ const kwargsWithSecrets = Object.keys(secrets).length ? replaceSecrets(escapedKwargs, secrets) : escapedKwargs;
411
+ const processedKwargs = mapKeys(kwargsWithSecrets, keyToJson, aliases);
349
412
  return {
350
413
  lc: 1,
351
414
  type: "constructor",
352
415
  id: this.lc_id,
353
- kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases)
416
+ kwargs: processedKwargs
354
417
  };
355
418
  }
356
419
  toJSONNotImplemented() {
@@ -950,7 +1013,10 @@ class LangChainCallbackHandler extends BaseCallbackHandler {
950
1013
 
951
1014
  // Add additional token data to properties
952
1015
  if (additionalTokenData.cacheReadInputTokens) {
953
- eventProperties['$ai_cache_read_tokens'] = additionalTokenData.cacheReadInputTokens;
1016
+ eventProperties['$ai_cache_read_input_tokens'] = additionalTokenData.cacheReadInputTokens;
1017
+ }
1018
+ if (additionalTokenData.cacheWriteInputTokens) {
1019
+ eventProperties['$ai_cache_creation_input_tokens'] = additionalTokenData.cacheWriteInputTokens;
954
1020
  }
955
1021
  if (additionalTokenData.reasoningTokens) {
956
1022
  eventProperties['$ai_reasoning_tokens'] = additionalTokenData.reasoningTokens;
@@ -1118,6 +1184,15 @@ class LangChainCallbackHandler extends BaseCallbackHandler {
1118
1184
  additionalTokenData.cacheReadInputTokens = usage.input_token_details.cache_read;
1119
1185
  } else if (usage.cachedPromptTokens != null) {
1120
1186
  additionalTokenData.cacheReadInputTokens = usage.cachedPromptTokens;
1187
+ } else if (usage.cache_read_input_tokens != null) {
1188
+ additionalTokenData.cacheReadInputTokens = usage.cache_read_input_tokens;
1189
+ }
1190
+
1191
+ // Check for cache write/creation tokens in various formats
1192
+ if (usage.cache_creation_input_tokens != null) {
1193
+ additionalTokenData.cacheWriteInputTokens = usage.cache_creation_input_tokens;
1194
+ } else if (usage.input_token_details?.cache_creation != null) {
1195
+ additionalTokenData.cacheWriteInputTokens = usage.input_token_details.cache_creation;
1121
1196
  }
1122
1197
 
1123
1198
  // Check for reasoning tokens in various formats
@@ -1167,8 +1242,10 @@ class LangChainCallbackHandler extends BaseCallbackHandler {
1167
1242
  additionalTokenData.webSearchCount = webSearchCount;
1168
1243
  }
1169
1244
 
1170
- // For Anthropic providers, LangChain reports input_tokens as the sum of input and cache read tokens.
1245
+ // For Anthropic providers, LangChain reports input_tokens as the sum of all input tokens.
1171
1246
  // Our cost calculation expects them to be separate for Anthropic, so we subtract cache tokens.
1247
+ // Both cache_read and cache_write tokens should be subtracted since Anthropic's raw API
1248
+ // reports input_tokens as tokens NOT read from or used to create a cache.
1172
1249
  // For other providers (OpenAI, etc.), input_tokens already excludes cache tokens as expected.
1173
1250
  // Match logic consistent with plugin-server: exact match on provider OR substring match on model
1174
1251
  let isAnthropic = false;
@@ -1177,8 +1254,11 @@ class LangChainCallbackHandler extends BaseCallbackHandler {
1177
1254
  } else if (model && model.toLowerCase().includes('anthropic')) {
1178
1255
  isAnthropic = true;
1179
1256
  }
1180
- if (isAnthropic && parsedUsage.input && additionalTokenData.cacheReadInputTokens) {
1181
- parsedUsage.input = Math.max(parsedUsage.input - additionalTokenData.cacheReadInputTokens, 0);
1257
+ if (isAnthropic && parsedUsage.input) {
1258
+ const cacheTokens = (additionalTokenData.cacheReadInputTokens || 0) + (additionalTokenData.cacheWriteInputTokens || 0);
1259
+ if (cacheTokens > 0) {
1260
+ parsedUsage.input = Math.max(parsedUsage.input - cacheTokens, 0);
1261
+ }
1182
1262
  }
1183
1263
  return [parsedUsage.input, parsedUsage.output, additionalTokenData];
1184
1264
  }