@posthog/ai 8.2.0 → 8.2.2

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/LICENSE CHANGED
@@ -324,3 +324,30 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
324
324
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
325
325
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
326
326
  SOFTWARE.
327
+
328
+ ---
329
+
330
+ Some files in this codebase contain code from MCPCat/mcpcat-typescript-sdk.
331
+ In such cases it is explicitly stated in the file header. This license only applies to the relevant code in such cases.
332
+
333
+ MIT License
334
+
335
+ Copyright (c) 2025 MCPcat
336
+
337
+ Permission is hereby granted, free of charge, to any person obtaining a copy
338
+ of this software and associated documentation files (the "Software"), to deal
339
+ in the Software without restriction, including without limitation the rights
340
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
341
+ copies of the Software, and to permit persons to whom the Software is
342
+ furnished to do so, subject to the following conditions:
343
+
344
+ The above copyright notice and this permission notice shall be included in all
345
+ copies or substantial portions of the Software.
346
+
347
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
348
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
349
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
350
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
351
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
352
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
353
+ SOFTWARE.
package/README.md CHANGED
@@ -1,156 +1,13 @@
1
- # PostHog Node AI
1
+ # PostHog AI package
2
2
 
3
- TypeScript SDK for LLM observability with PostHog.
3
+ Please see the main [PostHog docs](https://posthog.com/docs).
4
4
 
5
- [SEE FULL DOCS](https://posthog.com/docs/ai-engineering/observability)
5
+ SDK usage examples and code snippets live in the official documentation so they stay up to date.
6
6
 
7
- ## Installation
7
+ ## Documentation
8
8
 
9
- Provider SDKs are optional peer dependencies, so you only install the SDK for the integration you use. Install `@posthog/ai` alongside it:
10
-
11
- ```bash
12
- npm install @posthog/ai openai # OpenAI / Azure OpenAI
13
- npm install @posthog/ai @anthropic-ai/sdk # Anthropic
14
- npm install @posthog/ai @google/genai # Google Gemini
15
- npm install @posthog/ai @langchain/core # LangChain
16
- # Vercel AI SDK (withTracing), captureAiGeneration, and OpenTelemetry need no provider SDK
17
- ```
18
-
19
- Import each integration from its subpath:
20
-
21
- | Integration | Import from | Peer to install |
22
- | --- | --- | --- |
23
- | OpenAI / Azure OpenAI | `@posthog/ai/openai` | `openai` |
24
- | Anthropic | `@posthog/ai/anthropic` | `@anthropic-ai/sdk` |
25
- | Google Gemini | `@posthog/ai/gemini` | `@google/genai` |
26
- | LangChain | `@posthog/ai/langchain` | `@langchain/core` |
27
- | Vercel AI SDK (`withTracing`) | `@posthog/ai` | — |
28
- | Custom (`captureAiGeneration`) | `@posthog/ai` | — |
29
-
30
- ## Direct Provider Usage
31
-
32
- ```typescript
33
- import { OpenAI } from '@posthog/ai/openai'
34
- import { PostHog } from 'posthog-node'
35
-
36
- const phClient = new PostHog('<YOUR_PROJECT_API_KEY>', { host: 'https://us.i.posthog.com' })
37
-
38
- const client = new OpenAI({
39
- apiKey: '<YOUR_OPENAI_API_KEY>',
40
- posthog: phClient,
41
- })
42
-
43
- const completion = await client.chat.completions.create({
44
- model: 'gpt-5-mini',
45
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
46
- posthogDistinctId: 'user_123', // optional
47
- posthogTraceId: 'trace_123', // optional
48
- posthogProperties: { conversation_id: 'abc123', paid: true }, //optional
49
- posthogGroups: { company: 'company_id_in_your_db' }, // optional
50
- posthogPrivacyMode: false, // optional
51
- })
52
-
53
- console.log(completion.choices[0].message.content)
54
-
55
- // YOU HAVE TO HAVE THIS OR THE CLIENT MAY NOT SEND EVENTS
56
- await phClient.shutdown()
57
- ```
58
-
59
- ## Custom and unsupported providers
60
-
61
- For LLM calls that don't go through one of the wrapped clients — direct Cloudflare Workers AI bindings, TanStack AI adapters, custom HTTP clients — use `captureAiGeneration` to emit the same `$ai_generation` events the wrappers produce.
62
-
63
- ```typescript
64
- import { captureAiGeneration } from '@posthog/ai'
65
- import { PostHog } from 'posthog-node'
66
-
67
- const phClient = new PostHog('<YOUR_PROJECT_API_KEY>', { host: 'https://us.i.posthog.com' })
68
-
69
- const start = Date.now()
70
- const result = await env.AI.run('@cf/zai-org/glm-4.7-flash', { messages, reasoning_effort: 'high' })
71
-
72
- await captureAiGeneration(phClient, {
73
- distinctId: 'user_123',
74
- traceId: 'trace_abc',
75
- provider: 'cloudflare-workers-ai',
76
- model: '@cf/zai-org/glm-4.7-flash',
77
- input: messages,
78
- output: result.response,
79
- modelParameters: { reasoning_effort: 'high' },
80
- usage: { inputTokens: result.usage?.prompt_tokens, outputTokens: result.usage?.completion_tokens },
81
- latency: (Date.now() - start) / 1000,
82
- properties: { feature: 'transcript-toc' },
83
- })
84
-
85
- await phClient.shutdown()
86
- ```
87
-
88
- `captureAiGeneration` is the same primitive that every other `@posthog/ai` wrapper funnels through, so the resulting events are indistinguishable from those produced by `withTracing`, `OpenAI`, `Anthropic`, etc.
89
-
90
- ## OpenTelemetry
91
-
92
- `@posthog/ai/otel` provides two ways to send AI traces to PostHog via OpenTelemetry. Both automatically filter to AI-related spans only (`gen_ai.*`, `llm.*`, `ai.*`, `traceloop.*`) and PostHog converts them into `$ai_generation` events server-side. `projectToken` is required; a blank token disables the OpenTelemetry integration as a defensive no-op. This works with any LLM provider SDK that supports OpenTelemetry.
93
-
94
- ```bash
95
- npm install @posthog/ai @opentelemetry/sdk-node @opentelemetry/sdk-trace-base @opentelemetry/exporter-trace-otlp-http
96
- ```
97
-
98
- ### PostHogSpanProcessor (recommended)
99
-
100
- A self-contained `SpanProcessor` that handles batching and export internally. Use this when your setup accepts a span processor.
101
-
102
- ```typescript
103
- import { NodeSDK } from '@opentelemetry/sdk-node'
104
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
105
- import { generateText } from 'ai'
106
- import { openai } from '@ai-sdk/openai'
107
-
108
- const sdk = new NodeSDK({
109
- spanProcessors: [
110
- new PostHogSpanProcessor({
111
- projectToken: '<YOUR_PROJECT_TOKEN>',
112
- host: 'https://us.i.posthog.com', // optional, defaults to https://us.i.posthog.com
113
- }),
114
- ],
115
- })
116
- sdk.start()
117
-
118
- const result = await generateText({
119
- model: openai('gpt-5-mini'),
120
- prompt: 'Write a short haiku about debugging',
121
- experimental_telemetry: {
122
- isEnabled: true,
123
- functionId: 'my-awesome-function',
124
- metadata: {
125
- posthog_distinct_id: 'user_123',
126
- conversation_id: 'abc123',
127
- },
128
- },
129
- })
130
-
131
- await sdk.shutdown()
132
- ```
133
-
134
- ### PostHogTraceExporter
135
-
136
- A `TraceExporter` for APIs that only accept an exporter, such as Vercel's `registerOTel`.
137
-
138
- ```typescript
139
- import { PostHogTraceExporter } from '@posthog/ai/otel'
140
- import { registerOTel } from '@vercel/otel'
141
-
142
- registerOTel({
143
- serviceName: 'my-app',
144
- traceExporter: new PostHogTraceExporter({
145
- projectToken: '<YOUR_PROJECT_TOKEN>',
146
- host: 'https://us.i.posthog.com', // optional, defaults to https://us.i.posthog.com
147
- }),
148
- })
149
- ```
150
-
151
- LLM Observability [docs](https://posthog.com/docs/ai-engineering/observability)
152
-
153
- Please see the main [PostHog docs](https://www.posthog.com/docs).
9
+ - [AI observability installation docs](https://posthog.com/docs/ai-observability/installation)
10
+ - [AI observability docs](https://posthog.com/docs/ai-observability)
154
11
 
155
12
  ## Questions?
156
13
 
@@ -299,7 +299,7 @@ function addDefaults(params) {
299
299
  };
300
300
  }
301
301
 
302
- var version = "8.2.0";
302
+ var version = "8.2.2";
303
303
 
304
304
  const DEFAULT_MAX_DEPTH = 3;
305
305
  const MAX_STACK_LINES = 20;
@@ -291,7 +291,7 @@ function addDefaults(params) {
291
291
  };
292
292
  }
293
293
 
294
- var version = "8.2.0";
294
+ var version = "8.2.2";
295
295
 
296
296
  const DEFAULT_MAX_DEPTH = 3;
297
297
  const MAX_STACK_LINES = 20;
@@ -384,7 +384,7 @@ function addDefaults(params) {
384
384
  };
385
385
  }
386
386
 
387
- var version = "8.2.0";
387
+ var version = "8.2.2";
388
388
 
389
389
  const DEFAULT_MAX_DEPTH = 3;
390
390
  const MAX_STACK_LINES = 20;
@@ -380,7 +380,7 @@ function addDefaults(params) {
380
380
  };
381
381
  }
382
382
 
383
- var version = "8.2.0";
383
+ var version = "8.2.2";
384
384
 
385
385
  const DEFAULT_MAX_DEPTH = 3;
386
386
  const MAX_STACK_LINES = 20;
package/dist/index.cjs CHANGED
@@ -380,7 +380,7 @@ function sanitizeValues(obj) {
380
380
  return jsonSafe;
381
381
  }
382
382
 
383
- var version = "8.2.0";
383
+ var version = "8.2.2";
384
384
 
385
385
  const DEFAULT_MAX_DEPTH = 3;
386
386
  const MAX_STACK_LINES = 20;
package/dist/index.mjs CHANGED
@@ -378,7 +378,7 @@ function sanitizeValues(obj) {
378
378
  return jsonSafe;
379
379
  }
380
380
 
381
- var version = "8.2.0";
381
+ var version = "8.2.2";
382
382
 
383
383
  const DEFAULT_MAX_DEPTH = 3;
384
384
  const MAX_STACK_LINES = 20;
@@ -217,7 +217,7 @@ function sanitizeValues(obj) {
217
217
  return jsonSafe;
218
218
  }
219
219
 
220
- var version = "8.2.0";
220
+ var version = "8.2.2";
221
221
 
222
222
  const DEFAULT_MAX_DEPTH = 3;
223
223
  const MAX_STACK_LINES = 20;
@@ -215,7 +215,7 @@ function sanitizeValues(obj) {
215
215
  return jsonSafe;
216
216
  }
217
217
 
218
- var version = "8.2.0";
218
+ var version = "8.2.2";
219
219
 
220
220
  const DEFAULT_MAX_DEPTH = 3;
221
221
  const MAX_STACK_LINES = 20;
@@ -534,7 +534,7 @@ function formatOpenAIResponsesInput(input, instructions) {
534
534
  return messages;
535
535
  }
536
536
 
537
- var version = "8.2.0";
537
+ var version = "8.2.2";
538
538
 
539
539
  const DEFAULT_MAX_DEPTH = 3;
540
540
  const MAX_STACK_LINES = 20;
@@ -807,6 +807,7 @@ class PostHogAzureOpenAI extends openai.AzureOpenAI {
807
807
  super(openAIConfig);
808
808
  this.phClient = posthog;
809
809
  this.chat = new WrappedChat$1(this, this.phClient);
810
+ this.responses = new WrappedResponses$1(this, this.phClient);
810
811
  this.embeddings = new WrappedEmbeddings$1(this, this.phClient);
811
812
  }
812
813
  }
@@ -1358,6 +1359,10 @@ function preserveAPIPromiseHelpers(parentPromise, wrappedPromise) {
1358
1359
  }
1359
1360
  return apiPromise;
1360
1361
  }
1362
+ const TERMINAL_RESPONSE_STATUSES = new Set(['completed', 'failed', 'cancelled', 'incomplete']);
1363
+ function isPendingBackgroundResponse(params, response) {
1364
+ return params.background === true && !response.usage && !!response.status && !TERMINAL_RESPONSE_STATUSES.has(response.status);
1365
+ }
1361
1366
  class PostHogOpenAI extends openai.OpenAI {
1362
1367
  constructor(config) {
1363
1368
  const {
@@ -1783,6 +1788,9 @@ class WrappedResponses extends Responses {
1783
1788
  } else {
1784
1789
  const wrappedPromise = parentPromise.then(async result => {
1785
1790
  if ('output' in result) {
1791
+ if (isPendingBackgroundResponse(openAIParams, result)) {
1792
+ return result;
1793
+ }
1786
1794
  const latency = (Date.now() - startTime) / 1000;
1787
1795
  const availableTools = extractAvailableToolCalls('openai', openAIParams);
1788
1796
  const formattedOutput = formatResponseOpenAI({
@@ -1851,6 +1859,9 @@ class WrappedResponses extends Responses {
1851
1859
  try {
1852
1860
  const parentPromise = super.parse(openAIParams, options);
1853
1861
  const wrappedPromise = parentPromise.then(async result => {
1862
+ if (isPendingBackgroundResponse(openAIParams, result)) {
1863
+ return result;
1864
+ }
1854
1865
  const latency = (Date.now() - startTime) / 1000;
1855
1866
  await captureAiGeneration(this.phClient, {
1856
1867
  ...posthogParams,