langwatch 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/.eslintrc.cjs +37 -0
  2. package/README.md +3 -0
  3. package/dist/chunk-GOA2HL4A.mjs +269 -0
  4. package/dist/chunk-GOA2HL4A.mjs.map +1 -0
  5. package/dist/index.d.mts +82 -0
  6. package/dist/index.d.ts +82 -0
  7. package/dist/index.js +940 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/index.mjs +666 -0
  10. package/dist/index.mjs.map +1 -0
  11. package/dist/utils-s3gGR6vj.d.mts +209 -0
  12. package/dist/utils-s3gGR6vj.d.ts +209 -0
  13. package/dist/utils.d.mts +3 -0
  14. package/dist/utils.d.ts +3 -0
  15. package/dist/utils.js +263 -0
  16. package/dist/utils.js.map +1 -0
  17. package/dist/utils.mjs +7 -0
  18. package/dist/utils.mjs.map +1 -0
  19. package/example/.env.example +12 -0
  20. package/example/.eslintrc.json +26 -0
  21. package/example/LICENSE +13 -0
  22. package/example/README.md +10 -0
  23. package/example/app/(chat)/chat/[id]/page.tsx +60 -0
  24. package/example/app/(chat)/layout.tsx +14 -0
  25. package/example/app/(chat)/page.tsx +22 -0
  26. package/example/app/actions.ts +156 -0
  27. package/example/app/globals.css +76 -0
  28. package/example/app/layout.tsx +64 -0
  29. package/example/app/login/actions.ts +71 -0
  30. package/example/app/login/page.tsx +18 -0
  31. package/example/app/new/page.tsx +5 -0
  32. package/example/app/opengraph-image.png +0 -0
  33. package/example/app/share/[id]/page.tsx +58 -0
  34. package/example/app/signup/actions.ts +111 -0
  35. package/example/app/signup/page.tsx +18 -0
  36. package/example/app/twitter-image.png +0 -0
  37. package/example/auth.config.ts +42 -0
  38. package/example/auth.ts +45 -0
  39. package/example/components/button-scroll-to-bottom.tsx +36 -0
  40. package/example/components/chat-history.tsx +49 -0
  41. package/example/components/chat-list.tsx +52 -0
  42. package/example/components/chat-message-actions.tsx +40 -0
  43. package/example/components/chat-message.tsx +80 -0
  44. package/example/components/chat-panel.tsx +139 -0
  45. package/example/components/chat-share-dialog.tsx +95 -0
  46. package/example/components/chat.tsx +84 -0
  47. package/example/components/clear-history.tsx +75 -0
  48. package/example/components/empty-screen.tsx +38 -0
  49. package/example/components/external-link.tsx +29 -0
  50. package/example/components/footer.tsx +19 -0
  51. package/example/components/header.tsx +80 -0
  52. package/example/components/login-button.tsx +42 -0
  53. package/example/components/login-form.tsx +97 -0
  54. package/example/components/markdown.tsx +9 -0
  55. package/example/components/prompt-form.tsx +115 -0
  56. package/example/components/providers.tsx +17 -0
  57. package/example/components/sidebar-actions.tsx +125 -0
  58. package/example/components/sidebar-desktop.tsx +19 -0
  59. package/example/components/sidebar-footer.tsx +16 -0
  60. package/example/components/sidebar-item.tsx +124 -0
  61. package/example/components/sidebar-items.tsx +42 -0
  62. package/example/components/sidebar-list.tsx +38 -0
  63. package/example/components/sidebar-mobile.tsx +31 -0
  64. package/example/components/sidebar-toggle.tsx +24 -0
  65. package/example/components/sidebar.tsx +21 -0
  66. package/example/components/signup-form.tsx +95 -0
  67. package/example/components/stocks/events-skeleton.tsx +31 -0
  68. package/example/components/stocks/events.tsx +30 -0
  69. package/example/components/stocks/index.tsx +36 -0
  70. package/example/components/stocks/message.tsx +134 -0
  71. package/example/components/stocks/spinner.tsx +16 -0
  72. package/example/components/stocks/stock-purchase.tsx +146 -0
  73. package/example/components/stocks/stock-skeleton.tsx +22 -0
  74. package/example/components/stocks/stock.tsx +210 -0
  75. package/example/components/stocks/stocks-skeleton.tsx +9 -0
  76. package/example/components/stocks/stocks.tsx +67 -0
  77. package/example/components/tailwind-indicator.tsx +14 -0
  78. package/example/components/theme-toggle.tsx +31 -0
  79. package/example/components/ui/alert-dialog.tsx +141 -0
  80. package/example/components/ui/badge.tsx +36 -0
  81. package/example/components/ui/button.tsx +57 -0
  82. package/example/components/ui/codeblock.tsx +148 -0
  83. package/example/components/ui/dialog.tsx +122 -0
  84. package/example/components/ui/dropdown-menu.tsx +205 -0
  85. package/example/components/ui/icons.tsx +507 -0
  86. package/example/components/ui/input.tsx +25 -0
  87. package/example/components/ui/label.tsx +26 -0
  88. package/example/components/ui/select.tsx +164 -0
  89. package/example/components/ui/separator.tsx +31 -0
  90. package/example/components/ui/sheet.tsx +140 -0
  91. package/example/components/ui/sonner.tsx +31 -0
  92. package/example/components/ui/switch.tsx +29 -0
  93. package/example/components/ui/textarea.tsx +24 -0
  94. package/example/components/ui/tooltip.tsx +30 -0
  95. package/example/components/user-menu.tsx +53 -0
  96. package/example/components.json +17 -0
  97. package/example/lib/chat/actions.tsx +606 -0
  98. package/example/lib/hooks/use-copy-to-clipboard.tsx +33 -0
  99. package/example/lib/hooks/use-enter-submit.tsx +23 -0
  100. package/example/lib/hooks/use-local-storage.ts +24 -0
  101. package/example/lib/hooks/use-scroll-anchor.tsx +86 -0
  102. package/example/lib/hooks/use-sidebar.tsx +60 -0
  103. package/example/lib/hooks/use-streamable-text.ts +25 -0
  104. package/example/lib/types.ts +41 -0
  105. package/example/lib/utils.ts +89 -0
  106. package/example/middleware.ts +8 -0
  107. package/example/next-env.d.ts +5 -0
  108. package/example/next.config.js +13 -0
  109. package/example/package-lock.json +9249 -0
  110. package/example/package.json +77 -0
  111. package/example/pnpm-lock.yaml +5712 -0
  112. package/example/postcss.config.js +6 -0
  113. package/example/prettier.config.cjs +34 -0
  114. package/example/public/apple-touch-icon.png +0 -0
  115. package/example/public/favicon-16x16.png +0 -0
  116. package/example/public/favicon.ico +0 -0
  117. package/example/public/next.svg +1 -0
  118. package/example/public/thirteen.svg +1 -0
  119. package/example/public/vercel.svg +1 -0
  120. package/example/tailwind.config.ts +81 -0
  121. package/example/tsconfig.json +35 -0
  122. package/package.json +45 -0
  123. package/src/helpers.ts +64 -0
  124. package/src/index.test.ts +255 -0
  125. package/src/index.ts +397 -0
  126. package/src/server/types/.gitkeep +0 -0
  127. package/src/types.ts +69 -0
  128. package/src/utils.ts +134 -0
  129. package/ts-to-zod.config.js +18 -0
  130. package/tsconfig.json +32 -0
  131. package/tsup.config.ts +10 -0
  132. package/vitest.config.ts +8 -0
package/dist/index.js ADDED
@@ -0,0 +1,940 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __commonJS = (cb, mod) => function __require() {
26
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
27
+ };
28
+ var __export = (target, all) => {
29
+ for (var name in all)
30
+ __defProp(target, name, { get: all[name], enumerable: true });
31
+ };
32
+ var __copyProps = (to, from, except, desc) => {
33
+ if (from && typeof from === "object" || typeof from === "function") {
34
+ for (let key of __getOwnPropNames(from))
35
+ if (!__hasOwnProp.call(to, key) && key !== except)
36
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
37
+ }
38
+ return to;
39
+ };
40
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
41
+ // If the importer is in node compatibility mode or this is not an ESM
42
+ // file that has been converted to a CommonJS file using a Babel-
43
+ // compatible transform (i.e. "__esModule" has not been set), then set
44
+ // "default" to the CommonJS "module.exports" for node compatibility.
45
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
46
+ mod
47
+ ));
48
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
49
+
50
+ // node_modules/secure-json-parse/index.js
51
+ var require_secure_json_parse = __commonJS({
52
+ "node_modules/secure-json-parse/index.js"(exports2, module2) {
53
+ "use strict";
54
+ var hasBuffer = typeof Buffer !== "undefined";
55
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
56
+ var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
57
+ function _parse(text, reviver, options) {
58
+ if (options == null) {
59
+ if (reviver !== null && typeof reviver === "object") {
60
+ options = reviver;
61
+ reviver = void 0;
62
+ }
63
+ }
64
+ if (hasBuffer && Buffer.isBuffer(text)) {
65
+ text = text.toString();
66
+ }
67
+ if (text && text.charCodeAt(0) === 65279) {
68
+ text = text.slice(1);
69
+ }
70
+ const obj = JSON.parse(text, reviver);
71
+ if (obj === null || typeof obj !== "object") {
72
+ return obj;
73
+ }
74
+ const protoAction = options && options.protoAction || "error";
75
+ const constructorAction = options && options.constructorAction || "error";
76
+ if (protoAction === "ignore" && constructorAction === "ignore") {
77
+ return obj;
78
+ }
79
+ if (protoAction !== "ignore" && constructorAction !== "ignore") {
80
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
81
+ return obj;
82
+ }
83
+ } else if (protoAction !== "ignore" && constructorAction === "ignore") {
84
+ if (suspectProtoRx.test(text) === false) {
85
+ return obj;
86
+ }
87
+ } else {
88
+ if (suspectConstructorRx.test(text) === false) {
89
+ return obj;
90
+ }
91
+ }
92
+ return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
93
+ }
94
+ function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
95
+ let next = [obj];
96
+ while (next.length) {
97
+ const nodes = next;
98
+ next = [];
99
+ for (const node of nodes) {
100
+ if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
101
+ if (safe === true) {
102
+ return null;
103
+ } else if (protoAction === "error") {
104
+ throw new SyntaxError("Object contains forbidden prototype property");
105
+ }
106
+ delete node.__proto__;
107
+ }
108
+ if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
109
+ if (safe === true) {
110
+ return null;
111
+ } else if (constructorAction === "error") {
112
+ throw new SyntaxError("Object contains forbidden prototype property");
113
+ }
114
+ delete node.constructor;
115
+ }
116
+ for (const key in node) {
117
+ const value = node[key];
118
+ if (value && typeof value === "object") {
119
+ next.push(value);
120
+ }
121
+ }
122
+ }
123
+ }
124
+ return obj;
125
+ }
126
+ function parse(text, reviver, options) {
127
+ const stackTraceLimit = Error.stackTraceLimit;
128
+ Error.stackTraceLimit = 0;
129
+ try {
130
+ return _parse(text, reviver, options);
131
+ } finally {
132
+ Error.stackTraceLimit = stackTraceLimit;
133
+ }
134
+ }
135
+ function safeParse(text, reviver) {
136
+ const stackTraceLimit = Error.stackTraceLimit;
137
+ Error.stackTraceLimit = 0;
138
+ try {
139
+ return _parse(text, reviver, { safe: true });
140
+ } catch (_e) {
141
+ return null;
142
+ } finally {
143
+ Error.stackTraceLimit = stackTraceLimit;
144
+ }
145
+ }
146
+ module2.exports = parse;
147
+ module2.exports.default = parse;
148
+ module2.exports.parse = parse;
149
+ module2.exports.safeParse = safeParse;
150
+ module2.exports.scan = filter;
151
+ }
152
+ });
153
+
154
+ // src/index.ts
155
+ var src_exports = {};
156
+ __export(src_exports, {
157
+ LangWatch: () => LangWatch,
158
+ LangWatchLLMSpan: () => LangWatchLLMSpan,
159
+ LangWatchRAGSpan: () => LangWatchRAGSpan,
160
+ LangWatchSpan: () => LangWatchSpan,
161
+ LangWatchTrace: () => LangWatchTrace,
162
+ convertFromVercelAIMessages: () => convertFromVercelAIMessages
163
+ });
164
+ module.exports = __toCommonJS(src_exports);
165
+ var import_events = __toESM(require("events"));
166
+ var import_nanoid = require("nanoid");
167
+ var import_zod2 = require("zod");
168
+ var import_zod_validation_error = require("zod-validation-error");
169
+
170
+ // src/helpers.ts
171
+ function camelToSnakeCase(str) {
172
+ return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
173
+ }
174
+ function camelToSnakeCaseNested(obj) {
175
+ if (Array.isArray(obj)) {
176
+ return obj.map(
177
+ (item) => camelToSnakeCaseNested(item)
178
+ );
179
+ } else if (typeof obj === "object" && obj !== null) {
180
+ const newObj = {};
181
+ for (const key in obj) {
182
+ if (obj.hasOwnProperty(key)) {
183
+ const newKey = camelToSnakeCase(key);
184
+ newObj[newKey] = camelToSnakeCaseNested(obj[key]);
185
+ }
186
+ }
187
+ return newObj;
188
+ } else {
189
+ return obj;
190
+ }
191
+ }
192
+
193
+ // src/server/types/tracer.generated.ts
194
+ var import_zod = require("zod");
195
+ var chatRoleSchema = import_zod.z.union([
196
+ import_zod.z.literal("system"),
197
+ import_zod.z.literal("user"),
198
+ import_zod.z.literal("assistant"),
199
+ import_zod.z.literal("function"),
200
+ import_zod.z.literal("tool"),
201
+ import_zod.z.literal("unknown")
202
+ ]);
203
+ var functionCallSchema = import_zod.z.object({
204
+ name: import_zod.z.string().optional(),
205
+ arguments: import_zod.z.string().optional()
206
+ });
207
+ var toolCallSchema = import_zod.z.object({
208
+ id: import_zod.z.string(),
209
+ type: import_zod.z.string(),
210
+ function: functionCallSchema
211
+ });
212
+ var chatRichContentSchema = import_zod.z.union([
213
+ import_zod.z.object({
214
+ type: import_zod.z.literal("text"),
215
+ text: import_zod.z.string().optional()
216
+ }),
217
+ import_zod.z.object({
218
+ type: import_zod.z.literal("image_url"),
219
+ image_url: import_zod.z.object({
220
+ url: import_zod.z.string(),
221
+ detail: import_zod.z.union([import_zod.z.literal("auto"), import_zod.z.literal("low"), import_zod.z.literal("high")]).optional()
222
+ }).optional()
223
+ })
224
+ ]);
225
+ var typedValueTextSchema = import_zod.z.object({
226
+ type: import_zod.z.literal("text"),
227
+ value: import_zod.z.string()
228
+ });
229
+ var typedValueRawSchema = import_zod.z.object({
230
+ type: import_zod.z.literal("raw"),
231
+ value: import_zod.z.string()
232
+ });
233
+ var jSONSerializableSchema = import_zod.z.union([
234
+ import_zod.z.string(),
235
+ import_zod.z.number(),
236
+ import_zod.z.boolean(),
237
+ import_zod.z.record(import_zod.z.any()),
238
+ import_zod.z.array(import_zod.z.any())
239
+ ]).nullable();
240
+ var typedValueJsonSchema = import_zod.z.object({
241
+ type: import_zod.z.literal("json"),
242
+ value: jSONSerializableSchema
243
+ });
244
+ var moneySchema = import_zod.z.object({
245
+ currency: import_zod.z.string(),
246
+ amount: import_zod.z.number()
247
+ });
248
+ var guardrailResultSchema = import_zod.z.object({
249
+ status: import_zod.z.union([
250
+ import_zod.z.literal("processed"),
251
+ import_zod.z.literal("skipped"),
252
+ import_zod.z.literal("error")
253
+ ]),
254
+ passed: import_zod.z.boolean(),
255
+ score: import_zod.z.number().optional().nullable(),
256
+ details: import_zod.z.string().optional().nullable(),
257
+ cost: moneySchema.optional().nullable()
258
+ });
259
+ var typedValueGuardrailResultSchema = import_zod.z.object({
260
+ type: import_zod.z.literal("guardrail_result"),
261
+ value: guardrailResultSchema
262
+ });
263
+ var errorCaptureSchema = import_zod.z.object({
264
+ has_error: import_zod.z.literal(true),
265
+ message: import_zod.z.string(),
266
+ stacktrace: import_zod.z.array(import_zod.z.string())
267
+ });
268
+ var spanMetricsSchema = import_zod.z.object({
269
+ prompt_tokens: import_zod.z.number().optional().nullable(),
270
+ completion_tokens: import_zod.z.number().optional().nullable(),
271
+ tokens_estimated: import_zod.z.boolean().optional().nullable(),
272
+ cost: import_zod.z.number().optional().nullable()
273
+ });
274
+ var spanParamsSchema = import_zod.z.object({
275
+ temperature: import_zod.z.number().optional(),
276
+ stream: import_zod.z.boolean().optional(),
277
+ functions: import_zod.z.array(import_zod.z.record(import_zod.z.any())).optional(),
278
+ tools: import_zod.z.array(import_zod.z.record(import_zod.z.any())).optional(),
279
+ tool_choice: import_zod.z.string().optional()
280
+ });
281
+ var spanTimestampsSchema = import_zod.z.object({
282
+ started_at: import_zod.z.number(),
283
+ first_token_at: import_zod.z.number().optional().nullable(),
284
+ finished_at: import_zod.z.number()
285
+ });
286
+ var spanTypesSchema = import_zod.z.union([
287
+ import_zod.z.literal("span"),
288
+ import_zod.z.literal("llm"),
289
+ import_zod.z.literal("chain"),
290
+ import_zod.z.literal("tool"),
291
+ import_zod.z.literal("agent"),
292
+ import_zod.z.literal("rag"),
293
+ import_zod.z.literal("guardrail"),
294
+ import_zod.z.literal("unknown")
295
+ ]);
296
+ var rAGChunkSchema = import_zod.z.object({
297
+ document_id: import_zod.z.string().optional().nullable(),
298
+ chunk_id: import_zod.z.string().optional().nullable(),
299
+ content: import_zod.z.union([import_zod.z.string(), import_zod.z.record(import_zod.z.any()), import_zod.z.array(import_zod.z.any())])
300
+ });
301
+ var traceInputSchema = import_zod.z.object({
302
+ value: import_zod.z.string(),
303
+ embeddings: import_zod.z.object({
304
+ model: import_zod.z.string(),
305
+ embeddings: import_zod.z.array(import_zod.z.number())
306
+ }).optional(),
307
+ satisfaction_score: import_zod.z.number().optional()
308
+ });
309
+ var traceOutputSchema = import_zod.z.object({
310
+ value: import_zod.z.string(),
311
+ embeddings: import_zod.z.object({
312
+ model: import_zod.z.string(),
313
+ embeddings: import_zod.z.array(import_zod.z.number())
314
+ }).optional()
315
+ });
316
+ var traceSchema = import_zod.z.object({
317
+ trace_id: import_zod.z.string(),
318
+ project_id: import_zod.z.string(),
319
+ metadata: import_zod.z.object({
320
+ thread_id: import_zod.z.string().optional(),
321
+ user_id: import_zod.z.string().optional(),
322
+ customer_id: import_zod.z.string().optional(),
323
+ labels: import_zod.z.array(import_zod.z.string()).optional(),
324
+ topic_id: import_zod.z.string().optional(),
325
+ subtopic_id: import_zod.z.string().optional()
326
+ }),
327
+ timestamps: import_zod.z.object({
328
+ started_at: import_zod.z.number(),
329
+ inserted_at: import_zod.z.number(),
330
+ updated_at: import_zod.z.number()
331
+ }),
332
+ input: traceInputSchema,
333
+ output: traceOutputSchema.optional(),
334
+ metrics: import_zod.z.object({
335
+ first_token_ms: import_zod.z.number().optional().nullable(),
336
+ total_time_ms: import_zod.z.number().optional().nullable(),
337
+ prompt_tokens: import_zod.z.number().optional().nullable(),
338
+ completion_tokens: import_zod.z.number().optional().nullable(),
339
+ total_cost: import_zod.z.number().optional().nullable(),
340
+ tokens_estimated: import_zod.z.boolean().optional().nullable()
341
+ }),
342
+ error: errorCaptureSchema.optional().nullable(),
343
+ indexing_md5s: import_zod.z.array(import_zod.z.string()).optional()
344
+ });
345
+ var elasticSearchTraceSchema = traceSchema.and(
346
+ import_zod.z.object({
347
+ timestamps: traceSchema.shape.timestamps.and(
348
+ import_zod.z.object({
349
+ updated_at: import_zod.z.number()
350
+ })
351
+ )
352
+ })
353
+ );
354
+ var traceCheckSchema = import_zod.z.object({
355
+ trace_id: import_zod.z.string(),
356
+ check_id: import_zod.z.string(),
357
+ project_id: import_zod.z.string(),
358
+ check_type: import_zod.z.string(),
359
+ check_name: import_zod.z.string(),
360
+ is_guardrail: import_zod.z.boolean(),
361
+ status: import_zod.z.union([
362
+ import_zod.z.literal("scheduled"),
363
+ import_zod.z.literal("in_progress"),
364
+ import_zod.z.literal("error"),
365
+ import_zod.z.literal("skipped"),
366
+ import_zod.z.literal("processed")
367
+ ]),
368
+ passed: import_zod.z.boolean().optional(),
369
+ score: import_zod.z.number().optional(),
370
+ details: import_zod.z.string().optional(),
371
+ error: errorCaptureSchema.optional().nullable(),
372
+ retries: import_zod.z.number().optional(),
373
+ timestamps: import_zod.z.object({
374
+ inserted_at: import_zod.z.number().optional(),
375
+ started_at: import_zod.z.number().optional(),
376
+ finished_at: import_zod.z.number().optional(),
377
+ updated_at: import_zod.z.number()
378
+ }),
379
+ trace_metadata: import_zod.z.object({
380
+ thread_id: import_zod.z.string().optional(),
381
+ user_id: import_zod.z.string().optional(),
382
+ customer_id: import_zod.z.string().optional(),
383
+ labels: import_zod.z.array(import_zod.z.string()).optional(),
384
+ topics: import_zod.z.array(import_zod.z.string()).optional()
385
+ })
386
+ });
387
+ var experimentSchema = import_zod.z.object({
388
+ experiment_id: import_zod.z.string(),
389
+ variant: import_zod.z.number()
390
+ });
391
+ var eventSchema = import_zod.z.object({
392
+ event_id: import_zod.z.string(),
393
+ event_type: import_zod.z.string(),
394
+ project_id: import_zod.z.string(),
395
+ metrics: import_zod.z.record(import_zod.z.number()),
396
+ event_details: import_zod.z.record(import_zod.z.string()),
397
+ trace_id: import_zod.z.string().optional(),
398
+ trace_metadata: import_zod.z.object({
399
+ thread_id: import_zod.z.string().optional(),
400
+ user_id: import_zod.z.string().optional(),
401
+ customer_id: import_zod.z.string().optional(),
402
+ labels: import_zod.z.array(import_zod.z.string()).optional(),
403
+ topics: import_zod.z.array(import_zod.z.string()).optional()
404
+ }),
405
+ timestamps: import_zod.z.object({
406
+ started_at: import_zod.z.number(),
407
+ inserted_at: import_zod.z.number(),
408
+ updated_at: import_zod.z.number()
409
+ })
410
+ });
411
+ var elasticSearchEventSchema = eventSchema.omit({ metrics: true, event_details: true }).and(
412
+ import_zod.z.object({
413
+ metrics: import_zod.z.array(
414
+ import_zod.z.object({
415
+ key: import_zod.z.string(),
416
+ value: import_zod.z.number()
417
+ })
418
+ ),
419
+ event_details: import_zod.z.array(
420
+ import_zod.z.object({
421
+ key: import_zod.z.string(),
422
+ value: import_zod.z.string()
423
+ })
424
+ )
425
+ })
426
+ );
427
+ var trackEventRESTParamsValidatorSchema = eventSchema.omit({
428
+ event_id: true,
429
+ project_id: true,
430
+ timestamps: true,
431
+ event_details: true,
432
+ trace_metadata: true
433
+ }).and(
434
+ import_zod.z.object({
435
+ event_id: import_zod.z.string().optional(),
436
+ event_details: import_zod.z.record(import_zod.z.string()).optional(),
437
+ timestamp: import_zod.z.number().optional()
438
+ })
439
+ );
440
+ var chatMessageSchema = import_zod.z.object({
441
+ role: chatRoleSchema.optional(),
442
+ content: import_zod.z.union([import_zod.z.string(), import_zod.z.array(chatRichContentSchema)]).optional().nullable(),
443
+ function_call: functionCallSchema.optional().nullable(),
444
+ tool_calls: import_zod.z.array(toolCallSchema).optional().nullable(),
445
+ tool_call_id: import_zod.z.string().optional().nullable()
446
+ });
447
+ var typedValueChatMessagesSchema = import_zod.z.object({
448
+ type: import_zod.z.literal("chat_messages"),
449
+ value: import_zod.z.array(chatMessageSchema)
450
+ });
451
+ var spanInputOutputSchema = import_zod.z.union([
452
+ typedValueTextSchema,
453
+ typedValueChatMessagesSchema,
454
+ typedValueGuardrailResultSchema,
455
+ typedValueJsonSchema,
456
+ typedValueRawSchema
457
+ ]);
458
+ var baseSpanSchema = import_zod.z.object({
459
+ span_id: import_zod.z.string(),
460
+ parent_id: import_zod.z.string().optional().nullable(),
461
+ trace_id: import_zod.z.string(),
462
+ type: spanTypesSchema,
463
+ name: import_zod.z.string().optional().nullable(),
464
+ input: spanInputOutputSchema.optional().nullable(),
465
+ outputs: import_zod.z.array(spanInputOutputSchema),
466
+ error: errorCaptureSchema.optional().nullable(),
467
+ timestamps: spanTimestampsSchema,
468
+ metrics: spanMetricsSchema.optional().nullable()
469
+ });
470
+ var lLMSpanSchema = baseSpanSchema.extend({
471
+ type: import_zod.z.literal("llm"),
472
+ vendor: import_zod.z.string().optional().nullable(),
473
+ model: import_zod.z.string(),
474
+ params: spanParamsSchema
475
+ });
476
+ var rAGSpanSchema = baseSpanSchema.extend({
477
+ type: import_zod.z.literal("rag"),
478
+ contexts: import_zod.z.array(rAGChunkSchema)
479
+ });
480
+ var spanSchema = import_zod.z.union([
481
+ lLMSpanSchema,
482
+ rAGSpanSchema,
483
+ baseSpanSchema
484
+ ]);
485
+ var spanInputOutputValidatorSchema = spanInputOutputSchema.and(
486
+ import_zod.z.object({
487
+ value: import_zod.z.any()
488
+ })
489
+ );
490
+ var spanValidatorSchema = import_zod.z.union([
491
+ lLMSpanSchema.omit({ input: true, outputs: true }),
492
+ rAGSpanSchema.omit({ input: true, outputs: true }),
493
+ baseSpanSchema.omit({ input: true, outputs: true })
494
+ ]).and(
495
+ import_zod.z.object({
496
+ input: spanInputOutputValidatorSchema.optional().nullable(),
497
+ outputs: import_zod.z.array(spanInputOutputValidatorSchema)
498
+ })
499
+ );
500
+ var collectorRESTParamsSchema = import_zod.z.object({
501
+ trace_id: import_zod.z.union([import_zod.z.string(), import_zod.z.undefined()]).optional().nullable(),
502
+ spans: import_zod.z.array(spanSchema),
503
+ metadata: import_zod.z.object({
504
+ user_id: import_zod.z.union([import_zod.z.string(), import_zod.z.undefined()]).optional().nullable(),
505
+ thread_id: import_zod.z.union([import_zod.z.string(), import_zod.z.undefined()]).optional().nullable(),
506
+ customer_id: import_zod.z.union([import_zod.z.string(), import_zod.z.undefined()]).optional().nullable(),
507
+ labels: import_zod.z.union([import_zod.z.array(import_zod.z.string()), import_zod.z.undefined()]).optional().nullable(),
508
+ experiments: import_zod.z.union([import_zod.z.array(experimentSchema), import_zod.z.undefined()]).optional().nullable()
509
+ }).optional()
510
+ });
511
+ var collectorRESTParamsValidatorSchema = collectorRESTParamsSchema.omit({ spans: true });
512
+ var datasetSpanSchema = import_zod.z.union([
513
+ baseSpanSchema.omit({
514
+ project_id: true,
515
+ trace_id: true,
516
+ id: true,
517
+ timestamps: true,
518
+ metrics: true
519
+ }),
520
+ lLMSpanSchema.omit({
521
+ project_id: true,
522
+ trace_id: true,
523
+ id: true,
524
+ timestamps: true,
525
+ metrics: true
526
+ }),
527
+ rAGSpanSchema.omit({
528
+ project_id: true,
529
+ trace_id: true,
530
+ id: true,
531
+ timestamps: true,
532
+ metrics: true
533
+ })
534
+ ]);
535
+
536
+ // node_modules/@ai-sdk/provider-utils/dist/index.mjs
537
+ var import_non_secure = require("nanoid/non-secure");
538
+ var import_secure_json_parse = __toESM(require_secure_json_parse(), 1);
539
+ var generateId = (0, import_non_secure.customAlphabet)(
540
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
541
+ 7
542
+ );
543
+ function convertUint8ArrayToBase64(array) {
544
+ let latin1string = "";
545
+ for (let i = 0; i < array.length; i++) {
546
+ latin1string += String.fromCodePoint(array[i]);
547
+ }
548
+ return globalThis.btoa(latin1string);
549
+ }
550
+
551
+ // src/utils.ts
552
+ var convertImageToUrl = (image, mimeType) => {
553
+ try {
554
+ return image instanceof URL ? image.toString() : typeof image === "string" ? image : `data:${mimeType != null ? mimeType : "image/jpeg"};base64,${convertUint8ArrayToBase64(
555
+ image
556
+ )}`;
557
+ } catch (e) {
558
+ console.error("[LangWatch] error converting vercel ui image to url:", e);
559
+ return "";
560
+ }
561
+ };
562
+ function convertFromVercelAIMessages(messages) {
563
+ var _a;
564
+ const lwMessages = [];
565
+ for (const { role, content } of messages) {
566
+ switch (role) {
567
+ case "system": {
568
+ lwMessages.push({ role: "system", content });
569
+ break;
570
+ }
571
+ case "user": {
572
+ if (Array.isArray(content) && content.length === 1 && ((_a = content[0]) == null ? void 0 : _a.type) === "text") {
573
+ lwMessages.push({ role: "user", content: content[0].text });
574
+ break;
575
+ }
576
+ lwMessages.push({
577
+ role: "user",
578
+ content: Array.isArray(content) ? content.map((part) => {
579
+ switch (part.type) {
580
+ case "text": {
581
+ return { type: "text", text: part.text };
582
+ }
583
+ case "image": {
584
+ return {
585
+ type: "image_url",
586
+ image_url: {
587
+ url: convertImageToUrl(part.image, part.mimeType)
588
+ }
589
+ };
590
+ }
591
+ }
592
+ }) : content
593
+ });
594
+ break;
595
+ }
596
+ case "assistant": {
597
+ let text = "";
598
+ const toolCalls = [];
599
+ if (Array.isArray(content)) {
600
+ for (const part of content) {
601
+ switch (part.type) {
602
+ case "text": {
603
+ text += part.text;
604
+ break;
605
+ }
606
+ case "tool-call": {
607
+ toolCalls.push({
608
+ id: part.toolCallId,
609
+ type: "function",
610
+ function: {
611
+ name: part.toolName,
612
+ arguments: JSON.stringify(part.args)
613
+ }
614
+ });
615
+ break;
616
+ }
617
+ default: {
618
+ const _exhaustiveCheck = part;
619
+ throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
620
+ }
621
+ }
622
+ }
623
+ } else {
624
+ text = content;
625
+ }
626
+ lwMessages.push({
627
+ role: "assistant",
628
+ content: text,
629
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
630
+ });
631
+ break;
632
+ }
633
+ case "tool": {
634
+ for (const toolResponse of content) {
635
+ lwMessages.push({
636
+ role: "tool",
637
+ tool_call_id: toolResponse.toolCallId,
638
+ content: JSON.stringify(toolResponse.result)
639
+ });
640
+ }
641
+ break;
642
+ }
643
+ default: {
644
+ const _exhaustiveCheck = role;
645
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
646
+ }
647
+ }
648
+ }
649
+ return lwMessages;
650
+ }
651
+
652
+ // src/index.ts
653
+ var LangWatch = class extends import_events.default {
654
+ constructor({
655
+ apiKey,
656
+ endpoint = ((_a) => (_a = process.env.LANGWATCH_ENDPOINT) != null ? _a : "https://app.langwatch.ai")()
657
+ } = {}) {
658
+ super();
659
+ const apiKey_ = apiKey != null ? apiKey : process.env.LANGWATCH_API_KEY;
660
+ if (!apiKey_) {
661
+ console.warn(
662
+ "[LangWatch] \u26A0\uFE0F LangWatch API key is not set, please set the LANGWATCH_API_KEY environment variable or pass it in the constructor. Traces will not be captured."
663
+ );
664
+ }
665
+ this.apiKey = apiKey_;
666
+ this.endpoint = endpoint;
667
+ }
668
+ getTrace({
669
+ traceId,
670
+ metadata
671
+ } = {}) {
672
+ return new LangWatchTrace({
673
+ client: this,
674
+ traceId: traceId != null ? traceId : `trace_${(0, import_nanoid.nanoid)()}`,
675
+ metadata
676
+ });
677
+ }
678
+ async sendTrace(params) {
679
+ const backoff = [1e3, 2e3, 4e3, 8e3, 16e3];
680
+ for (const backoffTime of backoff) {
681
+ try {
682
+ await this._sendTrace(params);
683
+ return;
684
+ } catch (e) {
685
+ console.warn(
686
+ `[LangWatch] \u26A0\uFE0F Failed to send trace, retrying in ${backoffTime / 1e3}s`
687
+ );
688
+ await new Promise((resolve) => setTimeout(resolve, backoffTime));
689
+ }
690
+ }
691
+ console.warn("[LangWatch] \u26A0\uFE0F Failed to send trace, giving up");
692
+ }
693
+ async _sendTrace(params) {
694
+ if (params.spans.length === 0) {
695
+ return;
696
+ }
697
+ if (!this.apiKey) {
698
+ const error = new Error(
699
+ "[LangWatch] \u26A0\uFE0F LangWatch API key is not set, LLMs traces will not be sent, go to https://langwatch.ai to set it up"
700
+ );
701
+ this.emit("error", error);
702
+ console.warn(error.message);
703
+ return;
704
+ }
705
+ const response = await fetch(`${this.endpoint}/api/collector`, {
706
+ method: "POST",
707
+ headers: {
708
+ "X-Auth-Token": this.apiKey,
709
+ "Content-Type": "application/json"
710
+ },
711
+ body: JSON.stringify(params)
712
+ });
713
+ if (response.status === 429) {
714
+ const error = new Error(
715
+ "[LangWatch] \u26A0\uFE0F Rate limit exceeded, dropping message from being sent to LangWatch. Please check your dashboard to upgrade your plan."
716
+ );
717
+ this.emit("error", error);
718
+ console.warn(error.message);
719
+ return;
720
+ }
721
+ if (!response.ok) {
722
+ const error = new Error(
723
+ `[LangWatch] \u26A0\uFE0F Failed to send trace, status: ${response.status}`
724
+ );
725
+ this.emit("error", error);
726
+ throw error;
727
+ }
728
+ }
729
+ };
730
+ var LangWatchTrace = class {
731
+ constructor({
732
+ client,
733
+ traceId,
734
+ metadata
735
+ }) {
736
+ this.finishedSpans = {};
737
+ this.client = client;
738
+ this.traceId = traceId;
739
+ this.metadata = metadata;
740
+ }
741
+ update({ metadata }) {
742
+ var _a, _b;
743
+ this.metadata = __spreadValues(__spreadValues(__spreadValues({}, this.metadata), metadata), typeof metadata.labels !== "undefined" ? { labels: [...(_b = (_a = this.metadata) == null ? void 0 : _a.labels) != null ? _b : [], ...metadata.labels] } : {});
744
+ }
745
+ startSpan(params) {
746
+ const span = new LangWatchSpan(__spreadValues({
747
+ trace: this
748
+ }, params));
749
+ return span;
750
+ }
751
+ startLLMSpan(params) {
752
+ const span = new LangWatchLLMSpan(__spreadValues({
753
+ trace: this
754
+ }, params));
755
+ return span;
756
+ }
757
+ startRAGSpan(params) {
758
+ const span = new LangWatchRAGSpan(__spreadValues({
759
+ trace: this
760
+ }, params));
761
+ return span;
762
+ }
763
+ onEnd(span) {
764
+ this.finishedSpans[span.span_id] = span;
765
+ this.delayedSendSpans();
766
+ }
767
+ delayedSendSpans() {
768
+ clearTimeout(this.timeoutRef);
769
+ this.timeoutRef = setTimeout(() => {
770
+ void this.sendSpans();
771
+ }, 1e3);
772
+ }
773
+ async sendSpans() {
774
+ clearTimeout(this.timeoutRef);
775
+ let trace = void 0;
776
+ try {
777
+ trace = collectorRESTParamsSchema.parse({
778
+ trace_id: this.traceId,
779
+ metadata: camelToSnakeCaseNested(this.metadata),
780
+ spans: Object.values(this.finishedSpans)
781
+ });
782
+ } catch (error) {
783
+ if (error instanceof import_zod2.ZodError) {
784
+ console.warn("[LangWatch] \u26A0\uFE0F Failed to parse trace");
785
+ console.warn((0, import_zod_validation_error.fromZodError)(error).message);
786
+ } else {
787
+ console.warn(error);
788
+ }
789
+ this.client.emit("error", error);
790
+ }
791
+ if (trace) {
792
+ await this.client.sendTrace(trace);
793
+ }
794
+ }
795
+ };
796
+ var LangWatchSpan = class _LangWatchSpan {
797
+ constructor({
798
+ trace,
799
+ spanId,
800
+ parentId,
801
+ type,
802
+ name,
803
+ input,
804
+ outputs,
805
+ error,
806
+ timestamps,
807
+ metrics
808
+ }) {
809
+ this.spanId = spanId != null ? spanId : `span_${(0, import_nanoid.nanoid)()}`;
810
+ this.parentId = parentId;
811
+ this.trace = trace;
812
+ this.type = type != null ? type : "span";
813
+ this.name = name;
814
+ this.input = input;
815
+ this.outputs = outputs != null ? outputs : [];
816
+ this.error = error;
817
+ this.timestamps = timestamps != null ? timestamps : {
818
+ startedAt: Date.now()
819
+ };
820
+ this.metrics = metrics;
821
+ }
822
+ update(params) {
823
+ if (params.type) {
824
+ this.type = params.type;
825
+ }
826
+ if ("name" in params) {
827
+ this.name = params.name;
828
+ }
829
+ if ("input" in params) {
830
+ this.input = params.input;
831
+ }
832
+ if (params.outputs) {
833
+ this.outputs = params.outputs;
834
+ }
835
+ if ("error" in params) {
836
+ this.error = params.error;
837
+ }
838
+ if (params.timestamps) {
839
+ this.timestamps = params.timestamps;
840
+ }
841
+ if ("metrics" in params) {
842
+ this.metrics = params.metrics;
843
+ }
844
+ }
845
+ startSpan(params) {
846
+ const span = new _LangWatchSpan(__spreadValues({
847
+ trace: this.trace,
848
+ parentId: this.spanId
849
+ }, params));
850
+ return span;
851
+ }
852
+ startLLMSpan(params) {
853
+ const span = new LangWatchLLMSpan(__spreadValues({
854
+ trace: this.trace,
855
+ parentId: this.spanId
856
+ }, params));
857
+ return span;
858
+ }
859
+ startRAGSpan(params) {
860
+ const span = new LangWatchRAGSpan(__spreadValues({
861
+ trace: this.trace,
862
+ parentId: this.spanId
863
+ }, params));
864
+ return span;
865
+ }
866
+ end(params) {
867
+ this.timestamps.finishedAt = Date.now();
868
+ if (params) {
869
+ this.update(params);
870
+ }
871
+ try {
872
+ const finalSpan = spanSchema.parse(
873
+ camelToSnakeCaseNested(__spreadProps(__spreadValues({}, this), {
874
+ trace: void 0,
875
+ traceId: this.trace.traceId,
876
+ timestamps: __spreadProps(__spreadValues({}, this.timestamps), {
877
+ finishedAt: this.timestamps.finishedAt
878
+ })
879
+ }))
880
+ );
881
+ this.trace.onEnd(finalSpan);
882
+ } catch (error) {
883
+ if (error instanceof import_zod2.ZodError) {
884
+ console.warn("[LangWatch] \u26A0\uFE0F Failed to parse span");
885
+ console.warn((0, import_zod_validation_error.fromZodError)(error).message);
886
+ } else {
887
+ console.warn(error);
888
+ }
889
+ this.trace.client.emit("error", error);
890
+ }
891
+ }
892
+ };
893
+ var LangWatchLLMSpan = class extends LangWatchSpan {
894
+ constructor(params) {
895
+ var _a, _b;
896
+ super(__spreadValues({}, params));
897
+ this.type = "llm";
898
+ this.model = (_a = params.model) != null ? _a : "unknown";
899
+ this.params = (_b = params.params) != null ? _b : {};
900
+ }
901
+ update(params) {
902
+ super.update(params);
903
+ if (params.model) {
904
+ this.model = params.model;
905
+ }
906
+ if (params.params) {
907
+ this.params = params.params;
908
+ }
909
+ }
910
+ end(params) {
911
+ super.end(params);
912
+ }
913
+ };
914
+ var LangWatchRAGSpan = class extends LangWatchSpan {
915
+ constructor(params) {
916
+ var _a;
917
+ super(__spreadValues({}, params));
918
+ this.type = "rag";
919
+ this.contexts = (_a = params.contexts) != null ? _a : [];
920
+ }
921
+ update(params) {
922
+ super.update(params);
923
+ if (params.contexts) {
924
+ this.contexts = params.contexts;
925
+ }
926
+ }
927
+ end(params) {
928
+ super.end(params);
929
+ }
930
+ };
931
+ // Annotate the CommonJS export names for ESM import in node:
932
+ 0 && (module.exports = {
933
+ LangWatch,
934
+ LangWatchLLMSpan,
935
+ LangWatchRAGSpan,
936
+ LangWatchSpan,
937
+ LangWatchTrace,
938
+ convertFromVercelAIMessages
939
+ });
940
+ //# sourceMappingURL=index.js.map