@posthog/ai 5.2.2 → 5.2.3

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.
Files changed (54) hide show
  1. package/LICENSE +245 -0
  2. package/{lib → dist}/anthropic/index.cjs +7 -12
  3. package/{lib → dist}/anthropic/index.cjs.map +1 -1
  4. package/{lib → dist}/anthropic/index.mjs +4 -5
  5. package/{lib → dist}/anthropic/index.mjs.map +1 -1
  6. package/{lib → dist}/gemini/index.cjs +1 -1
  7. package/{lib → dist}/gemini/index.cjs.map +1 -1
  8. package/{lib → dist}/gemini/index.mjs.map +1 -1
  9. package/{lib → dist}/index.cjs +547 -479
  10. package/dist/index.cjs.map +1 -0
  11. package/{lib → dist}/index.mjs +530 -456
  12. package/dist/index.mjs.map +1 -0
  13. package/{lib → dist}/langchain/index.cjs +150 -110
  14. package/dist/langchain/index.cjs.map +1 -0
  15. package/{lib → dist}/langchain/index.mjs +147 -104
  16. package/dist/langchain/index.mjs.map +1 -0
  17. package/{lib → dist}/openai/index.cjs +7 -1
  18. package/dist/openai/index.cjs.map +1 -0
  19. package/{lib → dist}/openai/index.mjs +6 -0
  20. package/dist/openai/index.mjs.map +1 -0
  21. package/{lib → dist}/vercel/index.cjs +0 -2
  22. package/{lib → dist}/vercel/index.cjs.map +1 -1
  23. package/{lib → dist}/vercel/index.mjs.map +1 -1
  24. package/package.json +42 -33
  25. package/CHANGELOG.md +0 -89
  26. package/index.ts +0 -1
  27. package/lib/index.cjs.map +0 -1
  28. package/lib/index.mjs.map +0 -1
  29. package/lib/langchain/index.cjs.map +0 -1
  30. package/lib/langchain/index.mjs.map +0 -1
  31. package/lib/openai/index.cjs.map +0 -1
  32. package/lib/openai/index.mjs.map +0 -1
  33. package/src/anthropic/index.ts +0 -211
  34. package/src/gemini/index.ts +0 -254
  35. package/src/index.ts +0 -13
  36. package/src/langchain/callbacks.ts +0 -640
  37. package/src/langchain/index.ts +0 -1
  38. package/src/openai/azure.ts +0 -481
  39. package/src/openai/index.ts +0 -498
  40. package/src/utils.ts +0 -287
  41. package/src/vercel/index.ts +0 -1
  42. package/src/vercel/middleware.ts +0 -393
  43. package/tests/callbacks.test.ts +0 -48
  44. package/tests/gemini.test.ts +0 -344
  45. package/tests/openai.test.ts +0 -403
  46. package/tsconfig.json +0 -10
  47. /package/{lib → dist}/anthropic/index.d.ts +0 -0
  48. /package/{lib → dist}/gemini/index.d.ts +0 -0
  49. /package/{lib → dist}/gemini/index.mjs +0 -0
  50. /package/{lib → dist}/index.d.ts +0 -0
  51. /package/{lib → dist}/langchain/index.d.ts +0 -0
  52. /package/{lib → dist}/openai/index.d.ts +0 -0
  53. /package/{lib → dist}/vercel/index.d.ts +0 -0
  54. /package/{lib → dist}/vercel/index.mjs +0 -0
package/LICENSE ADDED
@@ -0,0 +1,245 @@
1
+ Copyright 2020 Posthog / Hiberly, Inc.
2
+
3
+ Copyright 2015 Mixpanel, Inc.
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this work except in compliance with the License.
7
+ You may obtain a copy of the License below, or at:
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+
17
+ Apache License
18
+ Version 2.0, January 2004
19
+ http://www.apache.org/licenses/
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction,
26
+ and distribution as defined by Sections 1 through 9 of this document.
27
+
28
+ "Licensor" shall mean the copyright owner or entity authorized by
29
+ the copyright owner that is granting the License.
30
+
31
+ "Legal Entity" shall mean the union of the acting entity and all
32
+ other entities that control, are controlled by, or are under common
33
+ control with that entity. For the purposes of this definition,
34
+ "control" means (i) the power, direct or indirect, to cause the
35
+ direction or management of such entity, whether by contract or
36
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
37
+ outstanding shares, or (iii) beneficial ownership of such entity.
38
+
39
+ "You" (or "Your") shall mean an individual or Legal Entity
40
+ exercising permissions granted by this License.
41
+
42
+ "Source" form shall mean the preferred form for making modifications,
43
+ including but not limited to software source code, documentation
44
+ source, and configuration files.
45
+
46
+ "Object" form shall mean any form resulting from mechanical
47
+ transformation or translation of a Source form, including but
48
+ not limited to compiled object code, generated documentation,
49
+ and conversions to other media types.
50
+
51
+ "Work" shall mean the work of authorship, whether in Source or
52
+ Object form, made available under the License, as indicated by a
53
+ copyright notice that is included in or attached to the work
54
+ (an example is provided in the Appendix below).
55
+
56
+ "Derivative Works" shall mean any work, whether in Source or Object
57
+ form, that is based on (or derived from) the Work and for which the
58
+ editorial revisions, annotations, elaborations, or other modifications
59
+ represent, as a whole, an original work of authorship. For the purposes
60
+ of this License, Derivative Works shall not include works that remain
61
+ separable from, or merely link (or bind by name) to the interfaces of,
62
+ the Work and Derivative Works thereof.
63
+
64
+ "Contribution" shall mean any work of authorship, including
65
+ the original version of the Work and any modifications or additions
66
+ to that Work or Derivative Works thereof, that is intentionally
67
+ submitted to Licensor for inclusion in the Work by the copyright owner
68
+ or by an individual or Legal Entity authorized to submit on behalf of
69
+ the copyright owner. For the purposes of this definition, "submitted"
70
+ means any form of electronic, verbal, or written communication sent
71
+ to the Licensor or its representatives, including but not limited to
72
+ communication on electronic mailing lists, source code control systems,
73
+ and issue tracking systems that are managed by, or on behalf of, the
74
+ Licensor for the purpose of discussing and improving the Work, but
75
+ excluding communication that is conspicuously marked or otherwise
76
+ designated in writing by the copyright owner as "Not a Contribution."
77
+
78
+ "Contributor" shall mean Licensor and any individual or Legal Entity
79
+ on behalf of whom a Contribution has been received by Licensor and
80
+ subsequently incorporated within the Work.
81
+
82
+ 2. Grant of Copyright License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ copyright license to reproduce, prepare Derivative Works of,
86
+ publicly display, publicly perform, sublicense, and distribute the
87
+ Work and such Derivative Works in Source or Object form.
88
+
89
+ 3. Grant of Patent License. Subject to the terms and conditions of
90
+ this License, each Contributor hereby grants to You a perpetual,
91
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
92
+ (except as stated in this section) patent license to make, have made,
93
+ use, offer to sell, sell, import, and otherwise transfer the Work,
94
+ where such license applies only to those patent claims licensable
95
+ by such Contributor that are necessarily infringed by their
96
+ Contribution(s) alone or by combination of their Contribution(s)
97
+ with the Work to which such Contribution(s) was submitted. If You
98
+ institute patent litigation against any entity (including a
99
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
100
+ or a Contribution incorporated within the Work constitutes direct
101
+ or contributory patent infringement, then any patent licenses
102
+ granted to You under this License for that Work shall terminate
103
+ as of the date such litigation is filed.
104
+
105
+ 4. Redistribution. You may reproduce and distribute copies of the
106
+ Work or Derivative Works thereof in any medium, with or without
107
+ modifications, and in Source or Object form, provided that You
108
+ meet the following conditions:
109
+
110
+ (a) You must give any other recipients of the Work or
111
+ Derivative Works a copy of this License; and
112
+
113
+ (b) You must cause any modified files to carry prominent notices
114
+ stating that You changed the files; and
115
+
116
+ (c) You must retain, in the Source form of any Derivative Works
117
+ that You distribute, all copyright, patent, trademark, and
118
+ attribution notices from the Source form of the Work,
119
+ excluding those notices that do not pertain to any part of
120
+ the Derivative Works; and
121
+
122
+ (d) If the Work includes a "NOTICE" text file as part of its
123
+ distribution, then any Derivative Works that You distribute must
124
+ include a readable copy of the attribution notices contained
125
+ within such NOTICE file, excluding those notices that do not
126
+ pertain to any part of the Derivative Works, in at least one
127
+ of the following places: within a NOTICE text file distributed
128
+ as part of the Derivative Works; within the Source form or
129
+ documentation, if provided along with the Derivative Works; or,
130
+ within a display generated by the Derivative Works, if and
131
+ wherever such third-party notices normally appear. The contents
132
+ of the NOTICE file are for informational purposes only and
133
+ do not modify the License. You may add Your own attribution
134
+ notices within Derivative Works that You distribute, alongside
135
+ or as an addendum to the NOTICE text from the Work, provided
136
+ that such additional attribution notices cannot be construed
137
+ as modifying the License.
138
+
139
+ You may add Your own copyright statement to Your modifications and
140
+ may provide additional or different license terms and conditions
141
+ for use, reproduction, or distribution of Your modifications, or
142
+ for any such Derivative Works as a whole, provided Your use,
143
+ reproduction, and distribution of the Work otherwise complies with
144
+ the conditions stated in this License.
145
+
146
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
147
+ any Contribution intentionally submitted for inclusion in the Work
148
+ by You to the Licensor shall be under the terms and conditions of
149
+ this License, without any additional terms or conditions.
150
+ Notwithstanding the above, nothing herein shall supersede or modify
151
+ the terms of any separate license agreement you may have executed
152
+ with Licensor regarding such Contributions.
153
+
154
+ 6. Trademarks. This License does not grant permission to use the trade
155
+ names, trademarks, service marks, or product names of the Licensor,
156
+ except as required for reasonable and customary use in describing the
157
+ origin of the Work and reproducing the content of the NOTICE file.
158
+
159
+ 7. Disclaimer of Warranty. Unless required by applicable law or
160
+ agreed to in writing, Licensor provides the Work (and each
161
+ Contributor provides its Contributions) on an "AS IS" BASIS,
162
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
163
+ implied, including, without limitation, any warranties or conditions
164
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
165
+ PARTICULAR PURPOSE. You are solely responsible for determining the
166
+ appropriateness of using or redistributing the Work and assume any
167
+ risks associated with Your exercise of permissions under this License.
168
+
169
+ 8. Limitation of Liability. In no event and under no legal theory,
170
+ whether in tort (including negligence), contract, or otherwise,
171
+ unless required by applicable law (such as deliberate and grossly
172
+ negligent acts) or agreed to in writing, shall any Contributor be
173
+ liable to You for damages, including any direct, indirect, special,
174
+ incidental, or consequential damages of any character arising as a
175
+ result of this License or out of the use or inability to use the
176
+ Work (including but not limited to damages for loss of goodwill,
177
+ work stoppage, computer failure or malfunction, or any and all
178
+ other commercial damages or losses), even if such Contributor
179
+ has been advised of the possibility of such damages.
180
+
181
+ 9. Accepting Warranty or Additional Liability. While redistributing
182
+ the Work or Derivative Works thereof, You may choose to offer,
183
+ and charge a fee for, acceptance of support, warranty, indemnity,
184
+ or other liability obligations and/or rights consistent with this
185
+ License. However, in accepting such obligations, You may act only
186
+ on Your own behalf and on Your sole responsibility, not on behalf
187
+ of any other Contributor, and only if You agree to indemnify,
188
+ defend, and hold each Contributor harmless for any liability
189
+ incurred by, or claims asserted against, such Contributor by reason
190
+ of your accepting any such warranty or additional liability.
191
+
192
+ END OF TERMS AND CONDITIONS
193
+
194
+ APPENDIX: How to apply the Apache License to your work.
195
+
196
+ To apply the Apache License to your work, attach the following
197
+ boilerplate notice, with the fields enclosed by brackets "[]"
198
+ replaced with your own identifying information. (Don't include
199
+ the brackets!) The text should be enclosed in the appropriate
200
+ comment syntax for the file format. We also recommend that a
201
+ file or class name and description of purpose be included on the
202
+ same "printed page" as the copyright notice for easier
203
+ identification within third-party archives.
204
+
205
+ Copyright [yyyy] [name of copyright owner]
206
+
207
+ Licensed under the Apache License, Version 2.0 (the "License");
208
+ you may not use this file except in compliance with the License.
209
+ You may obtain a copy of the License at
210
+
211
+ http://www.apache.org/licenses/LICENSE-2.0
212
+
213
+ Unless required by applicable law or agreed to in writing, software
214
+ distributed under the License is distributed on an "AS IS" BASIS,
215
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
216
+ See the License for the specific language governing permissions and
217
+ limitations under the License.
218
+
219
+
220
+ ---
221
+
222
+ Some files in this codebase contain code from getsentry/sentry-javascript by Software, Inc. dba Sentry.
223
+ In such cases it is explicitly stated in the file header. This license only applies to the relevant code in such cases.
224
+
225
+ MIT License
226
+
227
+ Copyright (c) 2012 Functional Software, Inc. dba Sentry
228
+
229
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
230
+ this software and associated documentation files (the "Software"), to deal in
231
+ the Software without restriction, including without limitation the rights to
232
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
233
+ of the Software, and to permit persons to whom the Software is furnished to do
234
+ so, subject to the following conditions:
235
+
236
+ The above copyright notice and this permission notice shall be included in all
237
+ copies or substantial portions of the Software.
238
+
239
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
240
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
241
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
242
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
243
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
244
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
245
+ SOFTWARE.
@@ -6,10 +6,6 @@ var AnthropicOriginal = require('@anthropic-ai/sdk');
6
6
  var uuid = require('uuid');
7
7
  var buffer = require('buffer');
8
8
 
9
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
-
11
- var AnthropicOriginal__default = /*#__PURE__*/_interopDefaultLegacy(AnthropicOriginal);
12
-
13
9
  const STRING_FORMAT = 'utf8';
14
10
  const getModelParams = params => {
15
11
  if (!params) {
@@ -38,7 +34,7 @@ const formatResponseAnthropic = response => {
38
34
  return output;
39
35
  };
40
36
  const mergeSystemPrompt = (params, provider) => {
41
- if (provider == 'anthropic') {
37
+ {
42
38
  const messages = params.messages || [];
43
39
  if (!params.system) {
44
40
  return messages;
@@ -49,7 +45,6 @@ const mergeSystemPrompt = (params, provider) => {
49
45
  content: systemMessage
50
46
  }, ...messages];
51
47
  }
52
- return params.messages;
53
48
  };
54
49
  const withPrivacyMode = (client, privacyMode, input) => {
55
50
  return client.privacy_mode || privacyMode ? null : input;
@@ -158,7 +153,7 @@ const sendEventToPosthog = async ({
158
153
  }
159
154
  };
160
155
 
161
- class PostHogAnthropic extends AnthropicOriginal__default["default"] {
156
+ class PostHogAnthropic extends AnthropicOriginal {
162
157
  constructor(config) {
163
158
  const {
164
159
  posthog,
@@ -169,7 +164,7 @@ class PostHogAnthropic extends AnthropicOriginal__default["default"] {
169
164
  this.messages = new WrappedMessages(this, this.phClient);
170
165
  }
171
166
  }
172
- class WrappedMessages extends AnthropicOriginal__default["default"].Messages {
167
+ class WrappedMessages extends AnthropicOriginal.Messages {
173
168
  constructor(parentClient, phClient) {
174
169
  super(parentClient);
175
170
  this.phClient = phClient;
@@ -244,7 +239,7 @@ class WrappedMessages extends AnthropicOriginal__default["default"].Messages {
244
239
  traceId,
245
240
  model: anthropicParams.model,
246
241
  provider: 'anthropic',
247
- input: mergeSystemPrompt(anthropicParams, 'anthropic'),
242
+ input: mergeSystemPrompt(anthropicParams),
248
243
  output: [],
249
244
  latency: 0,
250
245
  baseURL: this.baseURL ?? '',
@@ -276,7 +271,7 @@ class WrappedMessages extends AnthropicOriginal__default["default"].Messages {
276
271
  traceId,
277
272
  model: anthropicParams.model,
278
273
  provider: 'anthropic',
279
- input: mergeSystemPrompt(anthropicParams, 'anthropic'),
274
+ input: mergeSystemPrompt(anthropicParams),
280
275
  output: formatResponseAnthropic(result),
281
276
  latency,
282
277
  baseURL: this.baseURL ?? '',
@@ -299,7 +294,7 @@ class WrappedMessages extends AnthropicOriginal__default["default"].Messages {
299
294
  traceId,
300
295
  model: anthropicParams.model,
301
296
  provider: 'anthropic',
302
- input: mergeSystemPrompt(anthropicParams, 'anthropic'),
297
+ input: mergeSystemPrompt(anthropicParams),
303
298
  output: [],
304
299
  latency: 0,
305
300
  baseURL: this.baseURL ?? '',
@@ -323,5 +318,5 @@ class WrappedMessages extends AnthropicOriginal__default["default"].Messages {
323
318
  exports.Anthropic = PostHogAnthropic;
324
319
  exports.PostHogAnthropic = PostHogAnthropic;
325
320
  exports.WrappedMessages = WrappedMessages;
326
- exports["default"] = PostHogAnthropic;
321
+ exports.default = PostHogAnthropic;
327
322
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../src/utils.ts","../../src/anthropic/index.ts"],"sourcesContent":["import { PostHog } from 'posthog-node'\nimport { Buffer } from 'buffer'\nimport OpenAIOrignal from 'openai'\nimport AnthropicOriginal from '@anthropic-ai/sdk'\n\ntype ChatCompletionCreateParamsBase = OpenAIOrignal.Chat.Completions.ChatCompletionCreateParams\ntype MessageCreateParams = AnthropicOriginal.Messages.MessageCreateParams\ntype ResponseCreateParams = OpenAIOrignal.Responses.ResponseCreateParams\n\n// limit large outputs by truncating to 200kb (approx 200k bytes)\nexport const MAX_OUTPUT_SIZE = 200000\nconst STRING_FORMAT = 'utf8'\n\nexport interface MonitoringParams {\n posthogDistinctId?: string\n posthogTraceId?: string\n posthogProperties?: Record<string, any>\n posthogPrivacyMode?: boolean\n posthogGroups?: Record<string, any>\n posthogModelOverride?: string\n posthogProviderOverride?: string\n posthogCostOverride?: CostOverride\n posthogCaptureImmediate?: boolean\n}\n\nexport interface CostOverride {\n inputCost: number\n outputCost: number\n}\n\nexport const getModelParams = (\n params: ((ChatCompletionCreateParamsBase | MessageCreateParams | ResponseCreateParams) & MonitoringParams) | null\n): Record<string, any> => {\n if (!params) {\n return {}\n }\n const modelParams: Record<string, any> = {}\n const paramKeys = [\n 'temperature',\n 'max_tokens',\n 'max_completion_tokens',\n 'top_p',\n 'frequency_penalty',\n 'presence_penalty',\n 'n',\n 'stop',\n 'stream',\n 'streaming',\n ] as const\n\n for (const key of paramKeys) {\n if (key in params && (params as any)[key] !== undefined) {\n modelParams[key] = (params as any)[key]\n }\n }\n return modelParams\n}\n\n/**\n * Helper to format responses (non-streaming) for consumption, mirroring Python's openai vs. anthropic approach.\n */\nexport const formatResponse = (response: any, provider: string): Array<{ role: string; content: string }> => {\n if (!response) {\n return []\n }\n if (provider === 'anthropic') {\n return formatResponseAnthropic(response)\n } else if (provider === 'openai') {\n return formatResponseOpenAI(response)\n } else if (provider === 'gemini') {\n return formatResponseGemini(response)\n }\n return []\n}\n\nexport const formatResponseAnthropic = (response: any): Array<{ role: string; content: string }> => {\n // Example approach if \"response.content\" holds array of text segments, etc.\n const output: Array<{ role: string; content: string }> = []\n for (const choice of response.content ?? []) {\n if (choice?.text) {\n output.push({\n role: 'assistant',\n content: choice.text,\n })\n }\n }\n return output\n}\n\nexport const formatResponseOpenAI = (response: any): Array<{ role: string; content: string }> => {\n const output: Array<{ role: string; content: string }> = []\n for (const choice of response.choices ?? []) {\n if (choice.message?.content) {\n output.push({\n role: choice.message.role,\n content: choice.message.content,\n })\n }\n }\n return output\n}\n\nexport const formatResponseGemini = (response: any): Array<{ role: string; content: string }> => {\n const output: Array<{ role: string; content: string }> = []\n\n if (response.text) {\n output.push({\n role: 'assistant',\n content: response.text,\n })\n return output\n }\n\n if (response.candidates && Array.isArray(response.candidates)) {\n for (const candidate of response.candidates) {\n if (candidate.content && candidate.content.parts) {\n const text = candidate.content.parts\n .filter((part: any) => part.text)\n .map((part: any) => part.text)\n .join('')\n if (text) {\n output.push({\n role: 'assistant',\n content: text,\n })\n }\n }\n }\n }\n\n return output\n}\n\nexport const mergeSystemPrompt = (params: MessageCreateParams & MonitoringParams, provider: string): any => {\n if (provider == 'anthropic') {\n const messages = params.messages || []\n if (!(params as any).system) {\n return messages\n }\n const systemMessage = (params as any).system\n return [{ role: 'system', content: systemMessage }, ...messages]\n }\n return params.messages\n}\n\nexport const withPrivacyMode = (client: PostHog, privacyMode: boolean, input: any): any => {\n return (client as any).privacy_mode || privacyMode ? null : input\n}\n\nexport const truncate = (str: string): string => {\n try {\n const buffer = Buffer.from(str, STRING_FORMAT)\n if (buffer.length <= MAX_OUTPUT_SIZE) {\n return str\n }\n const truncatedBuffer = buffer.slice(0, MAX_OUTPUT_SIZE)\n return `${truncatedBuffer.toString(STRING_FORMAT)}... [truncated]`\n } catch (error) {\n console.error('Error truncating, likely not a string')\n return str\n }\n}\n\nexport type SendEventToPosthogParams = {\n client: PostHog\n distinctId?: string\n traceId: string\n model: string\n provider: string\n input: any\n output: any\n latency: number\n baseURL: string\n httpStatus: number\n usage?: {\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: any\n cacheReadInputTokens?: any\n cacheCreationInputTokens?: any\n }\n params: (ChatCompletionCreateParamsBase | MessageCreateParams | ResponseCreateParams) & MonitoringParams\n isError?: boolean\n error?: string\n tools?: any\n captureImmediate?: boolean\n}\n\nfunction sanitizeValues(obj: any): any {\n if (obj === undefined || obj === null) {\n return obj\n }\n const jsonSafe = JSON.parse(JSON.stringify(obj))\n if (typeof jsonSafe === 'string') {\n return Buffer.from(jsonSafe, STRING_FORMAT).toString(STRING_FORMAT)\n } else if (Array.isArray(jsonSafe)) {\n return jsonSafe.map(sanitizeValues)\n } else if (jsonSafe && typeof jsonSafe === 'object') {\n return Object.fromEntries(Object.entries(jsonSafe).map(([k, v]) => [k, sanitizeValues(v)]))\n }\n return jsonSafe\n}\n\nexport const sendEventToPosthog = async ({\n client,\n distinctId,\n traceId,\n model,\n provider,\n input,\n output,\n latency,\n baseURL,\n params,\n httpStatus = 200,\n usage = {},\n isError = false,\n error,\n tools,\n captureImmediate = false,\n}: SendEventToPosthogParams): Promise<void> => {\n if (!client.capture) {\n return Promise.resolve()\n }\n // sanitize input and output for UTF-8 validity\n const safeInput = sanitizeValues(input)\n const safeOutput = sanitizeValues(output)\n const safeError = sanitizeValues(error)\n\n let errorData = {}\n if (isError) {\n errorData = {\n $ai_is_error: true,\n $ai_error: safeError,\n }\n }\n let costOverrideData = {}\n if (params.posthogCostOverride) {\n const inputCostUSD = (params.posthogCostOverride.inputCost ?? 0) * (usage.inputTokens ?? 0)\n const outputCostUSD = (params.posthogCostOverride.outputCost ?? 0) * (usage.outputTokens ?? 0)\n costOverrideData = {\n $ai_input_cost_usd: inputCostUSD,\n $ai_output_cost_usd: outputCostUSD,\n $ai_total_cost_usd: inputCostUSD + outputCostUSD,\n }\n }\n\n const additionalTokenValues = {\n ...(usage.reasoningTokens ? { $ai_reasoning_tokens: usage.reasoningTokens } : {}),\n ...(usage.cacheReadInputTokens ? { $ai_cache_read_input_tokens: usage.cacheReadInputTokens } : {}),\n ...(usage.cacheCreationInputTokens ? { $ai_cache_creation_input_tokens: usage.cacheCreationInputTokens } : {}),\n }\n\n const properties = {\n $ai_provider: params.posthogProviderOverride ?? provider,\n $ai_model: params.posthogModelOverride ?? model,\n $ai_model_parameters: getModelParams(params),\n $ai_input: withPrivacyMode(client, params.posthogPrivacyMode ?? false, safeInput),\n $ai_output_choices: withPrivacyMode(client, params.posthogPrivacyMode ?? false, safeOutput),\n $ai_http_status: httpStatus,\n $ai_input_tokens: usage.inputTokens ?? 0,\n $ai_output_tokens: usage.outputTokens ?? 0,\n ...additionalTokenValues,\n $ai_latency: latency,\n $ai_trace_id: traceId,\n $ai_base_url: baseURL,\n ...params.posthogProperties,\n ...(distinctId ? {} : { $process_person_profile: false }),\n ...(tools ? { $ai_tools: tools } : {}),\n ...errorData,\n ...costOverrideData,\n }\n\n const event = {\n distinctId: distinctId ?? traceId,\n event: '$ai_generation',\n properties,\n groups: params.posthogGroups,\n }\n\n if (captureImmediate) {\n // await capture promise to send single event in serverless environments\n await client.captureImmediate(event)\n } else {\n client.capture(event)\n }\n}\n","import AnthropicOriginal from '@anthropic-ai/sdk'\nimport { PostHog } from 'posthog-node'\nimport { v4 as uuidv4 } from 'uuid'\nimport { formatResponseAnthropic, mergeSystemPrompt, MonitoringParams, sendEventToPosthog } from '../utils'\n\ntype MessageCreateParamsNonStreaming = AnthropicOriginal.Messages.MessageCreateParamsNonStreaming\ntype MessageCreateParamsStreaming = AnthropicOriginal.Messages.MessageCreateParamsStreaming\ntype MessageCreateParams = AnthropicOriginal.Messages.MessageCreateParams\ntype Message = AnthropicOriginal.Messages.Message\ntype RawMessageStreamEvent = AnthropicOriginal.Messages.RawMessageStreamEvent\ntype MessageCreateParamsBase = AnthropicOriginal.Messages.MessageCreateParams\n\nimport type { APIPromise, RequestOptions } from '@anthropic-ai/sdk/core'\nimport type { Stream } from '@anthropic-ai/sdk/streaming'\n\ninterface MonitoringAnthropicConfig {\n apiKey: string\n posthog: PostHog\n baseURL?: string\n}\n\nexport class PostHogAnthropic extends AnthropicOriginal {\n private readonly phClient: PostHog\n public messages: WrappedMessages\n\n constructor(config: MonitoringAnthropicConfig) {\n const { posthog, ...anthropicConfig } = config\n super(anthropicConfig)\n this.phClient = posthog\n this.messages = new WrappedMessages(this, this.phClient)\n }\n}\n\nexport class WrappedMessages extends AnthropicOriginal.Messages {\n private readonly phClient: PostHog\n\n constructor(parentClient: PostHogAnthropic, phClient: PostHog) {\n super(parentClient)\n this.phClient = phClient\n }\n\n public create(body: MessageCreateParamsNonStreaming, options?: RequestOptions): APIPromise<Message>\n public create(\n body: MessageCreateParamsStreaming & MonitoringParams,\n options?: RequestOptions\n ): APIPromise<Stream<RawMessageStreamEvent>>\n public create(\n body: MessageCreateParamsBase & MonitoringParams,\n options?: RequestOptions\n ): APIPromise<Stream<RawMessageStreamEvent> | Message>\n public create(\n body: MessageCreateParams & MonitoringParams,\n options?: RequestOptions\n ): APIPromise<Message> | APIPromise<Stream<RawMessageStreamEvent>> {\n const {\n posthogDistinctId,\n posthogTraceId,\n posthogProperties,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n posthogPrivacyMode = false,\n posthogGroups,\n posthogCaptureImmediate,\n ...anthropicParams\n } = body\n\n const traceId = posthogTraceId ?? uuidv4()\n const startTime = Date.now()\n\n const parentPromise = super.create(anthropicParams, options)\n\n if (anthropicParams.stream) {\n return parentPromise.then((value) => {\n let accumulatedContent = ''\n const usage: {\n inputTokens: number\n outputTokens: number\n cacheCreationInputTokens?: number\n cacheReadInputTokens?: number\n } = {\n inputTokens: 0,\n outputTokens: 0,\n cacheCreationInputTokens: 0,\n cacheReadInputTokens: 0,\n }\n if ('tee' in value) {\n const [stream1, stream2] = value.tee()\n ;(async () => {\n try {\n for await (const chunk of stream1) {\n if ('delta' in chunk) {\n if ('text' in chunk.delta) {\n const delta = chunk?.delta?.text ?? ''\n accumulatedContent += delta\n }\n }\n if (chunk.type == 'message_start') {\n usage.inputTokens = chunk.message.usage.input_tokens ?? 0\n usage.cacheCreationInputTokens = chunk.message.usage.cache_creation_input_tokens ?? 0\n usage.cacheReadInputTokens = chunk.message.usage.cache_read_input_tokens ?? 0\n }\n if ('usage' in chunk) {\n usage.outputTokens = chunk.usage.output_tokens ?? 0\n }\n }\n const latency = (Date.now() - startTime) / 1000\n await sendEventToPosthog({\n client: this.phClient,\n distinctId: posthogDistinctId,\n traceId,\n model: anthropicParams.model,\n provider: 'anthropic',\n input: mergeSystemPrompt(anthropicParams, 'anthropic'),\n output: [{ content: accumulatedContent, role: 'assistant' }],\n latency,\n baseURL: (this as any).baseURL ?? '',\n params: body,\n httpStatus: 200,\n usage,\n captureImmediate: posthogCaptureImmediate,\n })\n } catch (error: any) {\n // error handling\n await sendEventToPosthog({\n client: this.phClient,\n distinctId: posthogDistinctId,\n traceId,\n model: anthropicParams.model,\n provider: 'anthropic',\n input: mergeSystemPrompt(anthropicParams, 'anthropic'),\n output: [],\n latency: 0,\n baseURL: (this as any).baseURL ?? '',\n params: body,\n httpStatus: error?.status ? error.status : 500,\n usage: {\n inputTokens: 0,\n outputTokens: 0,\n },\n isError: true,\n error: JSON.stringify(error),\n captureImmediate: posthogCaptureImmediate,\n })\n }\n })()\n\n // Return the other stream to the user\n return stream2\n }\n return value\n }) as APIPromise<Stream<RawMessageStreamEvent>>\n } else {\n const wrappedPromise = parentPromise.then(\n async (result) => {\n if ('content' in result) {\n const latency = (Date.now() - startTime) / 1000\n await sendEventToPosthog({\n client: this.phClient,\n distinctId: posthogDistinctId,\n traceId,\n model: anthropicParams.model,\n provider: 'anthropic',\n input: mergeSystemPrompt(anthropicParams, 'anthropic'),\n output: formatResponseAnthropic(result),\n latency,\n baseURL: (this as any).baseURL ?? '',\n params: body,\n httpStatus: 200,\n usage: {\n inputTokens: result.usage.input_tokens ?? 0,\n outputTokens: result.usage.output_tokens ?? 0,\n cacheCreationInputTokens: result.usage.cache_creation_input_tokens ?? 0,\n cacheReadInputTokens: result.usage.cache_read_input_tokens ?? 0,\n },\n captureImmediate: posthogCaptureImmediate,\n })\n }\n return result\n },\n async (error: any) => {\n await sendEventToPosthog({\n client: this.phClient,\n distinctId: posthogDistinctId,\n traceId,\n model: anthropicParams.model,\n provider: 'anthropic',\n input: mergeSystemPrompt(anthropicParams, 'anthropic'),\n output: [],\n latency: 0,\n baseURL: (this as any).baseURL ?? '',\n params: body,\n httpStatus: error?.status ? error.status : 500,\n usage: {\n inputTokens: 0,\n outputTokens: 0,\n },\n isError: true,\n error: JSON.stringify(error),\n captureImmediate: posthogCaptureImmediate,\n })\n throw error\n }\n ) as APIPromise<Message>\n\n return wrappedPromise\n }\n }\n}\n\nexport default PostHogAnthropic\n\nexport { PostHogAnthropic as Anthropic }\n"],"names":["STRING_FORMAT","getModelParams","params","modelParams","paramKeys","key","undefined","formatResponseAnthropic","response","output","choice","content","text","push","role","mergeSystemPrompt","provider","messages","system","systemMessage","withPrivacyMode","client","privacyMode","input","privacy_mode","sanitizeValues","obj","jsonSafe","JSON","parse","stringify","Buffer","from","toString","Array","isArray","map","Object","fromEntries","entries","k","v","sendEventToPosthog","distinctId","traceId","model","latency","baseURL","httpStatus","usage","isError","error","tools","captureImmediate","capture","Promise","resolve","safeInput","safeOutput","safeError","errorData","$ai_is_error","$ai_error","costOverrideData","posthogCostOverride","inputCostUSD","inputCost","inputTokens","outputCostUSD","outputCost","outputTokens","$ai_input_cost_usd","$ai_output_cost_usd","$ai_total_cost_usd","additionalTokenValues","reasoningTokens","$ai_reasoning_tokens","cacheReadInputTokens","$ai_cache_read_input_tokens","cacheCreationInputTokens","$ai_cache_creation_input_tokens","properties","$ai_provider","posthogProviderOverride","$ai_model","posthogModelOverride","$ai_model_parameters","$ai_input","posthogPrivacyMode","$ai_output_choices","$ai_http_status","$ai_input_tokens","$ai_output_tokens","$ai_latency","$ai_trace_id","$ai_base_url","posthogProperties","$process_person_profile","$ai_tools","event","groups","posthogGroups","PostHogAnthropic","AnthropicOriginal","constructor","config","posthog","anthropicConfig","phClient","WrappedMessages","Messages","parentClient","create","body","options","posthogDistinctId","posthogTraceId","posthogCaptureImmediate","anthropicParams","uuidv4","startTime","Date","now","parentPromise","stream","then","value","accumulatedContent","stream1","stream2","tee","chunk","delta","type","message","input_tokens","cache_creation_input_tokens","cache_read_input_tokens","output_tokens","status","wrappedPromise","result"],"mappings":";;;;;;;;;;;;AAWA,MAAMA,aAAa,GAAG,MAAM,CAAA;AAmBrB,MAAMC,cAAc,GACzBC,MAAiH,IACzF;EACxB,IAAI,CAACA,MAAM,EAAE;AACX,IAAA,OAAO,EAAE,CAAA;AACX,GAAA;EACA,MAAMC,WAAgC,GAAG,EAAE,CAAA;EAC3C,MAAMC,SAAS,GAAG,CAChB,aAAa,EACb,YAAY,EACZ,uBAAuB,EACvB,OAAO,EACP,mBAAmB,EACnB,kBAAkB,EAClB,GAAG,EACH,MAAM,EACN,QAAQ,EACR,WAAW,CACH,CAAA;AAEV,EAAA,KAAK,MAAMC,GAAG,IAAID,SAAS,EAAE;IAC3B,IAAIC,GAAG,IAAIH,MAAM,IAAKA,MAAM,CAASG,GAAG,CAAC,KAAKC,SAAS,EAAE;AACvDH,MAAAA,WAAW,CAACE,GAAG,CAAC,GAAIH,MAAM,CAASG,GAAG,CAAC,CAAA;AACzC,KAAA;AACF,GAAA;AACA,EAAA,OAAOF,WAAW,CAAA;AACpB,CAAC,CAAA;AAmBM,MAAMI,uBAAuB,GAAIC,QAAa,IAA+C;AAClG;EACA,MAAMC,MAAgD,GAAG,EAAE,CAAA;EAC3D,KAAK,MAAMC,MAAM,IAAIF,QAAQ,CAACG,OAAO,IAAI,EAAE,EAAE;IAC3C,IAAID,MAAM,EAAEE,IAAI,EAAE;MAChBH,MAAM,CAACI,IAAI,CAAC;AACVC,QAAAA,IAAI,EAAE,WAAW;Q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ACwF,uBAAuB,IAAI,CAAA;aAC/D;AACDpF,YAAAA,gBAAgB,EAAEgE,uBAAAA;AACpB,WAAC,CAAC,CAAA;AACJ,SAAA;AACA,QAAA,OAAOwB,MAAM,CAAA;OACd,EACD,MAAO1F,KAAU,IAAK;AACpB,QAAA,MAAMT,kBAAkB,CAAC;UACvBrB,MAAM,EAAE,IAAI,CAACuF,QAAQ;AACrBjE,UAAAA,UAAU,EAAEwE,iBAAiB;UAC7BvE,OAAO;UACPC,KAAK,EAAEyE,eAAe,CAACzE,KAAK;AAC5B7B,UAAAA,QAAQ,EAAE,WAAW;AACrBO,UAAAA,KAAK,EAAER,iBAAiB,CAACuG,eAAe,EAAE,WAAW,CAAC;AACtD7G,UAAAA,MAAM,EAAE,EAAE;AACVqC,UAAAA,OAAO,EAAE,CAAC;AACVC,UAAAA,OAAO,EAAG,IAAI,CAASA,OAAO,IAAI,EAAE;AACpC7C,UAAAA,MAAM,EAAE+G,IAAI;UACZjE,UAAU,EAAEG,KAAK,EAAEwF,MAAM,GAAGxF,KAAK,CAACwF,MAAM,GAAG,GAAG;AAC9C1F,UAAAA,KAAK,EAAE;AACLkB,YAAAA,WAAW,EAAE,CAAC;AACdG,YAAAA,YAAY,EAAE,CAAA;WACf;AACDpB,UAAAA,OAAO,EAAE,IAAI;AACbC,UAAAA,KAAK,EAAEvB,IAAI,CAACE,SAAS,CAACqB,KAAK,CAAC;AAC5BE,UAAAA,gBAAgB,EAAEgE,uBAAAA;AACpB,SAAC,CAAC,CAAA;AACF,QAAA,MAAMlE,KAAK,CAAA;AACb,OACF,CAAwB,CAAA;AAExB,MAAA,OAAOyF,cAAc,CAAA;AACvB,KAAA;AACF,GAAA;AACF;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":["../../src/utils.ts","../../src/anthropic/index.ts"],"sourcesContent":["import { PostHog } from 'posthog-node'\nimport { Buffer } from 'buffer'\nimport OpenAIOrignal from 'openai'\nimport AnthropicOriginal from '@anthropic-ai/sdk'\n\ntype ChatCompletionCreateParamsBase = OpenAIOrignal.Chat.Completions.ChatCompletionCreateParams\ntype MessageCreateParams = AnthropicOriginal.Messages.MessageCreateParams\ntype ResponseCreateParams = OpenAIOrignal.Responses.ResponseCreateParams\n\n// limit large outputs by truncating to 200kb (approx 200k bytes)\nexport const MAX_OUTPUT_SIZE = 200000\nconst STRING_FORMAT = 'utf8'\n\nexport interface MonitoringParams {\n posthogDistinctId?: string\n posthogTraceId?: string\n posthogProperties?: Record<string, any>\n posthogPrivacyMode?: boolean\n posthogGroups?: Record<string, any>\n posthogModelOverride?: string\n posthogProviderOverride?: string\n posthogCostOverride?: CostOverride\n posthogCaptureImmediate?: boolean\n}\n\nexport interface CostOverride {\n inputCost: number\n outputCost: number\n}\n\nexport const getModelParams = (\n params: ((ChatCompletionCreateParamsBase | MessageCreateParams | ResponseCreateParams) & MonitoringParams) | null\n): Record<string, any> => {\n if (!params) {\n return {}\n }\n const modelParams: Record<string, any> = {}\n const paramKeys = [\n 'temperature',\n 'max_tokens',\n 'max_completion_tokens',\n 'top_p',\n 'frequency_penalty',\n 'presence_penalty',\n 'n',\n 'stop',\n 'stream',\n 'streaming',\n ] as const\n\n for (const key of paramKeys) {\n if (key in params && (params as any)[key] !== undefined) {\n modelParams[key] = (params as any)[key]\n }\n }\n return modelParams\n}\n\n/**\n * Helper to format responses (non-streaming) for consumption, mirroring Python's openai vs. anthropic approach.\n */\nexport const formatResponse = (response: any, provider: string): Array<{ role: string; content: string }> => {\n if (!response) {\n return []\n }\n if (provider === 'anthropic') {\n return formatResponseAnthropic(response)\n } else if (provider === 'openai') {\n return formatResponseOpenAI(response)\n } else if (provider === 'gemini') {\n return formatResponseGemini(response)\n }\n return []\n}\n\nexport const formatResponseAnthropic = (response: any): Array<{ role: string; content: string }> => {\n // Example approach if \"response.content\" holds array of text segments, etc.\n const output: Array<{ role: string; content: string }> = []\n for (const choice of response.content ?? []) {\n if (choice?.text) {\n output.push({\n role: 'assistant',\n content: choice.text,\n })\n }\n }\n return output\n}\n\nexport const formatResponseOpenAI = (response: any): Array<{ role: string; content: string }> => {\n const output: Array<{ role: string; content: string }> = []\n for (const choice of response.choices ?? []) {\n if (choice.message?.content) {\n output.push({\n role: choice.message.role,\n content: choice.message.content,\n })\n }\n }\n return output\n}\n\nexport const formatResponseGemini = (response: any): Array<{ role: string; content: string }> => {\n const output: Array<{ role: string; content: string }> = []\n\n if (response.text) {\n output.push({\n role: 'assistant',\n content: response.text,\n })\n return output\n }\n\n if (response.candidates && Array.isArray(response.candidates)) {\n for (const candidate of response.candidates) {\n if (candidate.content && candidate.content.parts) {\n const text = candidate.content.parts\n .filter((part: any) => part.text)\n .map((part: any) => part.text)\n .join('')\n if (text) {\n output.push({\n role: 'assistant',\n content: text,\n })\n }\n }\n }\n }\n\n return output\n}\n\nexport const mergeSystemPrompt = (params: MessageCreateParams & MonitoringParams, provider: string): any => {\n if (provider == 'anthropic') {\n const messages = params.messages || []\n if (!(params as any).system) {\n return messages\n }\n const systemMessage = (params as any).system\n return [{ role: 'system', content: systemMessage }, ...messages]\n }\n return params.messages\n}\n\nexport const withPrivacyMode = (client: PostHog, privacyMode: boolean, input: any): any => {\n return (client as any).privacy_mode || privacyMode ? null : input\n}\n\nexport const truncate = (str: string): string => {\n try {\n const buffer = Buffer.from(str, STRING_FORMAT)\n if (buffer.length <= MAX_OUTPUT_SIZE) {\n return str\n }\n const truncatedBuffer = buffer.slice(0, MAX_OUTPUT_SIZE)\n return `${truncatedBuffer.toString(STRING_FORMAT)}... [truncated]`\n } catch (error) {\n console.error('Error truncating, likely not a string')\n return str\n }\n}\n\nexport type SendEventToPosthogParams = {\n client: PostHog\n distinctId?: string\n traceId: string\n model: string\n provider: string\n input: any\n output: any\n latency: number\n baseURL: string\n httpStatus: number\n usage?: {\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: any\n cacheReadInputTokens?: any\n cacheCreationInputTokens?: any\n }\n params: (ChatCompletionCreateParamsBase | MessageCreateParams | ResponseCreateParams) & MonitoringParams\n isError?: boolean\n error?: string\n tools?: any\n captureImmediate?: boolean\n}\n\nfunction sanitizeValues(obj: any): any {\n if (obj === undefined || obj === null) {\n return obj\n }\n const jsonSafe = JSON.parse(JSON.stringify(obj))\n if (typeof jsonSafe === 'string') {\n return Buffer.from(jsonSafe, STRING_FORMAT).toString(STRING_FORMAT)\n } else if (Array.isArray(jsonSafe)) {\n return jsonSafe.map(sanitizeValues)\n } else if (jsonSafe && typeof jsonSafe === 'object') {\n return Object.fromEntries(Object.entries(jsonSafe).map(([k, v]) => [k, sanitizeValues(v)]))\n }\n return jsonSafe\n}\n\nexport const sendEventToPosthog = async ({\n client,\n distinctId,\n traceId,\n model,\n provider,\n input,\n output,\n latency,\n baseURL,\n params,\n httpStatus = 200,\n usage = {},\n isError = false,\n error,\n tools,\n captureImmediate = false,\n}: SendEventToPosthogParams): Promise<void> => {\n if (!client.capture) {\n return Promise.resolve()\n }\n // sanitize input and output for UTF-8 validity\n const safeInput = sanitizeValues(input)\n const safeOutput = sanitizeValues(output)\n const safeError = sanitizeValues(error)\n\n let errorData = {}\n if (isError) {\n errorData = {\n $ai_is_error: true,\n $ai_error: safeError,\n }\n }\n let costOverrideData = {}\n if (params.posthogCostOverride) {\n const inputCostUSD = (params.posthogCostOverride.inputCost ?? 0) * (usage.inputTokens ?? 0)\n const outputCostUSD = (params.posthogCostOverride.outputCost ?? 0) * (usage.outputTokens ?? 0)\n costOverrideData = {\n $ai_input_cost_usd: inputCostUSD,\n $ai_output_cost_usd: outputCostUSD,\n $ai_total_cost_usd: inputCostUSD + outputCostUSD,\n }\n }\n\n const additionalTokenValues = {\n ...(usage.reasoningTokens ? { $ai_reasoning_tokens: usage.reasoningTokens } : {}),\n ...(usage.cacheReadInputTokens ? { $ai_cache_read_input_tokens: usage.cacheReadInputTokens } : {}),\n ...(usage.cacheCreationInputTokens ? { $ai_cache_creation_input_tokens: usage.cacheCreationInputTokens } : {}),\n }\n\n const properties = {\n $ai_provider: params.posthogProviderOverride ?? provider,\n $ai_model: params.posthogModelOverride ?? model,\n $ai_model_parameters: getModelParams(params),\n $ai_input: withPrivacyMode(client, params.posthogPrivacyMode ?? false, safeInput),\n $ai_output_choices: withPrivacyMode(client, params.posthogPrivacyMode ?? false, safeOutput),\n $ai_http_status: httpStatus,\n $ai_input_tokens: usage.inputTokens ?? 0,\n $ai_output_tokens: usage.outputTokens ?? 0,\n ...additionalTokenValues,\n $ai_latency: latency,\n $ai_trace_id: traceId,\n $ai_base_url: baseURL,\n ...params.posthogProperties,\n ...(distinctId ? {} : { $process_person_profile: false }),\n ...(tools ? { $ai_tools: tools } : {}),\n ...errorData,\n ...costOverrideData,\n }\n\n const event = {\n distinctId: distinctId ?? traceId,\n event: '$ai_generation',\n properties,\n groups: params.posthogGroups,\n }\n\n if (captureImmediate) {\n // await capture promise to send single event in serverless environments\n await client.captureImmediate(event)\n } else {\n client.capture(event)\n }\n}\n","import AnthropicOriginal from '@anthropic-ai/sdk'\nimport { PostHog } from 'posthog-node'\nimport { v4 as uuidv4 } from 'uuid'\nimport { formatResponseAnthropic, mergeSystemPrompt, MonitoringParams, sendEventToPosthog } from '../utils'\n\ntype MessageCreateParamsNonStreaming = AnthropicOriginal.Messages.MessageCreateParamsNonStreaming\ntype MessageCreateParamsStreaming = AnthropicOriginal.Messages.MessageCreateParamsStreaming\ntype MessageCreateParams = AnthropicOriginal.Messages.MessageCreateParams\ntype Message = AnthropicOriginal.Messages.Message\ntype RawMessageStreamEvent = AnthropicOriginal.Messages.RawMessageStreamEvent\ntype MessageCreateParamsBase = AnthropicOriginal.Messages.MessageCreateParams\n\nimport type { APIPromise, RequestOptions } from '@anthropic-ai/sdk/core'\nimport type { Stream } from '@anthropic-ai/sdk/streaming'\n\ninterface MonitoringAnthropicConfig {\n apiKey: string\n posthog: PostHog\n baseURL?: string\n}\n\nexport class PostHogAnthropic extends AnthropicOriginal {\n private readonly phClient: PostHog\n public messages: WrappedMessages\n\n constructor(config: MonitoringAnthropicConfig) {\n const { posthog, ...anthropicConfig } = config\n super(anthropicConfig)\n this.phClient = posthog\n this.messages = new WrappedMessages(this, this.phClient)\n }\n}\n\nexport class WrappedMessages extends AnthropicOriginal.Messages {\n private readonly phClient: PostHog\n\n constructor(parentClient: PostHogAnthropic, phClient: PostHog) {\n super(parentClient)\n this.phClient = phClient\n }\n\n public create(body: MessageCreateParamsNonStreaming, options?: RequestOptions): APIPromise<Message>\n public create(\n body: MessageCreateParamsStreaming & MonitoringParams,\n options?: RequestOptions\n ): APIPromise<Stream<RawMessageStreamEvent>>\n public create(\n body: MessageCreateParamsBase & MonitoringParams,\n options?: RequestOptions\n ): APIPromise<Stream<RawMessageStreamEvent> | Message>\n public create(\n body: MessageCreateParams & MonitoringParams,\n options?: RequestOptions\n ): APIPromise<Message> | APIPromise<Stream<RawMessageStreamEvent>> {\n const {\n posthogDistinctId,\n posthogTraceId,\n posthogProperties,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n posthogPrivacyMode = false,\n posthogGroups,\n posthogCaptureImmediate,\n ...anthropicParams\n } = body\n\n const traceId = posthogTraceId ?? uuidv4()\n const startTime = Date.now()\n\n const parentPromise = super.create(anthropicParams, options)\n\n if (anthropicParams.stream) {\n return parentPromise.then((value) => {\n let accumulatedContent = ''\n const usage: {\n inputTokens: number\n outputTokens: number\n cacheCreationInputTokens?: number\n cacheReadInputTokens?: number\n } = {\n inputTokens: 0,\n outputTokens: 0,\n cacheCreationInputTokens: 0,\n cacheReadInputTokens: 0,\n }\n if ('tee' in value) {\n const [stream1, stream2] = value.tee()\n ;(async () => {\n try {\n for await (const chunk of stream1) {\n if ('delta' in chunk) {\n if ('text' in chunk.delta) {\n const delta = chunk?.delta?.text ?? ''\n accumulatedContent += delta\n }\n }\n if (chunk.type == 'message_start') {\n usage.inputTokens = chunk.message.usage.input_tokens ?? 0\n usage.cacheCreationInputTokens = chunk.message.usage.cache_creation_input_tokens ?? 0\n usage.cacheReadInputTokens = chunk.message.usage.cache_read_input_tokens ?? 0\n }\n if ('usage' in chunk) {\n usage.outputTokens = chunk.usage.output_tokens ?? 0\n }\n }\n const latency = (Date.now() - startTime) / 1000\n await sendEventToPosthog({\n client: this.phClient,\n distinctId: posthogDistinctId,\n traceId,\n model: anthropicParams.model,\n provider: 'anthropic',\n input: mergeSystemPrompt(anthropicParams, 'anthropic'),\n output: [{ content: accumulatedContent, role: 'assistant' }],\n latency,\n baseURL: (this as any).baseURL ?? '',\n params: body,\n httpStatus: 200,\n usage,\n captureImmediate: posthogCaptureImmediate,\n })\n } catch (error: any) {\n // error handling\n await sendEventToPosthog({\n client: this.phClient,\n distinctId: posthogDistinctId,\n traceId,\n model: anthropicParams.model,\n provider: 'anthropic',\n input: mergeSystemPrompt(anthropicParams, 'anthropic'),\n output: [],\n latency: 0,\n baseURL: (this as any).baseURL ?? '',\n params: body,\n httpStatus: error?.status ? error.status : 500,\n usage: {\n inputTokens: 0,\n outputTokens: 0,\n },\n isError: true,\n error: JSON.stringify(error),\n captureImmediate: posthogCaptureImmediate,\n })\n }\n })()\n\n // Return the other stream to the user\n return stream2\n }\n return value\n }) as APIPromise<Stream<RawMessageStreamEvent>>\n } else {\n const wrappedPromise = parentPromise.then(\n async (result) => {\n if ('content' in result) {\n const latency = (Date.now() - startTime) / 1000\n await sendEventToPosthog({\n client: this.phClient,\n distinctId: posthogDistinctId,\n traceId,\n model: anthropicParams.model,\n provider: 'anthropic',\n input: mergeSystemPrompt(anthropicParams, 'anthropic'),\n output: formatResponseAnthropic(result),\n latency,\n baseURL: (this as any).baseURL ?? '',\n params: body,\n httpStatus: 200,\n usage: {\n inputTokens: result.usage.input_tokens ?? 0,\n outputTokens: result.usage.output_tokens ?? 0,\n cacheCreationInputTokens: result.usage.cache_creation_input_tokens ?? 0,\n cacheReadInputTokens: result.usage.cache_read_input_tokens ?? 0,\n },\n captureImmediate: posthogCaptureImmediate,\n })\n }\n return result\n },\n async (error: any) => {\n await sendEventToPosthog({\n client: this.phClient,\n distinctId: posthogDistinctId,\n traceId,\n model: anthropicParams.model,\n provider: 'anthropic',\n input: mergeSystemPrompt(anthropicParams, 'anthropic'),\n output: [],\n latency: 0,\n baseURL: (this as any).baseURL ?? '',\n params: body,\n httpStatus: error?.status ? error.status : 500,\n usage: {\n inputTokens: 0,\n outputTokens: 0,\n },\n isError: true,\n error: JSON.stringify(error),\n captureImmediate: posthogCaptureImmediate,\n })\n throw error\n }\n ) as APIPromise<Message>\n\n return wrappedPromise\n }\n }\n}\n\nexport default PostHogAnthropic\n\nexport { PostHogAnthropic as Anthropic }\n"],"names":["STRING_FORMAT","getModelParams","params","modelParams","paramKeys","key","undefined","formatResponseAnthropic","response","output","choice","content","text","push","role","mergeSystemPrompt","provider","messages","system","systemMessage","withPrivacyMode","client","privacyMode","input","privacy_mode","sanitizeValues","obj","jsonSafe","JSON","parse","stringify","Buffer","from","toString","Array","isArray","map","Object","fromEntries","entries","k","v","sendEventToPosthog","distinctId","traceId","model","latency","baseURL","httpStatus","usage","isError","error","tools","captureImmediate","capture","Promise","resolve","safeInput","safeOutput","safeError","errorData","$ai_is_error","$ai_error","costOverrideData","posthogCostOverride","inputCostUSD","inputCost","inputTokens","outputCostUSD","outputCost","outputTokens","$ai_input_cost_usd","$ai_output_cost_usd","$ai_total_cost_usd","additionalTokenValues","reasoningTokens","$ai_reasoning_tokens","cacheReadInputTokens","$ai_cache_read_input_tokens","cacheCreationInputTokens","$ai_cache_creation_input_tokens","properties","$ai_provider","posthogProviderOverride","$ai_model","posthogModelOverride","$ai_model_parameters","$ai_input","posthogPrivacyMode","$ai_output_choices","$ai_http_status","$ai_input_tokens","$ai_output_tokens","$ai_latency","$ai_trace_id","$ai_base_url","posthogProperties","$process_person_profile","$ai_tools","event","groups","posthogGroups","PostHogAnthropic","AnthropicOriginal","constructor","config","posthog","anthropicConfig","phClient","WrappedMessages","Messages","parentClient","create","body","options","posthogDistinctId","posthogTraceId","posthogCaptureImmediate","anthropicParams","uuidv4","startTime","Date","now","parentPromise","stream","then","value","accumulatedContent","stream1","stream2","tee","chunk","delta","type","message","input_tokens","cache_creation_input_tokens","cache_read_input_tokens","output_tokens","status","wrappedPromise","result"],"mappings":";;;;;;;;AAWA,MAAMA,aAAa,GAAG,MAAM;AAmBrB,MAAMC,cAAc,GACzBC,MAAiH,IACzF;EACxB,IAAI,CAACA,MAAM,EAAE;AACX,IAAA,OAAO,EAAE;AACX,EAAA;EACA,MAAMC,WAAgC,GAAG,EAAE;EAC3C,MAAMC,SAAS,GAAG,CAChB,aAAa,EACb,YAAY,EACZ,uBAAuB,EACvB,OAAO,EACP,mBAAmB,EACnB,kBAAkB,EAClB,GAAG,EACH,MAAM,EACN,QAAQ,EACR,WAAW,CACH;AAEV,EAAA,KAAK,MAAMC,GAAG,IAAID,SAAS,EAAE;IAC3B,IAAIC,GAAG,IAAIH,MAAM,IAAKA,MAAM,CAASG,GAAG,CAAC,KAAKC,SAAS,EAAE;AACvDH,MAAAA,WAAW,CAACE,GAAG,CAAC,GAAIH,MAAM,CAASG,GAAG,CAAC;AACzC,IAAA;AACF,EAAA;AACA,EAAA,OAAOF,WAAW;AACpB,CAAC;AAmBM,MAAMI,uBAAuB,GAAIC,QAAa,IAA+C;AAClG;EACA,MAAMC,MAAgD,GAAG,EAAE;EAC3D,KAAK,MAAMC,MAAM,IAAIF,QAAQ,CAACG,OAAO,IAAI,EAAE,EAAE;IAC3C,IAAID,MAAM,EAAEE,IAAI,EAAE;MAChBH,MAAM,CAACI,IAAI,CAAC;AACVC,QAAAA,IAAI,EAAE,WAAW;QACjBH,OAAO,EAAED,MAAM,CAACE;AAClB,OAAC,CAAC;AACJ,IAAA;AACF,EAAA;AACA,EAAA,OAAOH,MAAM;AACf,CAAC;AA8CM,MAAMM,iBAAiB,GAAGA,CAACb,MAA8C,EAAEc,QAAgB,KAAU;EAC7E;AAC3B,IAAA,MAAMC,QAAQ,GAAGf,MAAM,CAACe,QAAQ,IAAI,EAAE;AACtC,IAAA,IAAI,CAAEf,MAAM,CAASgB,M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;AAC5BE,UAAAA,gBAAgB,EAAEgE;AACpB,SAAC,CAAC;AACF,QAAA,MAAMlE,KAAK;AACb,MAAA,CACF,CAAwB;AAExB,MAAA,OAAOyF,cAAc;AACvB,IAAA;AACF,EAAA;AACF;;;;;;;"}
@@ -30,7 +30,7 @@ const formatResponseAnthropic = response => {
30
30
  return output;
31
31
  };
32
32
  const mergeSystemPrompt = (params, provider) => {
33
- if (provider == 'anthropic') {
33
+ {
34
34
  const messages = params.messages || [];
35
35
  if (!params.system) {
36
36
  return messages;
@@ -41,7 +41,6 @@ const mergeSystemPrompt = (params, provider) => {
41
41
  content: systemMessage
42
42
  }, ...messages];
43
43
  }
44
- return params.messages;
45
44
  };
46
45
  const withPrivacyMode = (client, privacyMode, input) => {
47
46
  return client.privacy_mode || privacyMode ? null : input;
@@ -236,7 +235,7 @@ class WrappedMessages extends AnthropicOriginal.Messages {
236
235
  traceId,
237
236
  model: anthropicParams.model,
238
237
  provider: 'anthropic',
239
- input: mergeSystemPrompt(anthropicParams, 'anthropic'),
238
+ input: mergeSystemPrompt(anthropicParams),
240
239
  output: [],
241
240
  latency: 0,
242
241
  baseURL: this.baseURL ?? '',
@@ -268,7 +267,7 @@ class WrappedMessages extends AnthropicOriginal.Messages {
268
267
  traceId,
269
268
  model: anthropicParams.model,
270
269
  provider: 'anthropic',
271
- input: mergeSystemPrompt(anthropicParams, 'anthropic'),
270
+ input: mergeSystemPrompt(anthropicParams),
272
271
  output: formatResponseAnthropic(result),
273
272
  latency,
274
273
  baseURL: this.baseURL ?? '',
@@ -291,7 +290,7 @@ class WrappedMessages extends AnthropicOriginal.Messages {
291
290
  traceId,
292
291
  model: anthropicParams.model,
293
292
  provider: 'anthropic',
294
- input: mergeSystemPrompt(anthropicParams, 'anthropic'),
293
+ input: mergeSystemPrompt(anthropicParams),
295
294
  output: [],
296
295
  latency: 0,
297
296
  baseURL: this.baseURL ?? '',