@posthog/ai 7.21.0 → 8.0.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
@@ -1,20 +1,5 @@
1
- import OpenAIOrignal, { OpenAI, APIPromise, ClientOptions as ClientOptions$1, AzureOpenAI } from 'openai';
2
- import { PostHog } from 'posthog-node';
3
- import { Stream } from 'openai/streaming';
4
- import { ParsedResponse } from 'openai/resources/responses/responses';
5
- import { ResponseCreateParamsWithTools, ExtractParsedContentFromParams } from 'openai/lib/ResponsesParser';
6
1
  import { LanguageModelV2, LanguageModelV3 } from '@ai-sdk/provider';
7
- import AnthropicOriginal, { APIPromise as APIPromise$1 } from '@anthropic-ai/sdk';
8
- import { Stream as Stream$1 } from '@anthropic-ai/sdk/streaming';
9
- import { GoogleGenAI, GenerateContentParameters, GenerateContentResponse, EmbedContentParameters, EmbedContentResponse, GoogleGenAIOptions, Tool } from '@google/genai';
10
- import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
11
- import { Serialized } from '@langchain/core/load/serializable';
12
- import { ChainValues } from '@langchain/core/utils/types';
13
- import { LLMResult } from '@langchain/core/outputs';
14
- import { AgentAction, AgentFinish } from '@langchain/core/agents';
15
- import { DocumentInterface } from '@langchain/core/documents';
16
- import { BaseMessage } from '@langchain/core/messages';
17
- import { ChatCompletionTool } from 'openai/resources/chat/completions';
2
+ import { PostHog } from 'posthog-node';
18
3
 
19
4
  /**
20
5
  * Token usage information for AI model responses
@@ -35,14 +20,6 @@ interface GetPromptOptions {
35
20
  cacheTtlSeconds?: number;
36
21
  fallback?: string;
37
22
  version?: number;
38
- /**
39
- * When true, returns a `PromptResult` object with metadata (source, name, version)
40
- * instead of a plain string.
41
- *
42
- * Omitting this option or setting it to false is deprecated and will be removed
43
- * in a future major version.
44
- */
45
- withMetadata?: boolean;
46
23
  }
47
24
  /**
48
25
  * Result from the Prompts API or local cache — carries real metadata.
@@ -65,7 +42,7 @@ interface PromptCodeFallbackResult {
65
42
  version: undefined;
66
43
  }
67
44
  /**
68
- * Discriminated union returned by `Prompts.get()` when `withMetadata: true`.
45
+ * Discriminated union returned by `Prompts.get()`.
69
46
  *
70
47
  * Narrow on `source` to guarantee metadata, or access `result.name` /
71
48
  * `result.version` directly as `string | undefined` / `number | undefined`.
@@ -85,21 +62,6 @@ interface PromptsDirectOptions {
85
62
  defaultCacheTtlSeconds?: number;
86
63
  }
87
64
 
88
- interface MonitoringEventPropertiesWithDefaults {
89
- distinctId?: string;
90
- traceId: string;
91
- properties?: Record<string, any>;
92
- privacyMode: boolean;
93
- groups?: Record<string, any>;
94
- modelOverride?: string;
95
- providerOverride?: string;
96
- costOverride?: CostOverride;
97
- captureImmediate?: boolean;
98
- }
99
- type MonitoringEventProperties = Partial<MonitoringEventPropertiesWithDefaults>;
100
- type MonitoringParams = {
101
- [K in keyof MonitoringEventProperties as `posthog${Capitalize<string & K>}`]: MonitoringEventProperties[K];
102
- };
103
65
  interface CostOverride {
104
66
  inputCost: number;
105
67
  outputCost: number;
@@ -109,118 +71,6 @@ declare enum AIEvent {
109
71
  Embedding = "$ai_embedding"
110
72
  }
111
73
 
112
- declare const Chat: typeof OpenAI.Chat;
113
- declare const Completions: typeof OpenAI.Chat.Completions;
114
- declare const Responses: typeof OpenAI.Responses;
115
- declare const Embeddings: typeof OpenAI.Embeddings;
116
- declare const Audio: typeof OpenAI.Audio;
117
- declare const Transcriptions: typeof OpenAI.Audio.Transcriptions;
118
- type ChatCompletion$1 = OpenAI.ChatCompletion;
119
- type ChatCompletionChunk$1 = OpenAI.ChatCompletionChunk;
120
- type ChatCompletionCreateParamsBase$1 = OpenAI.Chat.Completions.ChatCompletionCreateParams;
121
- type ChatCompletionCreateParamsNonStreaming$1 = OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming;
122
- type ChatCompletionCreateParamsStreaming$1 = OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming;
123
- type ResponsesCreateParamsBase = OpenAI.Responses.ResponseCreateParams;
124
- type ResponsesCreateParamsNonStreaming = OpenAI.Responses.ResponseCreateParamsNonStreaming;
125
- type ResponsesCreateParamsStreaming = OpenAI.Responses.ResponseCreateParamsStreaming;
126
- type CreateEmbeddingResponse$1 = OpenAI.CreateEmbeddingResponse;
127
- type EmbeddingCreateParams$1 = OpenAI.EmbeddingCreateParams;
128
- interface MonitoringOpenAIConfig$1 extends ClientOptions$1 {
129
- apiKey: string;
130
- posthog: PostHog;
131
- baseURL?: string;
132
- }
133
- type RequestOptions$2 = Record<string, unknown>;
134
- declare class PostHogOpenAI extends OpenAI {
135
- private readonly phClient;
136
- chat: WrappedChat$1;
137
- responses: WrappedResponses;
138
- embeddings: WrappedEmbeddings$1;
139
- audio: WrappedAudio;
140
- constructor(config: MonitoringOpenAIConfig$1);
141
- }
142
- declare class WrappedChat$1 extends Chat {
143
- constructor(parentClient: PostHogOpenAI, phClient: PostHog);
144
- completions: WrappedCompletions$1;
145
- }
146
- declare class WrappedCompletions$1 extends Completions {
147
- private readonly phClient;
148
- private readonly baseURL;
149
- constructor(client: OpenAI, phClient: PostHog);
150
- create(body: ChatCompletionCreateParamsNonStreaming$1 & MonitoringParams, options?: RequestOptions$2): APIPromise<ChatCompletion$1>;
151
- create(body: ChatCompletionCreateParamsStreaming$1 & MonitoringParams, options?: RequestOptions$2): APIPromise<Stream<ChatCompletionChunk$1>>;
152
- create(body: ChatCompletionCreateParamsBase$1 & MonitoringParams, options?: RequestOptions$2): APIPromise<ChatCompletion$1 | Stream<ChatCompletionChunk$1>>;
153
- }
154
- declare class WrappedResponses extends Responses {
155
- private readonly phClient;
156
- private readonly baseURL;
157
- constructor(client: OpenAI, phClient: PostHog);
158
- create(body: ResponsesCreateParamsNonStreaming & MonitoringParams, options?: RequestOptions$2): APIPromise<OpenAI.Responses.Response>;
159
- create(body: ResponsesCreateParamsStreaming & MonitoringParams, options?: RequestOptions$2): APIPromise<Stream<OpenAI.Responses.ResponseStreamEvent>>;
160
- create(body: ResponsesCreateParamsBase & MonitoringParams, options?: RequestOptions$2): APIPromise<OpenAI.Responses.Response | Stream<OpenAI.Responses.ResponseStreamEvent>>;
161
- parse<Params extends ResponseCreateParamsWithTools, ParsedT = ExtractParsedContentFromParams<Params>>(body: Params & MonitoringParams, options?: RequestOptions$2): APIPromise<ParsedResponse<ParsedT>>;
162
- }
163
- declare class WrappedEmbeddings$1 extends Embeddings {
164
- private readonly phClient;
165
- private readonly baseURL;
166
- constructor(client: OpenAI, phClient: PostHog);
167
- create(body: EmbeddingCreateParams$1 & MonitoringParams, options?: RequestOptions$2): APIPromise<CreateEmbeddingResponse$1>;
168
- }
169
- declare class WrappedAudio extends Audio {
170
- constructor(parentClient: PostHogOpenAI, phClient: PostHog);
171
- transcriptions: WrappedTranscriptions;
172
- }
173
- declare class WrappedTranscriptions extends Transcriptions {
174
- private readonly phClient;
175
- private readonly baseURL;
176
- constructor(client: OpenAI, phClient: PostHog);
177
- create(body: OpenAI.Audio.Transcriptions.TranscriptionCreateParamsNonStreaming<'json' | undefined> & MonitoringParams, options?: RequestOptions$2): APIPromise<OpenAI.Audio.Transcriptions.Transcription>;
178
- create(body: OpenAI.Audio.Transcriptions.TranscriptionCreateParamsNonStreaming<'verbose_json'> & MonitoringParams, options?: RequestOptions$2): APIPromise<OpenAI.Audio.Transcriptions.TranscriptionVerbose>;
179
- create(body: OpenAI.Audio.Transcriptions.TranscriptionCreateParamsNonStreaming<'srt' | 'vtt' | 'text'> & MonitoringParams, options?: RequestOptions$2): APIPromise<string>;
180
- create(body: OpenAI.Audio.Transcriptions.TranscriptionCreateParamsNonStreaming, options?: RequestOptions$2): APIPromise<OpenAI.Audio.Transcriptions.Transcription>;
181
- create(body: OpenAI.Audio.Transcriptions.TranscriptionCreateParamsStreaming & MonitoringParams, options?: RequestOptions$2): APIPromise<Stream<OpenAI.Audio.Transcriptions.TranscriptionStreamEvent>>;
182
- create(body: OpenAI.Audio.Transcriptions.TranscriptionCreateParamsStreaming & MonitoringParams, options?: RequestOptions$2): APIPromise<OpenAI.Audio.Transcriptions.TranscriptionCreateResponse | string | Stream<OpenAI.Audio.Transcriptions.TranscriptionStreamEvent>>;
183
- create(body: OpenAI.Audio.Transcriptions.TranscriptionCreateParams & MonitoringParams, options?: RequestOptions$2): APIPromise<OpenAI.Audio.Transcriptions.TranscriptionCreateResponse | string | Stream<OpenAI.Audio.Transcriptions.TranscriptionStreamEvent>>;
184
- }
185
-
186
- type ChatCompletion = OpenAIOrignal.ChatCompletion;
187
- type ChatCompletionChunk = OpenAIOrignal.ChatCompletionChunk;
188
- type ChatCompletionCreateParamsBase = OpenAIOrignal.Chat.Completions.ChatCompletionCreateParams;
189
- type ChatCompletionCreateParamsNonStreaming = OpenAIOrignal.Chat.Completions.ChatCompletionCreateParamsNonStreaming;
190
- type ChatCompletionCreateParamsStreaming = OpenAIOrignal.Chat.Completions.ChatCompletionCreateParamsStreaming;
191
- type CreateEmbeddingResponse = OpenAIOrignal.CreateEmbeddingResponse;
192
- type EmbeddingCreateParams = OpenAIOrignal.EmbeddingCreateParams;
193
- interface MonitoringOpenAIConfig {
194
- apiKey: string;
195
- posthog: PostHog;
196
- baseURL?: string;
197
- }
198
- type RequestOptions$1 = Record<string, any>;
199
- declare class PostHogAzureOpenAI extends AzureOpenAI {
200
- private readonly phClient;
201
- chat: WrappedChat;
202
- embeddings: WrappedEmbeddings;
203
- constructor(config: MonitoringOpenAIConfig);
204
- }
205
- declare class WrappedChat extends AzureOpenAI.Chat {
206
- constructor(parentClient: PostHogAzureOpenAI, phClient: PostHog);
207
- completions: WrappedCompletions;
208
- }
209
- declare class WrappedCompletions extends AzureOpenAI.Chat.Completions {
210
- private readonly phClient;
211
- private readonly baseURL;
212
- constructor(client: AzureOpenAI, phClient: PostHog);
213
- create(body: ChatCompletionCreateParamsNonStreaming & MonitoringParams, options?: RequestOptions$1): APIPromise<ChatCompletion>;
214
- create(body: ChatCompletionCreateParamsStreaming & MonitoringParams, options?: RequestOptions$1): APIPromise<Stream<ChatCompletionChunk>>;
215
- create(body: ChatCompletionCreateParamsBase & MonitoringParams, options?: RequestOptions$1): APIPromise<ChatCompletion | Stream<ChatCompletionChunk>>;
216
- }
217
- declare class WrappedEmbeddings extends AzureOpenAI.Embeddings {
218
- private readonly phClient;
219
- private readonly baseURL;
220
- constructor(client: AzureOpenAI, phClient: PostHog);
221
- create(body: EmbeddingCreateParams & MonitoringParams, options?: RequestOptions$1): APIPromise<CreateEmbeddingResponse>;
222
- }
223
-
224
74
  type LanguageModel = LanguageModelV2 | LanguageModelV3;
225
75
  interface ClientOptions {
226
76
  posthogDistinctId?: string;
@@ -239,115 +89,6 @@ interface ClientOptions {
239
89
  */
240
90
  declare const wrapVercelLanguageModel: <T extends LanguageModel>(model: T, phClient: PostHog, options: ClientOptions) => T;
241
91
 
242
- type MessageCreateParamsNonStreaming = AnthropicOriginal.Messages.MessageCreateParamsNonStreaming;
243
- type MessageCreateParamsStreaming = AnthropicOriginal.Messages.MessageCreateParamsStreaming;
244
- type Message = AnthropicOriginal.Messages.Message;
245
- type RawMessageStreamEvent = AnthropicOriginal.Messages.RawMessageStreamEvent;
246
- type MessageCreateParamsBase = AnthropicOriginal.Messages.MessageCreateParams;
247
- type RequestOptions = AnthropicOriginal.RequestOptions;
248
-
249
- interface MonitoringAnthropicConfig {
250
- apiKey: string;
251
- posthog: PostHog;
252
- baseURL?: string;
253
- }
254
- declare class PostHogAnthropic extends AnthropicOriginal {
255
- private readonly phClient;
256
- messages: WrappedMessages;
257
- constructor(config: MonitoringAnthropicConfig);
258
- }
259
- declare class WrappedMessages extends AnthropicOriginal.Messages {
260
- private readonly phClient;
261
- private readonly baseURL;
262
- constructor(parentClient: PostHogAnthropic, phClient: PostHog);
263
- create(body: MessageCreateParamsNonStreaming, options?: RequestOptions): APIPromise$1<Message>;
264
- create(body: MessageCreateParamsStreaming & MonitoringParams, options?: RequestOptions): APIPromise$1<Stream$1<RawMessageStreamEvent>>;
265
- create(body: MessageCreateParamsBase & MonitoringParams, options?: RequestOptions): APIPromise$1<Stream$1<RawMessageStreamEvent> | Message>;
266
- }
267
-
268
- interface MonitoringGeminiConfig extends GoogleGenAIOptions {
269
- posthog: PostHog;
270
- }
271
- declare class PostHogGoogleGenAI {
272
- private readonly phClient;
273
- private readonly client;
274
- models: WrappedModels;
275
- constructor(config: MonitoringGeminiConfig);
276
- }
277
- declare class WrappedModels {
278
- private readonly phClient;
279
- private readonly client;
280
- constructor(client: GoogleGenAI, phClient: PostHog);
281
- generateContent(params: GenerateContentParameters & MonitoringParams): Promise<GenerateContentResponse>;
282
- generateContentStream(params: GenerateContentParameters & MonitoringParams): AsyncGenerator<GenerateContentResponse, void, unknown>;
283
- embedContent(params: EmbedContentParameters & MonitoringParams): Promise<EmbedContentResponse>;
284
- private formatPartsAsContentBlocks;
285
- private formatInput;
286
- private extractSystemInstruction;
287
- private formatInputForPostHog;
288
- }
289
-
290
- declare class LangChainCallbackHandler extends BaseCallbackHandler {
291
- name: string;
292
- private client;
293
- private distinctId?;
294
- private traceId?;
295
- private properties;
296
- private privacyMode;
297
- private groups;
298
- private debug;
299
- private runs;
300
- private parentTree;
301
- constructor(options: {
302
- client: PostHog;
303
- distinctId?: string | number;
304
- traceId?: string | number;
305
- properties?: Record<string, any>;
306
- privacyMode?: boolean;
307
- groups?: Record<string, any>;
308
- debug?: boolean;
309
- });
310
- handleChainStart(chain: Serialized, inputs: ChainValues, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>, _runType?: string, runName?: string): void;
311
- handleChainEnd(outputs: ChainValues, runId: string, parentRunId?: string, tags?: string[], _kwargs?: {
312
- inputs?: Record<string, unknown>;
313
- }): void;
314
- handleChainError(error: Error, runId: string, parentRunId?: string, tags?: string[], _kwargs?: {
315
- inputs?: Record<string, unknown>;
316
- }): void;
317
- handleChatModelStart(serialized: Serialized, messages: BaseMessage[][], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, tags?: string[], metadata?: Record<string, unknown>, runName?: string): void;
318
- handleLLMStart(serialized: Serialized, prompts: string[], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, tags?: string[], metadata?: Record<string, unknown>, runName?: string): void;
319
- handleLLMEnd(output: LLMResult, runId: string, parentRunId?: string, tags?: string[], _extraParams?: Record<string, unknown>): void;
320
- handleLLMError(err: Error, runId: string, parentRunId?: string, tags?: string[], _extraParams?: Record<string, unknown>): void;
321
- handleToolStart(tool: Serialized, input: string, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>, runName?: string): void;
322
- handleToolEnd(output: any, runId: string, parentRunId?: string, tags?: string[]): void;
323
- handleToolError(err: Error, runId: string, parentRunId?: string, tags?: string[]): void;
324
- handleRetrieverStart(retriever: Serialized, query: string, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>, name?: string): void;
325
- handleRetrieverEnd(documents: DocumentInterface[], runId: string, parentRunId?: string, tags?: string[]): void;
326
- handleRetrieverError(err: Error, runId: string, parentRunId?: string, tags?: string[]): void;
327
- handleAgentAction(action: AgentAction, runId: string, parentRunId?: string, tags?: string[]): void;
328
- handleAgentEnd(action: AgentFinish, runId: string, parentRunId?: string, tags?: string[]): void;
329
- private _setParentOfRun;
330
- private _popParentOfRun;
331
- private _findRootRun;
332
- private _setTraceOrSpanMetadata;
333
- private _setLLMMetadata;
334
- private _popRunMetadata;
335
- private _getTraceId;
336
- private _getParentRunId;
337
- private _popRunAndCaptureTraceOrSpan;
338
- private _captureTraceOrSpan;
339
- private _popRunAndCaptureGeneration;
340
- private _captureGeneration;
341
- private _logDebugEvent;
342
- private _getLangchainRunName;
343
- private _convertLcToolCallsToOai;
344
- private _extractRawResponse;
345
- private _convertMessageToDict;
346
- private _extractStopReason;
347
- private _parseUsageModel;
348
- private parseUsage;
349
- }
350
-
351
92
  interface PromptsWithPostHogOptions {
352
93
  posthog: PostHog;
353
94
  defaultCacheTtlSeconds?: number;
@@ -369,18 +110,18 @@ type PromptsOptions = PromptsWithPostHogOptions | PromptsDirectOptions;
369
110
  * })
370
111
  *
371
112
  * // Fetch with caching and fallback
372
- * const template = await prompts.get('support-system-prompt', {
113
+ * const result = await prompts.get('support-system-prompt', {
373
114
  * cacheTtlSeconds: 300,
374
115
  * fallback: 'You are a helpful assistant.',
375
116
  * })
376
117
  *
377
118
  * // Or fetch an exact published version
378
- * const v3Template = await prompts.get('support-system-prompt', {
119
+ * const v3 = await prompts.get('support-system-prompt', {
379
120
  * version: 3,
380
121
  * })
381
122
  *
382
123
  * // Compile with variables
383
- * const systemPrompt = prompts.compile(template, {
124
+ * const systemPrompt = prompts.compile(result.prompt, {
384
125
  * company: 'Acme Corp',
385
126
  * tier: 'premium',
386
127
  * })
@@ -392,7 +133,6 @@ declare class Prompts {
392
133
  private host;
393
134
  private defaultCacheTtlSeconds;
394
135
  private cache;
395
- private hasWarnedDeprecation;
396
136
  constructor(options: PromptsOptions);
397
137
  private getPromptCache;
398
138
  private getOrCreatePromptCache;
@@ -400,15 +140,10 @@ declare class Prompts {
400
140
  /**
401
141
  * Fetch a prompt by name from the PostHog API.
402
142
  *
403
- * When `withMetadata` is `true`, returns a `PromptResult` object with `source`,
404
- * `name`, and `version` metadata. When omitted or `false`, returns a plain string
405
- * (deprecated — will be removed in a future major version).
143
+ * Returns a `PromptResult` object carrying the prompt text alongside `source`,
144
+ * `name`, and `version` metadata. Read `result.prompt` for the template string.
406
145
  */
407
- get(name: string, options: GetPromptOptions & {
408
- withMetadata: true;
409
- }): Promise<PromptResult>;
410
- /** @deprecated Omitting `withMetadata` is deprecated. Pass `{ withMetadata: true }` to receive a `PromptResult`. */
411
- get(name: string, options?: GetPromptOptions): Promise<string>;
146
+ get(name: string, options?: GetPromptOptions): Promise<PromptResult>;
412
147
  /**
413
148
  * Internal method that handles cache + fetch logic, returning full metadata.
414
149
  * Does NOT handle the string `fallback` option — callers handle that.
@@ -435,7 +170,6 @@ declare class Prompts {
435
170
  private fetchPromptFromApi;
436
171
  }
437
172
 
438
- type AnthropicTool = AnthropicOriginal.Tool;
439
173
  /**
440
174
  * Options for `captureAiGeneration`. Mirrors the `$ai_generation` event shape
441
175
  * directly so that any caller — first-party SDK wrappers and external code
@@ -477,7 +211,7 @@ interface CaptureAiGenerationOptions {
477
211
  */
478
212
  providerOverride?: string;
479
213
  costOverride?: CostOverride;
480
- tools?: ChatCompletionTool[] | AnthropicTool[] | Tool[] | null;
214
+ tools?: unknown[] | null;
481
215
  stopReason?: string;
482
216
  /**
483
217
  * Provider-assigned ID for the generation (e.g. OpenAI's `chatcmpl-…` /
@@ -512,4 +246,4 @@ interface CaptureAiGenerationOptions {
512
246
  */
513
247
  declare const captureAiGeneration: (client: PostHog, options: CaptureAiGenerationOptions) => Promise<void>;
514
248
 
515
- export { AIEvent, PostHogAnthropic as Anthropic, PostHogAzureOpenAI as AzureOpenAI, type CaptureAiGenerationOptions, PostHogGoogleGenAI as GoogleGenAI, LangChainCallbackHandler, PostHogOpenAI as OpenAI, type PromptCodeFallbackResult, type PromptRemoteResult, type PromptResult, Prompts, captureAiGeneration, wrapVercelLanguageModel as withTracing };
249
+ export { AIEvent, type CaptureAiGenerationOptions, type PromptCodeFallbackResult, type PromptRemoteResult, type PromptResult, Prompts, captureAiGeneration, wrapVercelLanguageModel as withTracing };