@posthog/ai 7.15.0 → 7.16.1

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
@@ -22,7 +22,42 @@ interface GetPromptOptions {
22
22
  cacheTtlSeconds?: number;
23
23
  fallback?: string;
24
24
  version?: number;
25
+ /**
26
+ * When true, returns a `PromptResult` object with metadata (source, name, version)
27
+ * instead of a plain string.
28
+ *
29
+ * Omitting this option or setting it to false is deprecated and will be removed
30
+ * in a future major version.
31
+ */
32
+ withMetadata?: boolean;
33
+ }
34
+ /**
35
+ * Result from the Prompts API or local cache — carries real metadata.
36
+ */
37
+ interface PromptRemoteResult {
38
+ source: 'api' | 'cache' | 'stale_cache';
39
+ prompt: string;
40
+ name: string;
41
+ version: number;
25
42
  }
43
+ /**
44
+ * Result when the fetch failed and no cache was available — fell back to the
45
+ * hardcoded fallback string. name and version are undefined so they remain
46
+ * accessible on the PromptResult union without a type guard.
47
+ */
48
+ interface PromptCodeFallbackResult {
49
+ source: 'code_fallback';
50
+ prompt: string;
51
+ name: undefined;
52
+ version: undefined;
53
+ }
54
+ /**
55
+ * Discriminated union returned by `Prompts.get()` when `withMetadata: true`.
56
+ *
57
+ * Narrow on `source` to guarantee metadata, or access `result.name` /
58
+ * `result.version` directly as `string | undefined` / `number | undefined`.
59
+ */
60
+ type PromptResult = PromptRemoteResult | PromptCodeFallbackResult;
26
61
  /**
27
62
  * Variables for prompt compilation
28
63
  */
@@ -340,19 +375,28 @@ declare class Prompts {
340
375
  private host;
341
376
  private defaultCacheTtlSeconds;
342
377
  private cache;
378
+ private hasWarnedDeprecation;
343
379
  constructor(options: PromptsOptions);
344
380
  private getPromptCache;
345
381
  private getOrCreatePromptCache;
346
382
  private getPromptLabel;
347
383
  /**
348
- * Fetch a prompt by name from the PostHog API
384
+ * Fetch a prompt by name from the PostHog API.
349
385
  *
350
- * @param name - The name of the prompt to fetch
351
- * @param options - Optional settings for caching, fallback, and exact version selection
352
- * @returns The prompt string
353
- * @throws Error if the prompt cannot be fetched and no fallback is provided
386
+ * When `withMetadata` is `true`, returns a `PromptResult` object with `source`,
387
+ * `name`, and `version` metadata. When omitted or `false`, returns a plain string
388
+ * (deprecated will be removed in a future major version).
354
389
  */
390
+ get(name: string, options: GetPromptOptions & {
391
+ withMetadata: true;
392
+ }): Promise<PromptResult>;
393
+ /** @deprecated Omitting `withMetadata` is deprecated. Pass `{ withMetadata: true }` to receive a `PromptResult`. */
355
394
  get(name: string, options?: GetPromptOptions): Promise<string>;
395
+ /**
396
+ * Internal method that handles cache + fetch logic, returning full metadata.
397
+ * Does NOT handle the string `fallback` option — callers handle that.
398
+ */
399
+ private getInternal;
356
400
  /**
357
401
  * Compile a prompt template with variable substitution
358
402
  *
@@ -374,4 +418,4 @@ declare class Prompts {
374
418
  private fetchPromptFromApi;
375
419
  }
376
420
 
377
- export { PostHogAnthropic as Anthropic, PostHogAzureOpenAI as AzureOpenAI, PostHogGoogleGenAI as GoogleGenAI, LangChainCallbackHandler, PostHogOpenAI as OpenAI, Prompts, wrapVercelLanguageModel as withTracing };
421
+ export { PostHogAnthropic as Anthropic, PostHogAzureOpenAI as AzureOpenAI, PostHogGoogleGenAI as GoogleGenAI, LangChainCallbackHandler, PostHogOpenAI as OpenAI, type PromptCodeFallbackResult, type PromptRemoteResult, type PromptResult, Prompts, wrapVercelLanguageModel as withTracing };
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.15.0";
8
+ var version = "7.16.1";
9
9
 
10
10
  // Type guards for safer type checking
11
11
  const isString = value => {
@@ -4436,8 +4436,20 @@ class LangChainCallbackHandler extends BaseCallbackHandler {
4436
4436
 
4437
4437
  /// <reference lib="dom" />
4438
4438
  const DEFAULT_CACHE_TTL_SECONDS = 300; // 5 minutes
4439
+ const DEFAULT_PROMPTS_HOST = 'https://us.posthog.com';
4440
+ function normalizeApiKey(value) {
4441
+ return typeof value === 'string' ? value.trim() : '';
4442
+ }
4443
+ function normalizeHost(value) {
4444
+ const normalizedHost = typeof value === 'string' ? value.trim() : '';
4445
+ return (normalizedHost || DEFAULT_PROMPTS_HOST).replace(/\/+$/, '');
4446
+ }
4439
4447
  function isPromptApiResponse(data) {
4440
- return typeof data === 'object' && data !== null && 'prompt' in data && typeof data.prompt === 'string';
4448
+ if (typeof data !== 'object' || data === null) {
4449
+ return false;
4450
+ }
4451
+ const record = data;
4452
+ return typeof record.prompt === 'string' && typeof record.name === 'string' && typeof record.version === 'number';
4441
4453
  }
4442
4454
  function isPromptsWithPostHog(options) {
4443
4455
  return 'posthog' in options;
@@ -4478,16 +4490,17 @@ function isPromptsWithPostHog(options) {
4478
4490
  class Prompts {
4479
4491
  constructor(options) {
4480
4492
  this.cache = new Map();
4493
+ this.hasWarnedDeprecation = false;
4481
4494
  this.defaultCacheTtlSeconds = options.defaultCacheTtlSeconds ?? DEFAULT_CACHE_TTL_SECONDS;
4482
4495
  if (isPromptsWithPostHog(options)) {
4483
4496
  this.personalApiKey = options.posthog.options.personalApiKey ?? '';
4484
- this.projectApiKey = options.posthog.apiKey ?? '';
4497
+ this.projectApiKey = options.posthog.apiKey;
4485
4498
  this.host = options.posthog.host;
4486
4499
  } else {
4487
4500
  // Direct options
4488
- this.personalApiKey = options.personalApiKey;
4489
- this.projectApiKey = options.projectApiKey;
4490
- this.host = options.host ?? 'https://us.posthog.com';
4501
+ this.personalApiKey = normalizeApiKey(options.personalApiKey);
4502
+ this.projectApiKey = normalizeApiKey(options.projectApiKey);
4503
+ this.host = normalizeHost(options.host);
4491
4504
  }
4492
4505
  }
4493
4506
  getPromptCache(name) {
@@ -4505,17 +4518,42 @@ class Prompts {
4505
4518
  getPromptLabel(name, version) {
4506
4519
  return version === undefined ? `"${name}"` : `"${name}" version ${version}`;
4507
4520
  }
4521
+ async get(name, options) {
4522
+ const withMetadata = options?.withMetadata;
4523
+ if (withMetadata === undefined && !this.hasWarnedDeprecation) {
4524
+ this.hasWarnedDeprecation = true;
4525
+ console.warn('[PostHog Prompts] Calling get() without { withMetadata: true } is deprecated and will be ' + 'removed in a future major version. Pass { withMetadata: true } to receive a PromptResult ' + 'object with source, name, and version metadata. ' + 'You can pass { withMetadata: false } to silence this warning, but the plain-string return ' + 'will still be removed in the next major version.');
4526
+ }
4527
+ try {
4528
+ const result = await this.getInternal(name, options);
4529
+ if (withMetadata) {
4530
+ return result;
4531
+ }
4532
+ return result.prompt;
4533
+ } catch (error) {
4534
+ const fallback = options?.fallback;
4535
+ if (fallback !== undefined) {
4536
+ const promptLabel = this.getPromptLabel(name, options?.version);
4537
+ console.warn(`[PostHog Prompts] Failed to fetch prompt ${promptLabel}, using fallback:`, error);
4538
+ if (withMetadata) {
4539
+ return {
4540
+ source: 'code_fallback',
4541
+ prompt: fallback,
4542
+ name: undefined,
4543
+ version: undefined
4544
+ };
4545
+ }
4546
+ return fallback;
4547
+ }
4548
+ throw error;
4549
+ }
4550
+ }
4508
4551
  /**
4509
- * Fetch a prompt by name from the PostHog API
4510
- *
4511
- * @param name - The name of the prompt to fetch
4512
- * @param options - Optional settings for caching, fallback, and exact version selection
4513
- * @returns The prompt string
4514
- * @throws Error if the prompt cannot be fetched and no fallback is provided
4552
+ * Internal method that handles cache + fetch logic, returning full metadata.
4553
+ * Does NOT handle the string `fallback` option — callers handle that.
4515
4554
  */
4516
- async get(name, options) {
4555
+ async getInternal(name, options) {
4517
4556
  const cacheTtlSeconds = options?.cacheTtlSeconds ?? this.defaultCacheTtlSeconds;
4518
- const fallback = options?.fallback;
4519
4557
  const version = options?.version;
4520
4558
  const promptLabel = this.getPromptLabel(name, version);
4521
4559
  // Check cache first
@@ -4524,32 +4562,41 @@ class Prompts {
4524
4562
  if (cached) {
4525
4563
  const isFresh = now - cached.fetchedAt < cacheTtlSeconds * 1000;
4526
4564
  if (isFresh) {
4527
- return cached.prompt;
4565
+ const {
4566
+ fetchedAt: _,
4567
+ ...cachedResult
4568
+ } = cached;
4569
+ return {
4570
+ source: 'cache',
4571
+ ...cachedResult
4572
+ };
4528
4573
  }
4529
4574
  }
4530
4575
  // Try to fetch from API
4531
4576
  try {
4532
- const prompt = await this.fetchPromptFromApi(name, version);
4533
- const fetchedAt = Date.now();
4577
+ const fetched = await this.fetchPromptFromApi(name, version);
4534
4578
  // Update cache
4535
4579
  this.getOrCreatePromptCache(name).set(version, {
4536
- prompt,
4537
- fetchedAt
4580
+ ...fetched,
4581
+ fetchedAt: Date.now()
4538
4582
  });
4539
- return prompt;
4583
+ return {
4584
+ source: 'api',
4585
+ ...fetched
4586
+ };
4540
4587
  } catch (error) {
4541
- // Fallback order:
4542
- // 1. Return stale cache (with warning)
4588
+ // Return stale cache (with warning)
4543
4589
  if (cached) {
4590
+ const {
4591
+ fetchedAt: _,
4592
+ ...cachedResult
4593
+ } = cached;
4544
4594
  console.warn(`[PostHog Prompts] Failed to fetch prompt ${promptLabel}, using stale cache:`, error);
4545
- return cached.prompt;
4546
- }
4547
- // 2. Return fallback (with warning)
4548
- if (fallback !== undefined) {
4549
- console.warn(`[PostHog Prompts] Failed to fetch prompt ${promptLabel}, using fallback:`, error);
4550
- return fallback;
4595
+ return {
4596
+ source: 'stale_cache',
4597
+ ...cachedResult
4598
+ };
4551
4599
  }
4552
- // 3. Throw error
4553
4600
  throw error;
4554
4601
  }
4555
4602
  }
@@ -4626,7 +4673,11 @@ class Prompts {
4626
4673
  if (!isPromptApiResponse(data)) {
4627
4674
  throw new Error(`[PostHog Prompts] Invalid response format for prompt ${promptLabel}`);
4628
4675
  }
4629
- return data.prompt;
4676
+ return {
4677
+ prompt: data.prompt,
4678
+ name: data.name,
4679
+ version: data.version
4680
+ };
4630
4681
  }
4631
4682
  }
4632
4683