@posthog/ai 7.9.4 → 7.10.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.d.ts CHANGED
@@ -23,6 +23,7 @@ import { BaseMessage } from '@langchain/core/messages';
23
23
  interface GetPromptOptions {
24
24
  cacheTtlSeconds?: number;
25
25
  fallback?: string;
26
+ version?: number;
26
27
  }
27
28
  /**
28
29
  * Variables for prompt compilation
@@ -383,6 +384,11 @@ type PromptsOptions = PromptsWithPostHogOptions | PromptsDirectOptions;
383
384
  * fallback: 'You are a helpful assistant.',
384
385
  * })
385
386
  *
387
+ * // Or fetch an exact published version
388
+ * const v3Template = await prompts.get('support-system-prompt', {
389
+ * version: 3,
390
+ * })
391
+ *
386
392
  * // Compile with variables
387
393
  * const systemPrompt = prompts.compile(template, {
388
394
  * company: 'Acme Corp',
@@ -397,11 +403,13 @@ declare class Prompts {
397
403
  private defaultCacheTtlSeconds;
398
404
  private cache;
399
405
  constructor(options: PromptsOptions);
406
+ private getCacheKey;
407
+ private getPromptLabel;
400
408
  /**
401
409
  * Fetch a prompt by name from the PostHog API
402
410
  *
403
411
  * @param name - The name of the prompt to fetch
404
- * @param options - Optional settings for caching and fallback
412
+ * @param options - Optional settings for caching, fallback, and exact version selection
405
413
  * @returns The prompt string
406
414
  * @throws Error if the prompt cannot be fetched and no fallback is provided
407
415
  */
@@ -420,7 +428,7 @@ declare class Prompts {
420
428
  /**
421
429
  * Clear the cache for a specific prompt or all prompts
422
430
  *
423
- * @param name - Optional prompt name to clear. If not provided, clears all cached prompts.
431
+ * @param name - Optional prompt name to clear. If provided, clears all cached versions for that prompt.
424
432
  */
425
433
  clearCache(name?: string): void;
426
434
  private fetchPromptFromApi;
package/dist/index.mjs CHANGED
@@ -5,7 +5,7 @@ import { uuidv7 } from '@posthog/core';
5
5
  import AnthropicOriginal from '@anthropic-ai/sdk';
6
6
  import { GoogleGenAI } from '@google/genai';
7
7
 
8
- var version = "7.9.4";
8
+ var version = "7.10.0";
9
9
 
10
10
  // Type guards for safer type checking
11
11
  const isString = value => {
@@ -99,6 +99,16 @@ const sanitizeOpenAIImage = item => {
99
99
  }
100
100
  };
101
101
  }
102
+ // Handle video_url format
103
+ if (item.type === 'video_url' && 'video_url' in item && isObject(item.video_url) && 'url' in item.video_url) {
104
+ return {
105
+ ...item,
106
+ video_url: {
107
+ ...item.video_url,
108
+ url: redactBase64DataUrl(item.video_url.url)
109
+ }
110
+ };
111
+ }
102
112
  // Handle audio format
103
113
  if (item.type === 'audio' && 'data' in item) {
104
114
  if (isMultimodalEnabled()) return item;
@@ -5152,6 +5162,11 @@ function isPromptsWithPostHog(options) {
5152
5162
  * fallback: 'You are a helpful assistant.',
5153
5163
  * })
5154
5164
  *
5165
+ * // Or fetch an exact published version
5166
+ * const v3Template = await prompts.get('support-system-prompt', {
5167
+ * version: 3,
5168
+ * })
5169
+ *
5155
5170
  * // Compile with variables
5156
5171
  * const systemPrompt = prompts.compile(template, {
5157
5172
  * company: 'Acme Corp',
@@ -5174,19 +5189,28 @@ class Prompts {
5174
5189
  this.host = options.host ?? 'https://us.posthog.com';
5175
5190
  }
5176
5191
  }
5192
+ getCacheKey(name, version) {
5193
+ return version === undefined ? `${name}::latest` : `${name}::version:${version}`;
5194
+ }
5195
+ getPromptLabel(name, version) {
5196
+ return version === undefined ? `"${name}"` : `"${name}" version ${version}`;
5197
+ }
5177
5198
  /**
5178
5199
  * Fetch a prompt by name from the PostHog API
5179
5200
  *
5180
5201
  * @param name - The name of the prompt to fetch
5181
- * @param options - Optional settings for caching and fallback
5202
+ * @param options - Optional settings for caching, fallback, and exact version selection
5182
5203
  * @returns The prompt string
5183
5204
  * @throws Error if the prompt cannot be fetched and no fallback is provided
5184
5205
  */
5185
5206
  async get(name, options) {
5186
5207
  const cacheTtlSeconds = options?.cacheTtlSeconds ?? this.defaultCacheTtlSeconds;
5187
5208
  const fallback = options?.fallback;
5209
+ const version = options?.version;
5210
+ const cacheKey = this.getCacheKey(name, version);
5211
+ const promptLabel = this.getPromptLabel(name, version);
5188
5212
  // Check cache first
5189
- const cached = this.cache.get(name);
5213
+ const cached = this.cache.get(cacheKey);
5190
5214
  const now = Date.now();
5191
5215
  if (cached) {
5192
5216
  const isFresh = now - cached.fetchedAt < cacheTtlSeconds * 1000;
@@ -5196,10 +5220,10 @@ class Prompts {
5196
5220
  }
5197
5221
  // Try to fetch from API
5198
5222
  try {
5199
- const prompt = await this.fetchPromptFromApi(name);
5223
+ const prompt = await this.fetchPromptFromApi(name, version);
5200
5224
  const fetchedAt = Date.now();
5201
5225
  // Update cache
5202
- this.cache.set(name, {
5226
+ this.cache.set(cacheKey, {
5203
5227
  prompt,
5204
5228
  fetchedAt
5205
5229
  });
@@ -5208,12 +5232,12 @@ class Prompts {
5208
5232
  // Fallback order:
5209
5233
  // 1. Return stale cache (with warning)
5210
5234
  if (cached) {
5211
- console.warn(`[PostHog Prompts] Failed to fetch prompt "${name}", using stale cache:`, error);
5235
+ console.warn(`[PostHog Prompts] Failed to fetch prompt ${promptLabel}, using stale cache:`, error);
5212
5236
  return cached.prompt;
5213
5237
  }
5214
5238
  // 2. Return fallback (with warning)
5215
5239
  if (fallback !== undefined) {
5216
- console.warn(`[PostHog Prompts] Failed to fetch prompt "${name}", using fallback:`, error);
5240
+ console.warn(`[PostHog Prompts] Failed to fetch prompt ${promptLabel}, using fallback:`, error);
5217
5241
  return fallback;
5218
5242
  }
5219
5243
  // 3. Throw error
@@ -5241,16 +5265,26 @@ class Prompts {
5241
5265
  /**
5242
5266
  * Clear the cache for a specific prompt or all prompts
5243
5267
  *
5244
- * @param name - Optional prompt name to clear. If not provided, clears all cached prompts.
5268
+ * @param name - Optional prompt name to clear. If provided, clears all cached versions for that prompt.
5245
5269
  */
5246
5270
  clearCache(name) {
5247
5271
  if (name !== undefined) {
5248
- this.cache.delete(name);
5272
+ const latestKey = this.getCacheKey(name);
5273
+ const versionPrefix = `${name}::version:`;
5274
+ for (const key of this.cache.keys()) {
5275
+ if (key === latestKey) {
5276
+ this.cache.delete(key);
5277
+ continue;
5278
+ }
5279
+ if (key.startsWith(versionPrefix) && /^\d+$/.test(key.slice(versionPrefix.length))) {
5280
+ this.cache.delete(key);
5281
+ }
5282
+ }
5249
5283
  } else {
5250
5284
  this.cache.clear();
5251
5285
  }
5252
5286
  }
5253
- async fetchPromptFromApi(name) {
5287
+ async fetchPromptFromApi(name, version) {
5254
5288
  if (!this.personalApiKey) {
5255
5289
  throw new Error('[PostHog Prompts] personalApiKey is required to fetch prompts. ' + 'Please provide it when initializing the Prompts instance.');
5256
5290
  }
@@ -5259,7 +5293,9 @@ class Prompts {
5259
5293
  }
5260
5294
  const encodedPromptName = encodeURIComponent(name);
5261
5295
  const encodedProjectApiKey = encodeURIComponent(this.projectApiKey);
5262
- const url = `${this.host}/api/environments/@current/llm_prompts/name/${encodedPromptName}/?token=${encodedProjectApiKey}`;
5296
+ const versionQuery = version === undefined ? '' : `&version=${encodeURIComponent(String(version))}`;
5297
+ const promptLabel = this.getPromptLabel(name, version);
5298
+ const url = `${this.host}/api/environments/@current/llm_prompts/name/${encodedPromptName}/?token=${encodedProjectApiKey}${versionQuery}`;
5263
5299
  const response = await fetch(url, {
5264
5300
  method: 'GET',
5265
5301
  headers: {
@@ -5268,16 +5304,16 @@ class Prompts {
5268
5304
  });
5269
5305
  if (!response.ok) {
5270
5306
  if (response.status === 404) {
5271
- throw new Error(`[PostHog Prompts] Prompt "${name}" not found`);
5307
+ throw new Error(`[PostHog Prompts] Prompt ${promptLabel} not found`);
5272
5308
  }
5273
5309
  if (response.status === 403) {
5274
- throw new Error(`[PostHog Prompts] Access denied for prompt "${name}". ` + 'Check that your personalApiKey has the correct permissions and the LLM prompts feature is enabled.');
5310
+ throw new Error(`[PostHog Prompts] Access denied for prompt ${promptLabel}. ` + 'Check that your personalApiKey has the correct permissions and the LLM prompts feature is enabled.');
5275
5311
  }
5276
- throw new Error(`[PostHog Prompts] Failed to fetch prompt "${name}": HTTP ${response.status}`);
5312
+ throw new Error(`[PostHog Prompts] Failed to fetch prompt ${promptLabel}: HTTP ${response.status}`);
5277
5313
  }
5278
5314
  const data = await response.json();
5279
5315
  if (!isPromptApiResponse(data)) {
5280
- throw new Error(`[PostHog Prompts] Invalid response format for prompt "${name}"`);
5316
+ throw new Error(`[PostHog Prompts] Invalid response format for prompt ${promptLabel}`);
5281
5317
  }
5282
5318
  return data.prompt;
5283
5319
  }