@posthog/ai 5.2.2 → 6.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.
Files changed (60) hide show
  1. package/LICENSE +245 -0
  2. package/{lib → dist}/anthropic/index.cjs +44 -17
  3. package/dist/anthropic/index.cjs.map +1 -0
  4. package/{lib → dist}/anthropic/index.mjs +41 -10
  5. package/dist/anthropic/index.mjs.map +1 -0
  6. package/{lib → dist}/gemini/index.cjs +68 -26
  7. package/dist/gemini/index.cjs.map +1 -0
  8. package/{lib → dist}/gemini/index.d.ts +0 -1
  9. package/{lib → dist}/gemini/index.mjs +67 -25
  10. package/dist/gemini/index.mjs.map +1 -0
  11. package/{lib → dist}/index.cjs +875 -601
  12. package/dist/index.cjs.map +1 -0
  13. package/{lib → dist}/index.d.ts +3 -3
  14. package/{lib → dist}/index.mjs +859 -579
  15. package/dist/index.mjs.map +1 -0
  16. package/{lib → dist}/langchain/index.cjs +178 -118
  17. package/dist/langchain/index.cjs.map +1 -0
  18. package/{lib → dist}/langchain/index.d.ts +1 -0
  19. package/{lib → dist}/langchain/index.mjs +175 -112
  20. package/dist/langchain/index.mjs.map +1 -0
  21. package/{lib → dist}/openai/index.cjs +113 -6
  22. package/dist/openai/index.cjs.map +1 -0
  23. package/{lib → dist}/openai/index.mjs +112 -5
  24. package/dist/openai/index.mjs.map +1 -0
  25. package/{lib → dist}/vercel/index.cjs +117 -82
  26. package/dist/vercel/index.cjs.map +1 -0
  27. package/{lib → dist}/vercel/index.d.ts +2 -2
  28. package/{lib → dist}/vercel/index.mjs +118 -81
  29. package/dist/vercel/index.mjs.map +1 -0
  30. package/package.json +45 -35
  31. package/CHANGELOG.md +0 -89
  32. package/index.ts +0 -1
  33. package/lib/anthropic/index.cjs.map +0 -1
  34. package/lib/anthropic/index.mjs.map +0 -1
  35. package/lib/gemini/index.cjs.map +0 -1
  36. package/lib/gemini/index.mjs.map +0 -1
  37. package/lib/index.cjs.map +0 -1
  38. package/lib/index.mjs.map +0 -1
  39. package/lib/langchain/index.cjs.map +0 -1
  40. package/lib/langchain/index.mjs.map +0 -1
  41. package/lib/openai/index.cjs.map +0 -1
  42. package/lib/openai/index.mjs.map +0 -1
  43. package/lib/vercel/index.cjs.map +0 -1
  44. package/lib/vercel/index.mjs.map +0 -1
  45. package/src/anthropic/index.ts +0 -211
  46. package/src/gemini/index.ts +0 -254
  47. package/src/index.ts +0 -13
  48. package/src/langchain/callbacks.ts +0 -640
  49. package/src/langchain/index.ts +0 -1
  50. package/src/openai/azure.ts +0 -481
  51. package/src/openai/index.ts +0 -498
  52. package/src/utils.ts +0 -287
  53. package/src/vercel/index.ts +0 -1
  54. package/src/vercel/middleware.ts +0 -393
  55. package/tests/callbacks.test.ts +0 -48
  56. package/tests/gemini.test.ts +0 -344
  57. package/tests/openai.test.ts +0 -403
  58. package/tsconfig.json +0 -10
  59. /package/{lib → dist}/anthropic/index.d.ts +0 -0
  60. /package/{lib → dist}/openai/index.d.ts +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) {
@@ -25,20 +21,35 @@ const getModelParams = params => {
25
21
  return modelParams;
26
22
  };
27
23
  const formatResponseAnthropic = response => {
28
- // Example approach if "response.content" holds array of text segments, etc.
29
24
  const output = [];
25
+ const content = [];
30
26
  for (const choice of response.content ?? []) {
31
- if (choice?.text) {
32
- output.push({
33
- role: 'assistant',
34
- content: choice.text
27
+ if (choice?.type === 'text' && choice?.text) {
28
+ content.push({
29
+ type: 'text',
30
+ text: choice.text
31
+ });
32
+ } else if (choice?.type === 'tool_use' && choice?.name && choice?.id) {
33
+ content.push({
34
+ type: 'function',
35
+ id: choice.id,
36
+ function: {
37
+ name: choice.name,
38
+ arguments: choice.input || {}
39
+ }
35
40
  });
36
41
  }
37
42
  }
43
+ if (content.length > 0) {
44
+ output.push({
45
+ role: 'assistant',
46
+ content
47
+ });
48
+ }
38
49
  return output;
39
50
  };
40
51
  const mergeSystemPrompt = (params, provider) => {
41
- if (provider == 'anthropic') {
52
+ {
42
53
  const messages = params.messages || [];
43
54
  if (!params.system) {
44
55
  return messages;
@@ -49,11 +60,23 @@ const mergeSystemPrompt = (params, provider) => {
49
60
  content: systemMessage
50
61
  }, ...messages];
51
62
  }
52
- return params.messages;
53
63
  };
54
64
  const withPrivacyMode = (client, privacyMode, input) => {
55
65
  return client.privacy_mode || privacyMode ? null : input;
56
66
  };
67
+
68
+ /**
69
+ * Extract available tool calls from the request parameters.
70
+ * These are the tools provided to the LLM, not the tool calls in the response.
71
+ */
72
+ const extractAvailableToolCalls = (provider, params) => {
73
+ {
74
+ if (params.tools) {
75
+ return params.tools;
76
+ }
77
+ return null;
78
+ }
79
+ };
57
80
  function sanitizeValues(obj) {
58
81
  if (obj === undefined || obj === null) {
59
82
  return obj;
@@ -158,7 +181,7 @@ const sendEventToPosthog = async ({
158
181
  }
159
182
  };
160
183
 
161
- class PostHogAnthropic extends AnthropicOriginal__default["default"] {
184
+ class PostHogAnthropic extends AnthropicOriginal {
162
185
  constructor(config) {
163
186
  const {
164
187
  posthog,
@@ -169,7 +192,7 @@ class PostHogAnthropic extends AnthropicOriginal__default["default"] {
169
192
  this.messages = new WrappedMessages(this, this.phClient);
170
193
  }
171
194
  }
172
- class WrappedMessages extends AnthropicOriginal__default["default"].Messages {
195
+ class WrappedMessages extends AnthropicOriginal.Messages {
173
196
  constructor(parentClient, phClient) {
174
197
  super(parentClient);
175
198
  this.phClient = phClient;
@@ -218,6 +241,7 @@ class WrappedMessages extends AnthropicOriginal__default["default"].Messages {
218
241
  }
219
242
  }
220
243
  const latency = (Date.now() - startTime) / 1000;
244
+ const availableTools = extractAvailableToolCalls('anthropic', anthropicParams);
221
245
  await sendEventToPosthog({
222
246
  client: this.phClient,
223
247
  distinctId: posthogDistinctId,
@@ -234,6 +258,7 @@ class WrappedMessages extends AnthropicOriginal__default["default"].Messages {
234
258
  params: body,
235
259
  httpStatus: 200,
236
260
  usage,
261
+ tools: availableTools,
237
262
  captureImmediate: posthogCaptureImmediate
238
263
  });
239
264
  } catch (error) {
@@ -244,7 +269,7 @@ class WrappedMessages extends AnthropicOriginal__default["default"].Messages {
244
269
  traceId,
245
270
  model: anthropicParams.model,
246
271
  provider: 'anthropic',
247
- input: mergeSystemPrompt(anthropicParams, 'anthropic'),
272
+ input: mergeSystemPrompt(anthropicParams),
248
273
  output: [],
249
274
  latency: 0,
250
275
  baseURL: this.baseURL ?? '',
@@ -270,13 +295,14 @@ class WrappedMessages extends AnthropicOriginal__default["default"].Messages {
270
295
  const wrappedPromise = parentPromise.then(async result => {
271
296
  if ('content' in result) {
272
297
  const latency = (Date.now() - startTime) / 1000;
298
+ const availableTools = extractAvailableToolCalls('anthropic', anthropicParams);
273
299
  await sendEventToPosthog({
274
300
  client: this.phClient,
275
301
  distinctId: posthogDistinctId,
276
302
  traceId,
277
303
  model: anthropicParams.model,
278
304
  provider: 'anthropic',
279
- input: mergeSystemPrompt(anthropicParams, 'anthropic'),
305
+ input: mergeSystemPrompt(anthropicParams),
280
306
  output: formatResponseAnthropic(result),
281
307
  latency,
282
308
  baseURL: this.baseURL ?? '',
@@ -288,6 +314,7 @@ class WrappedMessages extends AnthropicOriginal__default["default"].Messages {
288
314
  cacheCreationInputTokens: result.usage.cache_creation_input_tokens ?? 0,
289
315
  cacheReadInputTokens: result.usage.cache_read_input_tokens ?? 0
290
316
  },
317
+ tools: availableTools,
291
318
  captureImmediate: posthogCaptureImmediate
292
319
  });
293
320
  }
@@ -299,7 +326,7 @@ class WrappedMessages extends AnthropicOriginal__default["default"].Messages {
299
326
  traceId,
300
327
  model: anthropicParams.model,
301
328
  provider: 'anthropic',
302
- input: mergeSystemPrompt(anthropicParams, 'anthropic'),
329
+ input: mergeSystemPrompt(anthropicParams),
303
330
  output: [],
304
331
  latency: 0,
305
332
  baseURL: this.baseURL ?? '',
@@ -323,5 +350,5 @@ class WrappedMessages extends AnthropicOriginal__default["default"].Messages {
323
350
  exports.Anthropic = PostHogAnthropic;
324
351
  exports.PostHogAnthropic = PostHogAnthropic;
325
352
  exports.WrappedMessages = WrappedMessages;
326
- exports["default"] = PostHogAnthropic;
353
+ exports.default = PostHogAnthropic;
327
354
  //# sourceMappingURL=index.cjs.map
@@ -0,0 +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'\nimport type { ChatCompletionTool } from 'openai/resources/chat/completions'\nimport type { Tool as GeminiTool } from '@google/genai'\nimport type { FormattedMessage, FormattedContent, TokenUsage } from './types'\n\ntype ChatCompletionCreateParamsBase = OpenAIOrignal.Chat.Completions.ChatCompletionCreateParams\ntype MessageCreateParams = AnthropicOriginal.Messages.MessageCreateParams\ntype ResponseCreateParams = OpenAIOrignal.Responses.ResponseCreateParams\ntype AnthropicTool = AnthropicOriginal.Tool\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): FormattedMessage[] => {\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): FormattedMessage[] => {\n const output: FormattedMessage[] = []\n const content: FormattedContent = []\n\n for (const choice of response.content ?? []) {\n if (choice?.type === 'text' && choice?.text) {\n content.push({ type: 'text', text: choice.text })\n } else if (choice?.type === 'tool_use' && choice?.name && choice?.id) {\n content.push({\n type: 'function',\n id: choice.id,\n function: {\n name: choice.name,\n arguments: choice.input || {},\n },\n })\n }\n }\n\n if (content.length > 0) {\n output.push({\n role: 'assistant',\n content,\n })\n }\n\n return output\n}\n\nexport const formatResponseOpenAI = (response: any): FormattedMessage[] => {\n const output: FormattedMessage[] = []\n\n if (response.choices) {\n for (const choice of response.choices) {\n const content: FormattedContent = []\n let role = 'assistant'\n\n if (choice.message) {\n if (choice.message.role) {\n role = choice.message.role\n }\n\n if (choice.message.content) {\n content.push({ type: 'text', text: choice.message.content })\n }\n\n if (choice.message.tool_calls) {\n for (const toolCall of choice.message.tool_calls) {\n content.push({\n type: 'function',\n id: toolCall.id,\n function: {\n name: toolCall.function.name,\n arguments: toolCall.function.arguments,\n },\n })\n }\n }\n }\n\n if (content.length > 0) {\n output.push({\n role,\n content,\n })\n }\n }\n }\n\n // Handle Responses API format\n if (response.output) {\n const content: FormattedContent = []\n let role = 'assistant'\n\n for (const item of response.output) {\n if (item.type === 'message') {\n role = item.role\n\n if (item.content && Array.isArray(item.content)) {\n for (const contentItem of item.content) {\n if (contentItem.type === 'output_text' && contentItem.text) {\n content.push({ type: 'text', text: contentItem.text })\n } else if (contentItem.text) {\n content.push({ type: 'text', text: contentItem.text })\n } else if (contentItem.type === 'input_image' && contentItem.image_url) {\n content.push({\n type: 'image',\n image: contentItem.image_url,\n })\n }\n }\n } else if (item.content) {\n content.push({ type: 'text', text: String(item.content) })\n }\n } else if (item.type === 'function_call') {\n content.push({\n type: 'function',\n id: item.call_id || item.id || '',\n function: {\n name: item.name,\n arguments: item.arguments || {},\n },\n })\n }\n }\n\n if (content.length > 0) {\n output.push({\n role,\n content,\n })\n }\n }\n\n return output\n}\n\nexport const formatResponseGemini = (response: any): FormattedMessage[] => {\n const output: FormattedMessage[] = []\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 content: FormattedContent = []\n\n for (const part of candidate.content.parts) {\n if (part.text) {\n content.push({ type: 'text', text: part.text })\n } else if (part.functionCall) {\n content.push({\n type: 'function',\n function: {\n name: part.functionCall.name,\n arguments: part.functionCall.args,\n },\n })\n }\n }\n\n if (content.length > 0) {\n output.push({\n role: 'assistant',\n content,\n })\n }\n } else if (candidate.text) {\n output.push({\n role: 'assistant',\n content: [{ type: 'text', text: candidate.text }],\n })\n }\n }\n } else if (response.text) {\n output.push({\n role: 'assistant',\n content: [{ type: 'text', text: response.text }],\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\n/**\n * Extract available tool calls from the request parameters.\n * These are the tools provided to the LLM, not the tool calls in the response.\n */\nexport const extractAvailableToolCalls = (\n provider: string,\n params: any\n): ChatCompletionTool[] | AnthropicTool[] | GeminiTool[] | null => {\n if (provider === 'anthropic') {\n if (params.tools) {\n return params.tools\n }\n\n return null\n } else if (provider === 'gemini') {\n if (params.config && params.config.tools) {\n return params.config.tools\n }\n\n return null\n } else if (provider === 'openai') {\n if (params.tools) {\n return params.tools\n }\n\n return null\n } else if (provider === 'vercel') {\n // Vercel AI SDK stores tools in params.mode.tools when mode type is 'regular'\n if (params.mode?.type === 'regular' && params.mode.tools) {\n return params.mode.tools\n }\n\n return null\n }\n\n return null\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?: TokenUsage\n params: (ChatCompletionCreateParamsBase | MessageCreateParams | ResponseCreateParams) & MonitoringParams\n isError?: boolean\n error?: string\n tools?: ChatCompletionTool[] | AnthropicTool[] | GeminiTool[] | null\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 {\n formatResponseAnthropic,\n mergeSystemPrompt,\n MonitoringParams,\n sendEventToPosthog,\n extractAvailableToolCalls,\n} 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\n const latency = (Date.now() - startTime) / 1000\n\n const availableTools = extractAvailableToolCalls('anthropic', anthropicParams)\n\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 tools: availableTools,\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\n const availableTools = extractAvailableToolCalls('anthropic', anthropicParams)\n\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 tools: availableTools,\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","content","choice","type","text","push","name","id","function","arguments","input","length","role","mergeSystemPrompt","provider","messages","system","systemMessage","withPrivacyMode","client","privacyMode","privacy_mode","extractAvailableToolCalls","tools","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","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","message","input_tokens","cache_creation_input_tokens","cache_read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;
18
18
  };
19
19
  const formatResponseAnthropic = response => {
20
- // Example approach if "response.content" holds array of text segments, etc.
21
20
  const output = [];
21
+ const content = [];
22
22
  for (const choice of response.content ?? []) {
23
- if (choice?.text) {
24
- output.push({
25
- role: 'assistant',
26
- content: choice.text
23
+ if (choice?.type === 'text' && choice?.text) {
24
+ content.push({
25
+ type: 'text',
26
+ text: choice.text
27
+ });
28
+ } else if (choice?.type === 'tool_use' && choice?.name && choice?.id) {
29
+ content.push({
30
+ type: 'function',
31
+ id: choice.id,
32
+ function: {
33
+ name: choice.name,
34
+ arguments: choice.input || {}
35
+ }
27
36
  });
28
37
  }
29
38
  }
39
+ if (content.length > 0) {
40
+ output.push({
41
+ role: 'assistant',
42
+ content
43
+ });
44
+ }
30
45
  return output;
31
46
  };
32
47
  const mergeSystemPrompt = (params, provider) => {
33
- if (provider == 'anthropic') {
48
+ {
34
49
  const messages = params.messages || [];
35
50
  if (!params.system) {
36
51
  return messages;
@@ -41,11 +56,23 @@ const mergeSystemPrompt = (params, provider) => {
41
56
  content: systemMessage
42
57
  }, ...messages];
43
58
  }
44
- return params.messages;
45
59
  };
46
60
  const withPrivacyMode = (client, privacyMode, input) => {
47
61
  return client.privacy_mode || privacyMode ? null : input;
48
62
  };
63
+
64
+ /**
65
+ * Extract available tool calls from the request parameters.
66
+ * These are the tools provided to the LLM, not the tool calls in the response.
67
+ */
68
+ const extractAvailableToolCalls = (provider, params) => {
69
+ {
70
+ if (params.tools) {
71
+ return params.tools;
72
+ }
73
+ return null;
74
+ }
75
+ };
49
76
  function sanitizeValues(obj) {
50
77
  if (obj === undefined || obj === null) {
51
78
  return obj;
@@ -210,6 +237,7 @@ class WrappedMessages extends AnthropicOriginal.Messages {
210
237
  }
211
238
  }
212
239
  const latency = (Date.now() - startTime) / 1000;
240
+ const availableTools = extractAvailableToolCalls('anthropic', anthropicParams);
213
241
  await sendEventToPosthog({
214
242
  client: this.phClient,
215
243
  distinctId: posthogDistinctId,
@@ -226,6 +254,7 @@ class WrappedMessages extends AnthropicOriginal.Messages {
226
254
  params: body,
227
255
  httpStatus: 200,
228
256
  usage,
257
+ tools: availableTools,
229
258
  captureImmediate: posthogCaptureImmediate
230
259
  });
231
260
  } catch (error) {
@@ -236,7 +265,7 @@ class WrappedMessages extends AnthropicOriginal.Messages {
236
265
  traceId,
237
266
  model: anthropicParams.model,
238
267
  provider: 'anthropic',
239
- input: mergeSystemPrompt(anthropicParams, 'anthropic'),
268
+ input: mergeSystemPrompt(anthropicParams),
240
269
  output: [],
241
270
  latency: 0,
242
271
  baseURL: this.baseURL ?? '',
@@ -262,13 +291,14 @@ class WrappedMessages extends AnthropicOriginal.Messages {
262
291
  const wrappedPromise = parentPromise.then(async result => {
263
292
  if ('content' in result) {
264
293
  const latency = (Date.now() - startTime) / 1000;
294
+ const availableTools = extractAvailableToolCalls('anthropic', anthropicParams);
265
295
  await sendEventToPosthog({
266
296
  client: this.phClient,
267
297
  distinctId: posthogDistinctId,
268
298
  traceId,
269
299
  model: anthropicParams.model,
270
300
  provider: 'anthropic',
271
- input: mergeSystemPrompt(anthropicParams, 'anthropic'),
301
+ input: mergeSystemPrompt(anthropicParams),
272
302
  output: formatResponseAnthropic(result),
273
303
  latency,
274
304
  baseURL: this.baseURL ?? '',
@@ -280,6 +310,7 @@ class WrappedMessages extends AnthropicOriginal.Messages {
280
310
  cacheCreationInputTokens: result.usage.cache_creation_input_tokens ?? 0,
281
311
  cacheReadInputTokens: result.usage.cache_read_input_tokens ?? 0
282
312
  },
313
+ tools: availableTools,
283
314
  captureImmediate: posthogCaptureImmediate
284
315
  });
285
316
  }
@@ -291,7 +322,7 @@ class WrappedMessages extends AnthropicOriginal.Messages {
291
322
  traceId,
292
323
  model: anthropicParams.model,
293
324
  provider: 'anthropic',
294
- input: mergeSystemPrompt(anthropicParams, 'anthropic'),
325
+ input: mergeSystemPrompt(anthropicParams),
295
326
  output: [],
296
327
  latency: 0,
297
328
  baseURL: this.baseURL ?? '',