@posthog/ai 7.9.5 → 7.11.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,14 @@ declare class Prompts {
397
403
  private defaultCacheTtlSeconds;
398
404
  private cache;
399
405
  constructor(options: PromptsOptions);
406
+ private getPromptCache;
407
+ private getOrCreatePromptCache;
408
+ private getPromptLabel;
400
409
  /**
401
410
  * Fetch a prompt by name from the PostHog API
402
411
  *
403
412
  * @param name - The name of the prompt to fetch
404
- * @param options - Optional settings for caching and fallback
413
+ * @param options - Optional settings for caching, fallback, and exact version selection
405
414
  * @returns The prompt string
406
415
  * @throws Error if the prompt cannot be fetched and no fallback is provided
407
416
  */
@@ -420,9 +429,10 @@ declare class Prompts {
420
429
  /**
421
430
  * Clear the cache for a specific prompt or all prompts
422
431
  *
423
- * @param name - Optional prompt name to clear. If not provided, clears all cached prompts.
432
+ * @param name - Optional prompt name to clear. If provided, clears all cached versions for that prompt unless a version is also provided.
433
+ * @param version - Optional prompt version to clear. Requires a prompt name.
424
434
  */
425
- clearCache(name?: string): void;
435
+ clearCache(name?: string, version?: number): void;
426
436
  private fetchPromptFromApi;
427
437
  }
428
438
 
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.5";
8
+ var version = "7.11.0";
9
9
 
10
10
  // Type guards for safer type checking
11
11
  const isString = value => {
@@ -5162,6 +5162,11 @@ function isPromptsWithPostHog(options) {
5162
5162
  * fallback: 'You are a helpful assistant.',
5163
5163
  * })
5164
5164
  *
5165
+ * // Or fetch an exact published version
5166
+ * const v3Template = await prompts.get('support-system-prompt', {
5167
+ * version: 3,
5168
+ * })
5169
+ *
5165
5170
  * // Compile with variables
5166
5171
  * const systemPrompt = prompts.compile(template, {
5167
5172
  * company: 'Acme Corp',
@@ -5184,19 +5189,36 @@ class Prompts {
5184
5189
  this.host = options.host ?? 'https://us.posthog.com';
5185
5190
  }
5186
5191
  }
5192
+ getPromptCache(name) {
5193
+ return this.cache.get(name);
5194
+ }
5195
+ getOrCreatePromptCache(name) {
5196
+ const cachedPromptVersions = this.cache.get(name);
5197
+ if (cachedPromptVersions) {
5198
+ return cachedPromptVersions;
5199
+ }
5200
+ const promptVersions = new Map();
5201
+ this.cache.set(name, promptVersions);
5202
+ return promptVersions;
5203
+ }
5204
+ getPromptLabel(name, version) {
5205
+ return version === undefined ? `"${name}"` : `"${name}" version ${version}`;
5206
+ }
5187
5207
  /**
5188
5208
  * Fetch a prompt by name from the PostHog API
5189
5209
  *
5190
5210
  * @param name - The name of the prompt to fetch
5191
- * @param options - Optional settings for caching and fallback
5211
+ * @param options - Optional settings for caching, fallback, and exact version selection
5192
5212
  * @returns The prompt string
5193
5213
  * @throws Error if the prompt cannot be fetched and no fallback is provided
5194
5214
  */
5195
5215
  async get(name, options) {
5196
5216
  const cacheTtlSeconds = options?.cacheTtlSeconds ?? this.defaultCacheTtlSeconds;
5197
5217
  const fallback = options?.fallback;
5218
+ const version = options?.version;
5219
+ const promptLabel = this.getPromptLabel(name, version);
5198
5220
  // Check cache first
5199
- const cached = this.cache.get(name);
5221
+ const cached = this.getPromptCache(name)?.get(version);
5200
5222
  const now = Date.now();
5201
5223
  if (cached) {
5202
5224
  const isFresh = now - cached.fetchedAt < cacheTtlSeconds * 1000;
@@ -5206,10 +5228,10 @@ class Prompts {
5206
5228
  }
5207
5229
  // Try to fetch from API
5208
5230
  try {
5209
- const prompt = await this.fetchPromptFromApi(name);
5231
+ const prompt = await this.fetchPromptFromApi(name, version);
5210
5232
  const fetchedAt = Date.now();
5211
5233
  // Update cache
5212
- this.cache.set(name, {
5234
+ this.getOrCreatePromptCache(name).set(version, {
5213
5235
  prompt,
5214
5236
  fetchedAt
5215
5237
  });
@@ -5218,12 +5240,12 @@ class Prompts {
5218
5240
  // Fallback order:
5219
5241
  // 1. Return stale cache (with warning)
5220
5242
  if (cached) {
5221
- console.warn(`[PostHog Prompts] Failed to fetch prompt "${name}", using stale cache:`, error);
5243
+ console.warn(`[PostHog Prompts] Failed to fetch prompt ${promptLabel}, using stale cache:`, error);
5222
5244
  return cached.prompt;
5223
5245
  }
5224
5246
  // 2. Return fallback (with warning)
5225
5247
  if (fallback !== undefined) {
5226
- console.warn(`[PostHog Prompts] Failed to fetch prompt "${name}", using fallback:`, error);
5248
+ console.warn(`[PostHog Prompts] Failed to fetch prompt ${promptLabel}, using fallback:`, error);
5227
5249
  return fallback;
5228
5250
  }
5229
5251
  // 3. Throw error
@@ -5251,16 +5273,28 @@ class Prompts {
5251
5273
  /**
5252
5274
  * Clear the cache for a specific prompt or all prompts
5253
5275
  *
5254
- * @param name - Optional prompt name to clear. If not provided, clears all cached prompts.
5276
+ * @param name - Optional prompt name to clear. If provided, clears all cached versions for that prompt unless a version is also provided.
5277
+ * @param version - Optional prompt version to clear. Requires a prompt name.
5255
5278
  */
5256
- clearCache(name) {
5257
- if (name !== undefined) {
5258
- this.cache.delete(name);
5259
- } else {
5279
+ clearCache(name, version) {
5280
+ if (version !== undefined && name === undefined) {
5281
+ throw new Error("'version' requires 'name' to be provided");
5282
+ }
5283
+ if (name === undefined) {
5260
5284
  this.cache.clear();
5285
+ return;
5286
+ }
5287
+ if (version === undefined) {
5288
+ this.cache.delete(name);
5289
+ return;
5290
+ }
5291
+ const promptVersions = this.getPromptCache(name);
5292
+ promptVersions?.delete(version);
5293
+ if (promptVersions?.size === 0) {
5294
+ this.cache.delete(name);
5261
5295
  }
5262
5296
  }
5263
- async fetchPromptFromApi(name) {
5297
+ async fetchPromptFromApi(name, version) {
5264
5298
  if (!this.personalApiKey) {
5265
5299
  throw new Error('[PostHog Prompts] personalApiKey is required to fetch prompts. ' + 'Please provide it when initializing the Prompts instance.');
5266
5300
  }
@@ -5269,7 +5303,9 @@ class Prompts {
5269
5303
  }
5270
5304
  const encodedPromptName = encodeURIComponent(name);
5271
5305
  const encodedProjectApiKey = encodeURIComponent(this.projectApiKey);
5272
- const url = `${this.host}/api/environments/@current/llm_prompts/name/${encodedPromptName}/?token=${encodedProjectApiKey}`;
5306
+ const versionQuery = version === undefined ? '' : `&version=${encodeURIComponent(String(version))}`;
5307
+ const promptLabel = this.getPromptLabel(name, version);
5308
+ const url = `${this.host}/api/environments/@current/llm_prompts/name/${encodedPromptName}/?token=${encodedProjectApiKey}${versionQuery}`;
5273
5309
  const response = await fetch(url, {
5274
5310
  method: 'GET',
5275
5311
  headers: {
@@ -5278,16 +5314,16 @@ class Prompts {
5278
5314
  });
5279
5315
  if (!response.ok) {
5280
5316
  if (response.status === 404) {
5281
- throw new Error(`[PostHog Prompts] Prompt "${name}" not found`);
5317
+ throw new Error(`[PostHog Prompts] Prompt ${promptLabel} not found`);
5282
5318
  }
5283
5319
  if (response.status === 403) {
5284
- 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.');
5320
+ 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.');
5285
5321
  }
5286
- throw new Error(`[PostHog Prompts] Failed to fetch prompt "${name}": HTTP ${response.status}`);
5322
+ throw new Error(`[PostHog Prompts] Failed to fetch prompt ${promptLabel}: HTTP ${response.status}`);
5287
5323
  }
5288
5324
  const data = await response.json();
5289
5325
  if (!isPromptApiResponse(data)) {
5290
- throw new Error(`[PostHog Prompts] Invalid response format for prompt "${name}"`);
5326
+ throw new Error(`[PostHog Prompts] Invalid response format for prompt ${promptLabel}`);
5291
5327
  }
5292
5328
  return data.prompt;
5293
5329
  }