@posthog/ai 7.6.0 → 7.7.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
@@ -15,6 +15,26 @@ import { AgentAction, AgentFinish } from '@langchain/core/agents';
15
15
  import { DocumentInterface } from '@langchain/core/documents';
16
16
  import { BaseMessage } from '@langchain/core/messages';
17
17
 
18
+ /**
19
+ * Options for fetching a prompt
20
+ */
21
+ interface GetPromptOptions {
22
+ cacheTtlSeconds?: number;
23
+ fallback?: string;
24
+ }
25
+ /**
26
+ * Variables for prompt compilation
27
+ */
28
+ type PromptVariables = Record<string, string | number | boolean>;
29
+ /**
30
+ * Direct options for initializing Prompts without a PostHog client
31
+ */
32
+ interface PromptsDirectOptions {
33
+ personalApiKey: string;
34
+ host?: string;
35
+ defaultCacheTtlSeconds?: number;
36
+ }
37
+
18
38
  interface MonitoringEventPropertiesWithDefaults {
19
39
  distinctId?: string;
20
40
  traceId: string;
@@ -272,4 +292,71 @@ declare class LangChainCallbackHandler extends BaseCallbackHandler {
272
292
  private parseUsage;
273
293
  }
274
294
 
275
- export { PostHogAnthropic as Anthropic, PostHogAzureOpenAI as AzureOpenAI, PostHogGoogleGenAI as GoogleGenAI, LangChainCallbackHandler, PostHogOpenAI as OpenAI, wrapVercelLanguageModel as withTracing };
295
+ interface PromptsWithPostHogOptions {
296
+ posthog: PostHog;
297
+ defaultCacheTtlSeconds?: number;
298
+ }
299
+ type PromptsOptions = PromptsWithPostHogOptions | PromptsDirectOptions;
300
+ /**
301
+ * Prompts class for fetching and compiling LLM prompts from PostHog
302
+ *
303
+ * @example
304
+ * ```ts
305
+ * // With PostHog client
306
+ * const prompts = new Prompts({ posthog })
307
+ *
308
+ * // Or with direct options (no PostHog client needed)
309
+ * const prompts = new Prompts({
310
+ * personalApiKey: 'phx_xxx',
311
+ * host: 'https://us.i.posthog.com',
312
+ * })
313
+ *
314
+ * // Fetch with caching and fallback
315
+ * const template = await prompts.get('support-system-prompt', {
316
+ * cacheTtlSeconds: 300,
317
+ * fallback: 'You are a helpful assistant.',
318
+ * })
319
+ *
320
+ * // Compile with variables
321
+ * const systemPrompt = prompts.compile(template, {
322
+ * company: 'Acme Corp',
323
+ * tier: 'premium',
324
+ * })
325
+ * ```
326
+ */
327
+ declare class Prompts {
328
+ private personalApiKey;
329
+ private host;
330
+ private defaultCacheTtlSeconds;
331
+ private cache;
332
+ constructor(options: PromptsOptions);
333
+ /**
334
+ * Fetch a prompt by name from the PostHog API
335
+ *
336
+ * @param name - The name of the prompt to fetch
337
+ * @param options - Optional settings for caching and fallback
338
+ * @returns The prompt string
339
+ * @throws Error if the prompt cannot be fetched and no fallback is provided
340
+ */
341
+ get(name: string, options?: GetPromptOptions): Promise<string>;
342
+ /**
343
+ * Compile a prompt template with variable substitution
344
+ *
345
+ * Variables in the format `{{variableName}}` will be replaced with values from the variables object.
346
+ * Unmatched variables are left unchanged.
347
+ *
348
+ * @param prompt - The prompt template string
349
+ * @param variables - Object containing variable values
350
+ * @returns The compiled prompt string
351
+ */
352
+ compile(prompt: string, variables: PromptVariables): string;
353
+ /**
354
+ * Clear the cache for a specific prompt or all prompts
355
+ *
356
+ * @param name - Optional prompt name to clear. If not provided, clears all cached prompts.
357
+ */
358
+ clearCache(name?: string): void;
359
+ private fetchPromptFromApi;
360
+ }
361
+
362
+ export { PostHogAnthropic as Anthropic, PostHogAzureOpenAI as AzureOpenAI, PostHogGoogleGenAI as GoogleGenAI, LangChainCallbackHandler, PostHogOpenAI as OpenAI, Prompts, wrapVercelLanguageModel as withTracing };
package/dist/index.mjs CHANGED
@@ -6,7 +6,7 @@ import { uuidv7 } from '@posthog/core';
6
6
  import AnthropicOriginal from '@anthropic-ai/sdk';
7
7
  import { GoogleGenAI } from '@google/genai';
8
8
 
9
- var version = "7.6.0";
9
+ var version = "7.7.0";
10
10
 
11
11
  // Type guards for safer type checking
12
12
  const isString = value => {
@@ -4262,5 +4262,157 @@ class LangChainCallbackHandler extends BaseCallbackHandler {
4262
4262
  }
4263
4263
  }
4264
4264
 
4265
- export { PostHogAnthropic as Anthropic, PostHogAzureOpenAI as AzureOpenAI, PostHogGoogleGenAI as GoogleGenAI, LangChainCallbackHandler, PostHogOpenAI as OpenAI, wrapVercelLanguageModel as withTracing };
4265
+ /// <reference lib="dom" />
4266
+ const DEFAULT_CACHE_TTL_SECONDS = 300; // 5 minutes
4267
+ function isPromptApiResponse(data) {
4268
+ return typeof data === 'object' && data !== null && 'prompt' in data && typeof data.prompt === 'string';
4269
+ }
4270
+ function isPromptsWithPostHog(options) {
4271
+ return 'posthog' in options;
4272
+ }
4273
+ /**
4274
+ * Prompts class for fetching and compiling LLM prompts from PostHog
4275
+ *
4276
+ * @example
4277
+ * ```ts
4278
+ * // With PostHog client
4279
+ * const prompts = new Prompts({ posthog })
4280
+ *
4281
+ * // Or with direct options (no PostHog client needed)
4282
+ * const prompts = new Prompts({
4283
+ * personalApiKey: 'phx_xxx',
4284
+ * host: 'https://us.i.posthog.com',
4285
+ * })
4286
+ *
4287
+ * // Fetch with caching and fallback
4288
+ * const template = await prompts.get('support-system-prompt', {
4289
+ * cacheTtlSeconds: 300,
4290
+ * fallback: 'You are a helpful assistant.',
4291
+ * })
4292
+ *
4293
+ * // Compile with variables
4294
+ * const systemPrompt = prompts.compile(template, {
4295
+ * company: 'Acme Corp',
4296
+ * tier: 'premium',
4297
+ * })
4298
+ * ```
4299
+ */
4300
+ class Prompts {
4301
+ constructor(options) {
4302
+ this.cache = new Map();
4303
+ this.defaultCacheTtlSeconds = options.defaultCacheTtlSeconds ?? DEFAULT_CACHE_TTL_SECONDS;
4304
+ if (isPromptsWithPostHog(options)) {
4305
+ this.personalApiKey = options.posthog.options.personalApiKey ?? '';
4306
+ this.host = options.posthog.host;
4307
+ } else {
4308
+ // Direct options
4309
+ this.personalApiKey = options.personalApiKey;
4310
+ this.host = options.host ?? 'https://us.i.posthog.com';
4311
+ }
4312
+ }
4313
+ /**
4314
+ * Fetch a prompt by name from the PostHog API
4315
+ *
4316
+ * @param name - The name of the prompt to fetch
4317
+ * @param options - Optional settings for caching and fallback
4318
+ * @returns The prompt string
4319
+ * @throws Error if the prompt cannot be fetched and no fallback is provided
4320
+ */
4321
+ async get(name, options) {
4322
+ const cacheTtlSeconds = options?.cacheTtlSeconds ?? this.defaultCacheTtlSeconds;
4323
+ const fallback = options?.fallback;
4324
+ // Check cache first
4325
+ const cached = this.cache.get(name);
4326
+ const now = Date.now();
4327
+ if (cached) {
4328
+ const isFresh = now - cached.fetchedAt < cacheTtlSeconds * 1000;
4329
+ if (isFresh) {
4330
+ return cached.prompt;
4331
+ }
4332
+ }
4333
+ // Try to fetch from API
4334
+ try {
4335
+ const prompt = await this.fetchPromptFromApi(name);
4336
+ const fetchedAt = Date.now();
4337
+ // Update cache
4338
+ this.cache.set(name, {
4339
+ prompt,
4340
+ fetchedAt
4341
+ });
4342
+ return prompt;
4343
+ } catch (error) {
4344
+ // Fallback order:
4345
+ // 1. Return stale cache (with warning)
4346
+ if (cached) {
4347
+ console.warn(`[PostHog Prompts] Failed to fetch prompt "${name}", using stale cache:`, error);
4348
+ return cached.prompt;
4349
+ }
4350
+ // 2. Return fallback (with warning)
4351
+ if (fallback !== undefined) {
4352
+ console.warn(`[PostHog Prompts] Failed to fetch prompt "${name}", using fallback:`, error);
4353
+ return fallback;
4354
+ }
4355
+ // 3. Throw error
4356
+ throw error;
4357
+ }
4358
+ }
4359
+ /**
4360
+ * Compile a prompt template with variable substitution
4361
+ *
4362
+ * Variables in the format `{{variableName}}` will be replaced with values from the variables object.
4363
+ * Unmatched variables are left unchanged.
4364
+ *
4365
+ * @param prompt - The prompt template string
4366
+ * @param variables - Object containing variable values
4367
+ * @returns The compiled prompt string
4368
+ */
4369
+ compile(prompt, variables) {
4370
+ return prompt.replace(/\{\{([\w.-]+)\}\}/g, (match, variableName) => {
4371
+ if (variableName in variables) {
4372
+ return String(variables[variableName]);
4373
+ }
4374
+ return match;
4375
+ });
4376
+ }
4377
+ /**
4378
+ * Clear the cache for a specific prompt or all prompts
4379
+ *
4380
+ * @param name - Optional prompt name to clear. If not provided, clears all cached prompts.
4381
+ */
4382
+ clearCache(name) {
4383
+ if (name !== undefined) {
4384
+ this.cache.delete(name);
4385
+ } else {
4386
+ this.cache.clear();
4387
+ }
4388
+ }
4389
+ async fetchPromptFromApi(name) {
4390
+ if (!this.personalApiKey) {
4391
+ throw new Error('[PostHog Prompts] personalApiKey is required to fetch prompts. ' + 'Please provide it when initializing the Prompts instance.');
4392
+ }
4393
+ const url = `${this.host}/api/projects/@current/llm_prompts/name/${encodeURIComponent(name)}/`;
4394
+ const response = await fetch(url, {
4395
+ method: 'GET',
4396
+ headers: {
4397
+ Authorization: `Bearer ${this.personalApiKey}`
4398
+ }
4399
+ });
4400
+ if (!response.ok) {
4401
+ if (response.status === 404) {
4402
+ throw new Error(`[PostHog Prompts] Prompt "${name}" not found`);
4403
+ }
4404
+ if (response.status === 403) {
4405
+ 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.');
4406
+ }
4407
+ throw new Error(`[PostHog Prompts] Failed to fetch prompt "${name}": HTTP ${response.status}`);
4408
+ }
4409
+ const data = await response.json();
4410
+ if (!isPromptApiResponse(data)) {
4411
+ throw new Error(`[PostHog Prompts] Invalid response format for prompt "${name}"`);
4412
+ }
4413
+ return data.prompt;
4414
+ }
4415
+ }
4416
+
4417
+ export { PostHogAnthropic as Anthropic, PostHogAzureOpenAI as AzureOpenAI, PostHogGoogleGenAI as GoogleGenAI, LangChainCallbackHandler, PostHogOpenAI as OpenAI, Prompts, wrapVercelLanguageModel as withTracing };
4266
4418
  //# sourceMappingURL=index.mjs.map