@posthog/ai 8.1.11 → 8.2.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/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.1.11";
302
+ var version = "8.2.1";
303
303
 
304
304
  const DEFAULT_MAX_DEPTH = 3;
305
305
  const MAX_STACK_LINES = 20;
@@ -352,6 +352,44 @@ function truncateStack(stack) {
352
352
  return [...lines.slice(0, MAX_STACK_LINES), '... (truncated)'].join('\n');
353
353
  }
354
354
 
355
+ // Warn when a wrapper's base_url points at the PostHog AI Gateway: the gateway
356
+ // emits its own $ai_generation, so each call would be captured (and, for billable
357
+ // products, billed) twice. We only warn — the wrapper's event carries data the
358
+ // gateway never sees (groups, custom properties, trace hierarchy).
359
+
360
+ // Keep in sync with the gateway's deployed hosts (see services/llm-gateway in the
361
+ // main repo). gateway.us.posthog.com is live today; the rest are listed ahead of
362
+ // any traffic moving to them.
363
+ const POSTHOG_AI_GATEWAY_HOSTS = ['gateway.posthog.com', 'gateway.us.posthog.com', 'gateway.eu.posthog.com', 'ai-gateway.us.posthog.com', 'ai-gateway.eu.posthog.com'];
364
+
365
+ // Swap for the dedicated AI Gateway page once it ships.
366
+ const GATEWAY_DOCS_URL = 'https://posthog.com/docs/ai-observability';
367
+ const extractHost = baseURL => {
368
+ try {
369
+ // Tolerate bare hosts that omit a scheme, e.g. "gateway.us.posthog.com/v1".
370
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(baseURL);
371
+ return new URL(hasScheme ? baseURL : `https://${baseURL}`).hostname.toLowerCase();
372
+ } catch {
373
+ return undefined;
374
+ }
375
+ };
376
+ const isPostHogAiGatewayUrl = baseURL => {
377
+ if (!baseURL) {
378
+ return false;
379
+ }
380
+ const host = extractHost(baseURL);
381
+ return host !== undefined && POSTHOG_AI_GATEWAY_HOSTS.includes(host);
382
+ };
383
+
384
+ // Warns on every gateway call by design: the misconfiguration is impossible to
385
+ // miss that way, and a doubled bill is worse than noisy logs.
386
+ const warnIfPostHogAiGateway = baseURL => {
387
+ if (!isPostHogAiGatewayUrl(baseURL)) {
388
+ return;
389
+ }
390
+ console.warn('[PostHog] The PostHog AI wrapper is pointed at the PostHog AI Gateway. ' + 'Both capture $ai_generation, so every call is double-counted and double-billed. ' + `Use one or the other — see ${GATEWAY_DOCS_URL}.`);
391
+ };
392
+
355
393
  /**
356
394
  * Options for `captureAiGeneration`. Mirrors the `$ai_generation` event shape
357
395
  * directly so that any caller — first-party SDK wrappers and external code
@@ -375,6 +413,7 @@ const captureAiGeneration = async (client, options) => {
375
413
  if (!client.capture) {
376
414
  return;
377
415
  }
416
+ warnIfPostHogAiGateway(options.baseURL);
378
417
  const traceId = options.traceId ?? uuid.v4();
379
418
  const eventType = options.eventType ?? AIEvent.Generation;
380
419
  const privacyMode = options.privacyMode ?? false;