langwatch 0.1.1 → 0.1.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.
package/dist/index.js CHANGED
@@ -30,110 +30,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  ));
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
- // node_modules/secure-json-parse/index.js
34
- var require_secure_json_parse = __commonJS({
35
- "node_modules/secure-json-parse/index.js"(exports2, module2) {
36
- "use strict";
37
- var hasBuffer = typeof Buffer !== "undefined";
38
- var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
39
- 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*:/;
40
- function _parse(text, reviver, options) {
41
- if (options == null) {
42
- if (reviver !== null && typeof reviver === "object") {
43
- options = reviver;
44
- reviver = void 0;
45
- }
46
- }
47
- if (hasBuffer && Buffer.isBuffer(text)) {
48
- text = text.toString();
49
- }
50
- if (text && text.charCodeAt(0) === 65279) {
51
- text = text.slice(1);
52
- }
53
- const obj = JSON.parse(text, reviver);
54
- if (obj === null || typeof obj !== "object") {
55
- return obj;
56
- }
57
- const protoAction = options && options.protoAction || "error";
58
- const constructorAction = options && options.constructorAction || "error";
59
- if (protoAction === "ignore" && constructorAction === "ignore") {
60
- return obj;
61
- }
62
- if (protoAction !== "ignore" && constructorAction !== "ignore") {
63
- if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
64
- return obj;
65
- }
66
- } else if (protoAction !== "ignore" && constructorAction === "ignore") {
67
- if (suspectProtoRx.test(text) === false) {
68
- return obj;
69
- }
70
- } else {
71
- if (suspectConstructorRx.test(text) === false) {
72
- return obj;
73
- }
74
- }
75
- return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
76
- }
77
- function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
78
- let next = [obj];
79
- while (next.length) {
80
- const nodes = next;
81
- next = [];
82
- for (const node of nodes) {
83
- if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
84
- if (safe === true) {
85
- return null;
86
- } else if (protoAction === "error") {
87
- throw new SyntaxError("Object contains forbidden prototype property");
88
- }
89
- delete node.__proto__;
90
- }
91
- if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
92
- if (safe === true) {
93
- return null;
94
- } else if (constructorAction === "error") {
95
- throw new SyntaxError("Object contains forbidden prototype property");
96
- }
97
- delete node.constructor;
98
- }
99
- for (const key in node) {
100
- const value = node[key];
101
- if (value && typeof value === "object") {
102
- next.push(value);
103
- }
104
- }
105
- }
106
- }
107
- return obj;
108
- }
109
- function parse(text, reviver, options) {
110
- const stackTraceLimit = Error.stackTraceLimit;
111
- Error.stackTraceLimit = 0;
112
- try {
113
- return _parse(text, reviver, options);
114
- } finally {
115
- Error.stackTraceLimit = stackTraceLimit;
116
- }
117
- }
118
- function safeParse(text, reviver) {
119
- const stackTraceLimit = Error.stackTraceLimit;
120
- Error.stackTraceLimit = 0;
121
- try {
122
- return _parse(text, reviver, { safe: true });
123
- } catch (_e) {
124
- return null;
125
- } finally {
126
- Error.stackTraceLimit = stackTraceLimit;
127
- }
128
- }
129
- module2.exports = parse;
130
- module2.exports.default = parse;
131
- module2.exports.parse = parse;
132
- module2.exports.safeParse = safeParse;
133
- module2.exports.scan = filter;
134
- }
135
- });
136
-
137
33
  // node_modules/decamelize/index.js
138
34
  var require_decamelize = __commonJS({
139
35
  "node_modules/decamelize/index.js"(exports2, module2) {
@@ -758,6 +654,110 @@ var require_dist = __commonJS({
758
654
  }
759
655
  });
760
656
 
657
+ // node_modules/secure-json-parse/index.js
658
+ var require_secure_json_parse = __commonJS({
659
+ "node_modules/secure-json-parse/index.js"(exports2, module2) {
660
+ "use strict";
661
+ var hasBuffer = typeof Buffer !== "undefined";
662
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
663
+ 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*:/;
664
+ function _parse(text, reviver, options) {
665
+ if (options == null) {
666
+ if (reviver !== null && typeof reviver === "object") {
667
+ options = reviver;
668
+ reviver = void 0;
669
+ }
670
+ }
671
+ if (hasBuffer && Buffer.isBuffer(text)) {
672
+ text = text.toString();
673
+ }
674
+ if (text && text.charCodeAt(0) === 65279) {
675
+ text = text.slice(1);
676
+ }
677
+ const obj = JSON.parse(text, reviver);
678
+ if (obj === null || typeof obj !== "object") {
679
+ return obj;
680
+ }
681
+ const protoAction = options && options.protoAction || "error";
682
+ const constructorAction = options && options.constructorAction || "error";
683
+ if (protoAction === "ignore" && constructorAction === "ignore") {
684
+ return obj;
685
+ }
686
+ if (protoAction !== "ignore" && constructorAction !== "ignore") {
687
+ if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
688
+ return obj;
689
+ }
690
+ } else if (protoAction !== "ignore" && constructorAction === "ignore") {
691
+ if (suspectProtoRx.test(text) === false) {
692
+ return obj;
693
+ }
694
+ } else {
695
+ if (suspectConstructorRx.test(text) === false) {
696
+ return obj;
697
+ }
698
+ }
699
+ return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
700
+ }
701
+ function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
702
+ let next = [obj];
703
+ while (next.length) {
704
+ const nodes = next;
705
+ next = [];
706
+ for (const node of nodes) {
707
+ if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
708
+ if (safe === true) {
709
+ return null;
710
+ } else if (protoAction === "error") {
711
+ throw new SyntaxError("Object contains forbidden prototype property");
712
+ }
713
+ delete node.__proto__;
714
+ }
715
+ if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
716
+ if (safe === true) {
717
+ return null;
718
+ } else if (constructorAction === "error") {
719
+ throw new SyntaxError("Object contains forbidden prototype property");
720
+ }
721
+ delete node.constructor;
722
+ }
723
+ for (const key in node) {
724
+ const value = node[key];
725
+ if (value && typeof value === "object") {
726
+ next.push(value);
727
+ }
728
+ }
729
+ }
730
+ }
731
+ return obj;
732
+ }
733
+ function parse(text, reviver, options) {
734
+ const stackTraceLimit = Error.stackTraceLimit;
735
+ Error.stackTraceLimit = 0;
736
+ try {
737
+ return _parse(text, reviver, options);
738
+ } finally {
739
+ Error.stackTraceLimit = stackTraceLimit;
740
+ }
741
+ }
742
+ function safeParse(text, reviver) {
743
+ const stackTraceLimit = Error.stackTraceLimit;
744
+ Error.stackTraceLimit = 0;
745
+ try {
746
+ return _parse(text, reviver, { safe: true });
747
+ } catch (_e) {
748
+ return null;
749
+ } finally {
750
+ Error.stackTraceLimit = stackTraceLimit;
751
+ }
752
+ }
753
+ module2.exports = parse;
754
+ module2.exports.default = parse;
755
+ module2.exports.parse = parse;
756
+ module2.exports.safeParse = safeParse;
757
+ module2.exports.scan = filter;
758
+ }
759
+ });
760
+
761
761
  // src/index.ts
762
762
  var src_exports = {};
763
763
  __export(src_exports, {
@@ -1580,11 +1580,11 @@ var datetimeRegex = (args) => {
1580
1580
  }
1581
1581
  }
1582
1582
  };
1583
- function isValidIP(ip, version) {
1584
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1583
+ function isValidIP(ip, version2) {
1584
+ if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
1585
1585
  return true;
1586
1586
  }
1587
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
1587
+ if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
1588
1588
  return true;
1589
1589
  }
1590
1590
  return false;
@@ -4699,546 +4699,123 @@ function fromError(err, options = {}) {
4699
4699
  return toValidationError(options)(err);
4700
4700
  }
4701
4701
 
4702
- // src/typeUtils.ts
4703
- function camelToSnakeCase(str) {
4704
- return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
4705
- }
4706
- function camelToSnakeCaseNested(obj) {
4707
- if (Array.isArray(obj)) {
4708
- return obj.map(
4709
- (item) => camelToSnakeCaseNested(item)
4710
- );
4711
- } else if (typeof obj === "object" && obj !== null) {
4712
- const newObj = {};
4713
- for (const key in obj) {
4714
- if (obj.hasOwnProperty(key)) {
4715
- const newKey = camelToSnakeCase(key);
4716
- newObj[newKey] = camelToSnakeCaseNested(obj[key]);
4717
- }
4702
+ // package.json
4703
+ var version = "0.1.3";
4704
+
4705
+ // src/evaluations.ts
4706
+ var evaluate = async (params) => {
4707
+ const slug = "slug" in params ? params.slug : params.evaluator;
4708
+ const span = optionalCreateSpan({
4709
+ trace: params.trace,
4710
+ span: params.span,
4711
+ name: params.name ? params.name : slug,
4712
+ type: params.asGuardrail ? "guardrail" : "evaluation"
4713
+ });
4714
+ try {
4715
+ const requestParams = prepareData({
4716
+ ...params,
4717
+ slug,
4718
+ traceId: span?.trace.traceId,
4719
+ spanId: span?.spanId,
4720
+ span
4721
+ });
4722
+ const response = await fetch(requestParams.url, {
4723
+ method: "POST",
4724
+ headers: requestParams.headers,
4725
+ body: JSON.stringify(requestParams.json)
4726
+ });
4727
+ if (!response.ok) {
4728
+ throw new Error(`HTTP error! status: ${response.status}`);
4718
4729
  }
4719
- return newObj;
4720
- } else {
4721
- return obj;
4730
+ const result = await response.json();
4731
+ return handleResponse(result, span, params.asGuardrail);
4732
+ } catch (e) {
4733
+ return handleException(e, span, params.asGuardrail);
4722
4734
  }
4723
- }
4724
-
4725
- // src/server/types/tracer.generated.ts
4726
- var chatRoleSchema = z.union([
4727
- z.literal("system"),
4728
- z.literal("user"),
4729
- z.literal("assistant"),
4730
- z.literal("function"),
4731
- z.literal("tool"),
4732
- z.literal("unknown")
4733
- ]);
4734
- var functionCallSchema = z.object({
4735
- name: z.string().optional(),
4736
- arguments: z.string().optional()
4737
- });
4738
- var toolCallSchema = z.object({
4739
- id: z.string(),
4740
- type: z.string(),
4741
- function: functionCallSchema
4742
- });
4743
- var chatRichContentSchema = z.union([
4744
- z.object({
4745
- type: z.literal("text"),
4746
- text: z.string().optional()
4747
- }),
4748
- z.object({
4749
- type: z.literal("image_url"),
4750
- image_url: z.object({
4751
- url: z.string(),
4752
- detail: z.union([z.literal("auto"), z.literal("low"), z.literal("high")]).optional()
4753
- }).optional()
4754
- })
4755
- ]);
4756
- var typedValueTextSchema = z.object({
4757
- type: z.literal("text"),
4758
- value: z.string()
4759
- });
4760
- var typedValueRawSchema = z.object({
4761
- type: z.literal("raw"),
4762
- value: z.string()
4763
- });
4764
- var jSONSerializableSchema = z.union([
4765
- z.string(),
4766
- z.number(),
4767
- z.boolean(),
4768
- z.record(z.any()),
4769
- z.array(z.any())
4770
- ]).nullable();
4771
- var typedValueJsonSchema = z.object({
4772
- type: z.literal("json"),
4773
- value: jSONSerializableSchema
4774
- });
4775
- var moneySchema = z.object({
4776
- currency: z.string(),
4777
- amount: z.number()
4778
- });
4779
- var guardrailResultSchema = z.object({
4780
- status: z.union([
4781
- z.literal("processed"),
4782
- z.literal("skipped"),
4783
- z.literal("error")
4784
- ]),
4785
- passed: z.boolean(),
4786
- score: z.number().optional().nullable(),
4787
- details: z.string().optional().nullable(),
4788
- cost: moneySchema.optional().nullable()
4789
- });
4790
- var typedValueGuardrailResultSchema = z.object({
4791
- type: z.literal("guardrail_result"),
4792
- value: guardrailResultSchema
4793
- });
4794
- var errorCaptureSchema = z.object({
4795
- has_error: z.literal(true),
4796
- message: z.string(),
4797
- stacktrace: z.array(z.string())
4798
- });
4799
- var spanMetricsSchema = z.object({
4800
- prompt_tokens: z.number().optional().nullable(),
4801
- completion_tokens: z.number().optional().nullable(),
4802
- tokens_estimated: z.boolean().optional().nullable(),
4803
- cost: z.number().optional().nullable()
4804
- });
4805
- var spanParamsSchema = z.object({
4806
- temperature: z.number().optional(),
4807
- stream: z.boolean().optional(),
4808
- functions: z.array(z.record(z.any())).optional(),
4809
- tools: z.array(z.record(z.any())).optional(),
4810
- tool_choice: z.string().optional()
4811
- });
4812
- var spanTimestampsSchema = z.object({
4813
- started_at: z.number(),
4814
- first_token_at: z.number().optional().nullable(),
4815
- finished_at: z.number()
4816
- });
4817
- var spanTypesSchema = z.union([
4818
- z.literal("span"),
4819
- z.literal("llm"),
4820
- z.literal("chain"),
4821
- z.literal("tool"),
4822
- z.literal("agent"),
4823
- z.literal("rag"),
4824
- z.literal("guardrail"),
4825
- z.literal("unknown")
4826
- ]);
4827
- var rAGChunkSchema = z.object({
4828
- document_id: z.string().optional().nullable(),
4829
- chunk_id: z.string().optional().nullable(),
4830
- content: z.union([z.string(), z.record(z.any()), z.array(z.any())])
4831
- });
4832
- var traceInputSchema = z.object({
4833
- value: z.string(),
4834
- embeddings: z.object({
4835
- model: z.string(),
4836
- embeddings: z.array(z.number())
4837
- }).optional(),
4838
- satisfaction_score: z.number().optional()
4839
- });
4840
- var traceOutputSchema = z.object({
4841
- value: z.string(),
4842
- embeddings: z.object({
4843
- model: z.string(),
4844
- embeddings: z.array(z.number())
4845
- }).optional()
4846
- });
4847
- var traceSchema = z.object({
4848
- trace_id: z.string(),
4849
- project_id: z.string(),
4850
- metadata: z.object({
4851
- thread_id: z.string().optional(),
4852
- user_id: z.string().optional(),
4853
- customer_id: z.string().optional(),
4854
- labels: z.array(z.string()).optional(),
4855
- topic_id: z.string().optional(),
4856
- subtopic_id: z.string().optional()
4857
- }),
4858
- timestamps: z.object({
4859
- started_at: z.number(),
4860
- inserted_at: z.number(),
4861
- updated_at: z.number()
4862
- }),
4863
- input: traceInputSchema,
4864
- output: traceOutputSchema.optional(),
4865
- metrics: z.object({
4866
- first_token_ms: z.number().optional().nullable(),
4867
- total_time_ms: z.number().optional().nullable(),
4868
- prompt_tokens: z.number().optional().nullable(),
4869
- completion_tokens: z.number().optional().nullable(),
4870
- total_cost: z.number().optional().nullable(),
4871
- tokens_estimated: z.boolean().optional().nullable()
4872
- }),
4873
- error: errorCaptureSchema.optional().nullable(),
4874
- indexing_md5s: z.array(z.string()).optional()
4875
- });
4876
- var elasticSearchTraceSchema = traceSchema.and(
4877
- z.object({
4878
- timestamps: traceSchema.shape.timestamps.and(
4879
- z.object({
4880
- updated_at: z.number()
4881
- })
4882
- )
4883
- })
4884
- );
4885
- var traceCheckSchema = z.object({
4886
- trace_id: z.string(),
4887
- check_id: z.string(),
4888
- project_id: z.string(),
4889
- check_type: z.string(),
4890
- check_name: z.string(),
4891
- is_guardrail: z.boolean(),
4892
- status: z.union([
4893
- z.literal("scheduled"),
4894
- z.literal("in_progress"),
4895
- z.literal("error"),
4896
- z.literal("skipped"),
4897
- z.literal("processed")
4898
- ]),
4899
- passed: z.boolean().optional(),
4900
- score: z.number().optional(),
4901
- details: z.string().optional(),
4902
- error: errorCaptureSchema.optional().nullable(),
4903
- retries: z.number().optional(),
4904
- timestamps: z.object({
4905
- inserted_at: z.number().optional(),
4906
- started_at: z.number().optional(),
4907
- finished_at: z.number().optional(),
4908
- updated_at: z.number()
4909
- }),
4910
- trace_metadata: z.object({
4911
- thread_id: z.string().optional(),
4912
- user_id: z.string().optional(),
4913
- customer_id: z.string().optional(),
4914
- labels: z.array(z.string()).optional(),
4915
- topics: z.array(z.string()).optional()
4916
- })
4917
- });
4918
- var experimentSchema = z.object({
4919
- experiment_id: z.string(),
4920
- variant: z.number()
4921
- });
4922
- var eventSchema = z.object({
4923
- event_id: z.string(),
4924
- event_type: z.string(),
4925
- project_id: z.string(),
4926
- metrics: z.record(z.number()),
4927
- event_details: z.record(z.string()),
4928
- trace_id: z.string().optional(),
4929
- trace_metadata: z.object({
4930
- thread_id: z.string().optional(),
4931
- user_id: z.string().optional(),
4932
- customer_id: z.string().optional(),
4933
- labels: z.array(z.string()).optional(),
4934
- topics: z.array(z.string()).optional()
4935
- }),
4936
- timestamps: z.object({
4937
- started_at: z.number(),
4938
- inserted_at: z.number(),
4939
- updated_at: z.number()
4940
- })
4941
- });
4942
- var elasticSearchEventSchema = eventSchema.omit({ metrics: true, event_details: true }).and(
4943
- z.object({
4944
- metrics: z.array(
4945
- z.object({
4946
- key: z.string(),
4947
- value: z.number()
4948
- })
4949
- ),
4950
- event_details: z.array(
4951
- z.object({
4952
- key: z.string(),
4953
- value: z.string()
4954
- })
4955
- )
4956
- })
4957
- );
4958
- var trackEventRESTParamsValidatorSchema = eventSchema.omit({
4959
- event_id: true,
4960
- project_id: true,
4961
- timestamps: true,
4962
- event_details: true,
4963
- trace_metadata: true
4964
- }).and(
4965
- z.object({
4966
- event_id: z.string().optional(),
4967
- event_details: z.record(z.string()).optional(),
4968
- timestamp: z.number().optional()
4969
- })
4970
- );
4971
- var chatMessageSchema = z.object({
4972
- role: chatRoleSchema.optional(),
4973
- content: z.union([z.string(), z.array(chatRichContentSchema)]).optional().nullable(),
4974
- function_call: functionCallSchema.optional().nullable(),
4975
- tool_calls: z.array(toolCallSchema).optional().nullable(),
4976
- tool_call_id: z.string().optional().nullable()
4977
- });
4978
- var typedValueChatMessagesSchema = z.object({
4979
- type: z.literal("chat_messages"),
4980
- value: z.array(chatMessageSchema)
4981
- });
4982
- var spanInputOutputSchema = z.lazy(
4983
- () => z.union([
4984
- typedValueTextSchema,
4985
- typedValueChatMessagesSchema,
4986
- typedValueGuardrailResultSchema,
4987
- typedValueJsonSchema,
4988
- typedValueRawSchema,
4989
- z.object({
4990
- type: z.literal("list"),
4991
- value: z.array(spanInputOutputSchema)
4992
- })
4993
- ])
4994
- );
4995
- var baseSpanSchema = z.object({
4996
- span_id: z.string(),
4997
- parent_id: z.string().optional().nullable(),
4998
- trace_id: z.string(),
4999
- type: spanTypesSchema,
5000
- name: z.string().optional().nullable(),
5001
- input: spanInputOutputSchema.optional().nullable(),
5002
- output: spanInputOutputSchema.optional().nullable(),
5003
- error: errorCaptureSchema.optional().nullable(),
5004
- timestamps: spanTimestampsSchema,
5005
- metrics: spanMetricsSchema.optional().nullable()
5006
- });
5007
- var lLMSpanSchema = baseSpanSchema.extend({
5008
- type: z.literal("llm"),
5009
- vendor: z.string().optional().nullable(),
5010
- model: z.string().optional(),
5011
- params: spanParamsSchema.optional()
5012
- });
5013
- var rAGSpanSchema = baseSpanSchema.extend({
5014
- type: z.literal("rag"),
5015
- contexts: z.array(rAGChunkSchema)
5016
- });
5017
- var spanSchema = z.union([
5018
- lLMSpanSchema,
5019
- rAGSpanSchema,
5020
- baseSpanSchema
5021
- ]);
5022
- var spanInputOutputValidatorSchema = spanInputOutputSchema.and(
5023
- z.object({
5024
- value: z.any()
5025
- })
5026
- );
5027
- var spanValidatorSchema = z.union([
5028
- lLMSpanSchema.omit({ input: true, output: true }),
5029
- rAGSpanSchema.omit({ input: true, output: true }),
5030
- baseSpanSchema.omit({ input: true, output: true })
5031
- ]).and(
5032
- z.object({
5033
- input: spanInputOutputValidatorSchema.optional().nullable(),
5034
- output: spanInputOutputValidatorSchema.optional().nullable()
5035
- })
5036
- );
5037
- var collectorRESTParamsSchema = z.object({
5038
- trace_id: z.union([z.string(), z.undefined()]).optional().nullable(),
5039
- spans: z.array(spanSchema),
5040
- metadata: z.object({
5041
- user_id: z.union([z.string(), z.undefined()]).optional().nullable(),
5042
- thread_id: z.union([z.string(), z.undefined()]).optional().nullable(),
5043
- customer_id: z.union([z.string(), z.undefined()]).optional().nullable(),
5044
- labels: z.union([z.array(z.string()), z.undefined()]).optional().nullable(),
5045
- experiments: z.union([z.array(experimentSchema), z.undefined()]).optional().nullable()
5046
- }).optional()
5047
- });
5048
- var collectorRESTParamsValidatorSchema = collectorRESTParamsSchema.omit({ spans: true });
5049
- var datasetSpanSchema = z.union([
5050
- baseSpanSchema.omit({
5051
- project_id: true,
5052
- trace_id: true,
5053
- id: true,
5054
- timestamps: true,
5055
- metrics: true
5056
- }),
5057
- lLMSpanSchema.omit({
5058
- project_id: true,
5059
- trace_id: true,
5060
- id: true,
5061
- timestamps: true,
5062
- metrics: true
5063
- }),
5064
- rAGSpanSchema.omit({
5065
- project_id: true,
5066
- trace_id: true,
5067
- id: true,
5068
- timestamps: true,
5069
- metrics: true
5070
- })
5071
- ]);
5072
-
5073
- // node_modules/@ai-sdk/provider-utils/node_modules/nanoid/non-secure/index.js
5074
- var customAlphabet = (alphabet, defaultSize = 21) => {
5075
- return (size = defaultSize) => {
5076
- let id = "";
5077
- let i = size;
5078
- while (i--) {
5079
- id += alphabet[Math.random() * alphabet.length | 0];
5080
- }
5081
- return id;
5082
- };
5083
- };
5084
-
5085
- // node_modules/@ai-sdk/provider-utils/dist/index.mjs
5086
- var import_secure_json_parse = __toESM(require_secure_json_parse(), 1);
5087
- var generateId = customAlphabet(
5088
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
5089
- 7
5090
- );
5091
- function convertUint8ArrayToBase64(array) {
5092
- let latin1string = "";
5093
- for (let i = 0; i < array.length; i++) {
5094
- latin1string += String.fromCodePoint(array[i]);
5095
- }
5096
- return globalThis.btoa(latin1string);
5097
- }
5098
-
5099
- // src/utils.ts
5100
- var convertImageToUrl = (image, mimeType) => {
5101
- try {
5102
- return image instanceof URL ? image.toString() : typeof image === "string" ? image : `data:${mimeType ?? "image/jpeg"};base64,${convertUint8ArrayToBase64(
5103
- image
5104
- )}`;
5105
- } catch (e) {
5106
- console.error("[LangWatch] error converting vercel ui image to url:", e);
5107
- return "";
5108
- }
5109
- };
5110
- function convertFromVercelAIMessages(messages) {
5111
- const lwMessages = [];
5112
- for (const { role, content } of messages) {
5113
- switch (role) {
5114
- case "system": {
5115
- lwMessages.push({ role: "system", content });
5116
- break;
5117
- }
5118
- case "user": {
5119
- if (Array.isArray(content) && content.length === 1 && content[0]?.type === "text") {
5120
- lwMessages.push({ role: "user", content: content[0].text });
5121
- break;
5122
- }
5123
- lwMessages.push({
5124
- role: "user",
5125
- content: Array.isArray(content) ? content.map((part) => {
5126
- switch (part.type) {
5127
- case "text": {
5128
- return { type: "text", text: part.text };
5129
- }
5130
- case "image": {
5131
- return {
5132
- type: "image_url",
5133
- image_url: {
5134
- url: convertImageToUrl(part.image, part.mimeType)
5135
- }
5136
- };
5137
- }
5138
- }
5139
- }) : content
5140
- });
5141
- break;
5142
- }
5143
- case "assistant": {
5144
- let text = "";
5145
- const toolCalls = [];
5146
- if (Array.isArray(content)) {
5147
- for (const part of content) {
5148
- switch (part.type) {
5149
- case "text": {
5150
- text += part.text;
5151
- break;
5152
- }
5153
- case "tool-call": {
5154
- toolCalls.push({
5155
- id: part.toolCallId,
5156
- type: "function",
5157
- function: {
5158
- name: part.toolName,
5159
- arguments: JSON.stringify(part.args)
5160
- }
5161
- });
5162
- break;
5163
- }
5164
- default: {
5165
- const _exhaustiveCheck = part;
5166
- throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
5167
- }
5168
- }
5169
- }
5170
- } else {
5171
- text = content;
5172
- }
5173
- lwMessages.push({
5174
- role: "assistant",
5175
- content: text,
5176
- tool_calls: toolCalls.length > 0 ? toolCalls : void 0
5177
- });
5178
- break;
5179
- }
5180
- case "tool": {
5181
- for (const toolResponse of content) {
5182
- lwMessages.push({
5183
- role: "tool",
5184
- tool_call_id: toolResponse.toolCallId,
5185
- content: JSON.stringify(toolResponse.result)
5186
- });
5187
- }
5188
- break;
5189
- }
5190
- default: {
5191
- const _exhaustiveCheck = role;
5192
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
5193
- }
5194
- }
5195
- }
5196
- return lwMessages;
5197
- }
5198
- var captureError = (error) => {
5199
- if (error && typeof error === "object" && "has_error" in error && "message" in error && "stacktrace" in error) {
5200
- return error;
5201
- } else if (error instanceof Error) {
5202
- return {
5203
- has_error: true,
5204
- message: error.message,
5205
- stacktrace: error.stack ? error.stack.split("\n") : []
5206
- };
5207
- } else if (typeof error === "object" && error !== null) {
5208
- const err = error;
5209
- const message = typeof err.message === "string" ? err.message : "An unknown error occurred";
5210
- const stacktrace = typeof err.stack === "string" ? err.stack.split("\n") : Array.isArray(err.stack) && err.stack.length > 0 && typeof err.stack[0] === "string" ? err.stack : ["No stack trace available"];
5211
- return {
5212
- has_error: true,
5213
- message,
5214
- stacktrace
5215
- };
5216
- } else {
5217
- return {
5218
- has_error: true,
5219
- message: String(error),
5220
- stacktrace: []
5221
- };
5222
- }
5223
- };
5224
- var autoconvertTypedValues = (value) => {
5225
- if (typeof value === "string") {
5226
- return { type: "text", value };
5227
- }
5228
- const chatMessages = z.array(chatMessageSchema).safeParse(value);
5229
- if (Array.isArray(value) && chatMessages.success) {
5230
- return {
5231
- type: "chat_messages",
5232
- value: chatMessages.data
5233
- };
5234
- }
5235
- try {
5236
- JSON.stringify(value);
5237
- return { type: "json", value };
5238
- } catch (e) {
5239
- return { type: "raw", value };
5240
- }
5241
- };
4735
+ };
4736
+ var optionalCreateSpan = ({
4737
+ trace,
4738
+ span,
4739
+ name,
4740
+ type
4741
+ }) => {
4742
+ if (span) {
4743
+ return span.startSpan({ name, type });
4744
+ } else if (trace) {
4745
+ return trace.startSpan({ name, type });
4746
+ }
4747
+ return void 0;
4748
+ };
4749
+ var prepareData = (params) => {
4750
+ const data = {};
4751
+ if (params.input) data.input = params.input;
4752
+ if (params.output) data.output = params.output;
4753
+ if (params.expectedOutput) data.expected_output = params.expectedOutput;
4754
+ if (params.contexts && params.contexts.length > 0)
4755
+ data.contexts = params.contexts;
4756
+ if (params.conversation && params.conversation.length > 0)
4757
+ data.conversation = params.conversation;
4758
+ if (params.span) {
4759
+ params.span.update({
4760
+ input: { type: "json", value: data },
4761
+ params: params.settings
4762
+ });
4763
+ }
4764
+ return {
4765
+ url: `${process.env.LANGWATCH_ENDPOINT}/api/evaluations/${params.slug}/evaluate`,
4766
+ json: {
4767
+ trace_id: params.traceId,
4768
+ span_id: params.spanId,
4769
+ name: params.name,
4770
+ data,
4771
+ settings: params.settings,
4772
+ as_guardrail: params.asGuardrail
4773
+ },
4774
+ headers: {
4775
+ "X-Auth-Token": process.env.LANGWATCH_API_KEY ?? "",
4776
+ "Content-Type": "application/json"
4777
+ }
4778
+ };
4779
+ };
4780
+ var handleResponse = (response, span, asGuardrail = false) => {
4781
+ if (response.status === "error") {
4782
+ response.details = response.details ?? "";
4783
+ }
4784
+ for (const key of Object.keys(response)) {
4785
+ if (response[key] === null || response[key] === void 0) {
4786
+ delete response[key];
4787
+ }
4788
+ }
4789
+ if (span) {
4790
+ const output = asGuardrail ? {
4791
+ type: "guardrail_result",
4792
+ value: response
4793
+ } : {
4794
+ type: "evaluation_result",
4795
+ value: response
4796
+ };
4797
+ span.update({ output });
4798
+ if (response.cost) {
4799
+ span.update({
4800
+ metrics: {
4801
+ cost: response.cost.amount
4802
+ }
4803
+ });
4804
+ }
4805
+ span.end();
4806
+ }
4807
+ return response;
4808
+ };
4809
+ var handleException = (e, span, asGuardrail = false) => {
4810
+ const response = {
4811
+ status: "error",
4812
+ details: e.toString()
4813
+ };
4814
+ if (asGuardrail) {
4815
+ response.passed = true;
4816
+ }
4817
+ return handleResponse(response, span, asGuardrail);
4818
+ };
5242
4819
 
5243
4820
  // node_modules/uuid/dist/esm-node/rng.js
5244
4821
  var import_crypto = __toESM(require("crypto"));
@@ -5928,526 +5505,1136 @@ var AIMessage = class extends BaseMessage {
5928
5505
  writable: true,
5929
5506
  value: void 0
5930
5507
  });
5931
- if (typeof initParams !== "string") {
5932
- this.tool_calls = initParams.tool_calls ?? this.tool_calls;
5933
- this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls;
5934
- }
5935
- this.usage_metadata = initParams.usage_metadata;
5508
+ if (typeof initParams !== "string") {
5509
+ this.tool_calls = initParams.tool_calls ?? this.tool_calls;
5510
+ this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls;
5511
+ }
5512
+ this.usage_metadata = initParams.usage_metadata;
5513
+ }
5514
+ static lc_name() {
5515
+ return "AIMessage";
5516
+ }
5517
+ _getType() {
5518
+ return "ai";
5519
+ }
5520
+ };
5521
+ var AIMessageChunk = class _AIMessageChunk extends BaseMessageChunk {
5522
+ constructor(fields) {
5523
+ let initParams;
5524
+ if (typeof fields === "string") {
5525
+ initParams = {
5526
+ content: fields,
5527
+ tool_calls: [],
5528
+ invalid_tool_calls: [],
5529
+ tool_call_chunks: []
5530
+ };
5531
+ } else if (fields.tool_call_chunks === void 0) {
5532
+ initParams = {
5533
+ ...fields,
5534
+ tool_calls: [],
5535
+ invalid_tool_calls: [],
5536
+ tool_call_chunks: []
5537
+ };
5538
+ } else {
5539
+ const toolCalls = [];
5540
+ const invalidToolCalls = [];
5541
+ for (const toolCallChunk of fields.tool_call_chunks) {
5542
+ let parsedArgs = {};
5543
+ try {
5544
+ parsedArgs = parsePartialJson(toolCallChunk.args ?? "{}") ?? {};
5545
+ if (typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) {
5546
+ throw new Error("Malformed tool call chunk args.");
5547
+ }
5548
+ toolCalls.push({
5549
+ name: toolCallChunk.name ?? "",
5550
+ args: parsedArgs,
5551
+ id: toolCallChunk.id
5552
+ });
5553
+ } catch (e) {
5554
+ invalidToolCalls.push({
5555
+ name: toolCallChunk.name,
5556
+ args: toolCallChunk.args,
5557
+ id: toolCallChunk.id,
5558
+ error: "Malformed args."
5559
+ });
5560
+ }
5561
+ }
5562
+ initParams = {
5563
+ ...fields,
5564
+ tool_calls: toolCalls,
5565
+ invalid_tool_calls: invalidToolCalls
5566
+ };
5567
+ }
5568
+ super(initParams);
5569
+ Object.defineProperty(this, "tool_calls", {
5570
+ enumerable: true,
5571
+ configurable: true,
5572
+ writable: true,
5573
+ value: []
5574
+ });
5575
+ Object.defineProperty(this, "invalid_tool_calls", {
5576
+ enumerable: true,
5577
+ configurable: true,
5578
+ writable: true,
5579
+ value: []
5580
+ });
5581
+ Object.defineProperty(this, "tool_call_chunks", {
5582
+ enumerable: true,
5583
+ configurable: true,
5584
+ writable: true,
5585
+ value: []
5586
+ });
5587
+ Object.defineProperty(this, "usage_metadata", {
5588
+ enumerable: true,
5589
+ configurable: true,
5590
+ writable: true,
5591
+ value: void 0
5592
+ });
5593
+ this.tool_call_chunks = initParams.tool_call_chunks ?? this.tool_call_chunks;
5594
+ this.tool_calls = initParams.tool_calls ?? this.tool_calls;
5595
+ this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls;
5596
+ this.usage_metadata = initParams.usage_metadata;
5597
+ }
5598
+ get lc_aliases() {
5599
+ return {
5600
+ ...super.lc_aliases,
5601
+ tool_calls: "tool_calls",
5602
+ invalid_tool_calls: "invalid_tool_calls",
5603
+ tool_call_chunks: "tool_call_chunks"
5604
+ };
5605
+ }
5606
+ static lc_name() {
5607
+ return "AIMessageChunk";
5608
+ }
5609
+ _getType() {
5610
+ return "ai";
5611
+ }
5612
+ concat(chunk) {
5613
+ const combinedFields = {
5614
+ content: mergeContent(this.content, chunk.content),
5615
+ additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
5616
+ response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),
5617
+ tool_call_chunks: []
5618
+ };
5619
+ if (this.tool_call_chunks !== void 0 || chunk.tool_call_chunks !== void 0) {
5620
+ const rawToolCalls = _mergeLists(this.tool_call_chunks, chunk.tool_call_chunks);
5621
+ if (rawToolCalls !== void 0 && rawToolCalls.length > 0) {
5622
+ combinedFields.tool_call_chunks = rawToolCalls;
5623
+ }
5624
+ }
5625
+ if (this.usage_metadata !== void 0 || chunk.usage_metadata !== void 0) {
5626
+ const left = this.usage_metadata ?? {
5627
+ input_tokens: 0,
5628
+ output_tokens: 0,
5629
+ total_tokens: 0
5630
+ };
5631
+ const right = chunk.usage_metadata ?? {
5632
+ input_tokens: 0,
5633
+ output_tokens: 0,
5634
+ total_tokens: 0
5635
+ };
5636
+ const usage_metadata = {
5637
+ input_tokens: left.input_tokens + right.input_tokens,
5638
+ output_tokens: left.output_tokens + right.output_tokens,
5639
+ total_tokens: left.total_tokens + right.total_tokens
5640
+ };
5641
+ combinedFields.usage_metadata = usage_metadata;
5642
+ }
5643
+ return new _AIMessageChunk(combinedFields);
5644
+ }
5645
+ };
5646
+
5647
+ // node_modules/@langchain/core/dist/messages/function.js
5648
+ var FunctionMessage = class extends BaseMessage {
5649
+ static lc_name() {
5650
+ return "FunctionMessage";
5651
+ }
5652
+ constructor(fields, name) {
5653
+ if (typeof fields === "string") {
5654
+ fields = { content: fields, name };
5655
+ }
5656
+ super(fields);
5657
+ }
5658
+ _getType() {
5659
+ return "function";
5660
+ }
5661
+ };
5662
+ var FunctionMessageChunk = class _FunctionMessageChunk extends BaseMessageChunk {
5663
+ static lc_name() {
5664
+ return "FunctionMessageChunk";
5665
+ }
5666
+ _getType() {
5667
+ return "function";
5668
+ }
5669
+ concat(chunk) {
5670
+ return new _FunctionMessageChunk({
5671
+ content: mergeContent(this.content, chunk.content),
5672
+ additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
5673
+ response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),
5674
+ name: this.name ?? ""
5675
+ });
5676
+ }
5677
+ };
5678
+
5679
+ // node_modules/@langchain/core/dist/messages/human.js
5680
+ var HumanMessage = class extends BaseMessage {
5681
+ static lc_name() {
5682
+ return "HumanMessage";
5683
+ }
5684
+ _getType() {
5685
+ return "human";
5686
+ }
5687
+ };
5688
+ var HumanMessageChunk = class _HumanMessageChunk extends BaseMessageChunk {
5689
+ static lc_name() {
5690
+ return "HumanMessageChunk";
5691
+ }
5692
+ _getType() {
5693
+ return "human";
5694
+ }
5695
+ concat(chunk) {
5696
+ return new _HumanMessageChunk({
5697
+ content: mergeContent(this.content, chunk.content),
5698
+ additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
5699
+ response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata)
5700
+ });
5936
5701
  }
5702
+ };
5703
+
5704
+ // node_modules/@langchain/core/dist/messages/system.js
5705
+ var SystemMessage = class extends BaseMessage {
5937
5706
  static lc_name() {
5938
- return "AIMessage";
5707
+ return "SystemMessage";
5939
5708
  }
5940
5709
  _getType() {
5941
- return "ai";
5710
+ return "system";
5942
5711
  }
5943
5712
  };
5944
- var AIMessageChunk = class _AIMessageChunk extends BaseMessageChunk {
5945
- constructor(fields) {
5946
- let initParams;
5947
- if (typeof fields === "string") {
5948
- initParams = {
5949
- content: fields,
5950
- tool_calls: [],
5951
- invalid_tool_calls: [],
5952
- tool_call_chunks: []
5953
- };
5954
- } else if (fields.tool_call_chunks === void 0) {
5955
- initParams = {
5956
- ...fields,
5957
- tool_calls: [],
5958
- invalid_tool_calls: [],
5959
- tool_call_chunks: []
5960
- };
5961
- } else {
5962
- const toolCalls = [];
5963
- const invalidToolCalls = [];
5964
- for (const toolCallChunk of fields.tool_call_chunks) {
5965
- let parsedArgs = {};
5966
- try {
5967
- parsedArgs = parsePartialJson(toolCallChunk.args ?? "{}") ?? {};
5968
- if (typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) {
5969
- throw new Error("Malformed tool call chunk args.");
5713
+ var SystemMessageChunk = class _SystemMessageChunk extends BaseMessageChunk {
5714
+ static lc_name() {
5715
+ return "SystemMessageChunk";
5716
+ }
5717
+ _getType() {
5718
+ return "system";
5719
+ }
5720
+ concat(chunk) {
5721
+ return new _SystemMessageChunk({
5722
+ content: mergeContent(this.content, chunk.content),
5723
+ additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
5724
+ response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata)
5725
+ });
5726
+ }
5727
+ };
5728
+
5729
+ // node_modules/@langchain/core/dist/messages/utils.js
5730
+ function mapChatMessagesToStoredMessages(messages) {
5731
+ return messages.map((message) => message.toDict());
5732
+ }
5733
+
5734
+ // src/langchain.ts
5735
+ var import_javascript_stringify = __toESM(require_dist());
5736
+ var LangWatchCallbackHandler = class extends BaseCallbackHandler {
5737
+ constructor({ trace }) {
5738
+ super();
5739
+ this.name = "LangWatchCallbackHandler";
5740
+ this.spans = {};
5741
+ this.trace = trace;
5742
+ }
5743
+ async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, _tags, metadata, name) {
5744
+ this.spans[runId] = this.buildLLMSpan({
5745
+ llm,
5746
+ runId,
5747
+ parentRunId,
5748
+ input: {
5749
+ type: "json",
5750
+ value: prompts
5751
+ },
5752
+ extraParams,
5753
+ metadata,
5754
+ name
5755
+ });
5756
+ }
5757
+ buildLLMSpan({
5758
+ llm,
5759
+ runId,
5760
+ parentRunId,
5761
+ input,
5762
+ extraParams,
5763
+ metadata,
5764
+ name
5765
+ }) {
5766
+ try {
5767
+ const parent = this.getParent(parentRunId);
5768
+ const vendor = metadata?.ls_provider ?? llm.id.at(-2)?.toString();
5769
+ const model = metadata?.ls_model_name ?? llm.kwargs?.model ?? "unknown";
5770
+ const span = parent.startLLMSpan({
5771
+ spanId: runId,
5772
+ name: name ?? llm.id.at(-1)?.toString(),
5773
+ input,
5774
+ model: [vendor, model].filter((x) => x).join("/"),
5775
+ params: {
5776
+ temperature: extraParams?.invocation_params?.temperature,
5777
+ ...extraParams?.invocation_params?.functions ? { functions: extraParams?.invocation_params?.functions } : {}
5778
+ }
5779
+ });
5780
+ return span;
5781
+ } catch (e) {
5782
+ this.trace.client.emit("error", e);
5783
+ throw e;
5784
+ }
5785
+ }
5786
+ async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) {
5787
+ this.spans[runId] = this.buildLLMSpan({
5788
+ name,
5789
+ llm,
5790
+ runId,
5791
+ parentRunId,
5792
+ input: {
5793
+ type: "chat_messages",
5794
+ value: messages.flatMap(convertFromLangChainMessages)
5795
+ },
5796
+ extraParams,
5797
+ metadata
5798
+ });
5799
+ }
5800
+ async handleNewToken(_token, runId) {
5801
+ const span = this.spans[runId];
5802
+ if (runId && span && !span.timestamps.firstTokenAt) {
5803
+ span.update({
5804
+ timestamps: { ...span.timestamps, firstTokenAt: Date.now() }
5805
+ });
5806
+ }
5807
+ }
5808
+ async handleLLMEnd(response, runId, _parentRunId) {
5809
+ try {
5810
+ const span = this.spans[runId];
5811
+ if (!span) {
5812
+ return;
5813
+ }
5814
+ const outputs = [];
5815
+ for (const generation of response.generations) {
5816
+ for (const generation_ of generation) {
5817
+ if ("message" in generation_) {
5818
+ outputs.push({
5819
+ type: "chat_messages",
5820
+ value: convertFromLangChainMessages([
5821
+ generation_.message
5822
+ ])
5823
+ });
5824
+ } else if ("text" in generation_) {
5825
+ outputs.push({
5826
+ type: "text",
5827
+ value: generation_.text
5828
+ });
5829
+ } else {
5830
+ outputs.push({
5831
+ type: "text",
5832
+ value: JSON.stringify(generation_)
5833
+ });
5970
5834
  }
5971
- toolCalls.push({
5972
- name: toolCallChunk.name ?? "",
5973
- args: parsedArgs,
5974
- id: toolCallChunk.id
5975
- });
5976
- } catch (e) {
5977
- invalidToolCalls.push({
5978
- name: toolCallChunk.name,
5979
- args: toolCallChunk.args,
5980
- id: toolCallChunk.id,
5981
- error: "Malformed args."
5982
- });
5983
5835
  }
5984
5836
  }
5985
- initParams = {
5986
- ...fields,
5987
- tool_calls: toolCalls,
5988
- invalid_tool_calls: invalidToolCalls
5989
- };
5837
+ const output = outputs.length === 1 ? outputs[0] : { type: "list", value: outputs };
5838
+ span.end({
5839
+ output
5840
+ // ...(metrics ? { metrics } : {}),
5841
+ });
5842
+ } catch (e) {
5843
+ this.trace.client.emit("error", e);
5844
+ throw e;
5990
5845
  }
5991
- super(initParams);
5992
- Object.defineProperty(this, "tool_calls", {
5993
- enumerable: true,
5994
- configurable: true,
5995
- writable: true,
5996
- value: []
5997
- });
5998
- Object.defineProperty(this, "invalid_tool_calls", {
5999
- enumerable: true,
6000
- configurable: true,
6001
- writable: true,
6002
- value: []
5846
+ }
5847
+ async handleLLMError(err, runId, _parentRunId) {
5848
+ this.errorSpan({ runId, error: err });
5849
+ }
5850
+ async handleChainStart(chain, inputs, runId, parentRunId, _tags, _metadata, _runType, name) {
5851
+ this.spans[runId] = this.buildSpan({
5852
+ type: "chain",
5853
+ serialized: chain,
5854
+ runId,
5855
+ parentRunId,
5856
+ input: inputs,
5857
+ name
6003
5858
  });
6004
- Object.defineProperty(this, "tool_call_chunks", {
6005
- enumerable: true,
6006
- configurable: true,
6007
- writable: true,
6008
- value: []
5859
+ }
5860
+ async handleChainEnd(output, runId, _parentRunId) {
5861
+ this.endSpan({
5862
+ runId,
5863
+ output
6009
5864
  });
6010
- Object.defineProperty(this, "usage_metadata", {
6011
- enumerable: true,
6012
- configurable: true,
6013
- writable: true,
6014
- value: void 0
5865
+ }
5866
+ async handleChainError(err, runId, _parentRunId, _tags, _kwargs) {
5867
+ this.errorSpan({ runId, error: err });
5868
+ }
5869
+ async handleToolStart(tool, input, runId, parentRunId, _tags, _metadata, name) {
5870
+ this.spans[runId] = this.buildSpan({
5871
+ type: "tool",
5872
+ serialized: tool,
5873
+ runId,
5874
+ parentRunId,
5875
+ input,
5876
+ name
6015
5877
  });
6016
- this.tool_call_chunks = initParams.tool_call_chunks ?? this.tool_call_chunks;
6017
- this.tool_calls = initParams.tool_calls ?? this.tool_calls;
6018
- this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls;
6019
- this.usage_metadata = initParams.usage_metadata;
6020
5878
  }
6021
- get lc_aliases() {
6022
- return {
6023
- ...super.lc_aliases,
6024
- tool_calls: "tool_calls",
6025
- invalid_tool_calls: "invalid_tool_calls",
6026
- tool_call_chunks: "tool_call_chunks"
6027
- };
5879
+ async handleToolEnd(output, runId, _parentRunId) {
5880
+ this.endSpan({ runId, output });
6028
5881
  }
6029
- static lc_name() {
6030
- return "AIMessageChunk";
5882
+ async handleToolError(err, runId, _parentRunId, _tags) {
5883
+ this.errorSpan({ runId, error: err });
6031
5884
  }
6032
- _getType() {
6033
- return "ai";
5885
+ async handleRetrieverStart(retriever, query, runId, parentRunId, _tags, _metadata, name) {
5886
+ try {
5887
+ const parent = this.getParent(parentRunId);
5888
+ this.spans[runId] = parent.startRAGSpan({
5889
+ spanId: runId,
5890
+ name: name ?? retriever.name ?? retriever.id.at(-1)?.toString(),
5891
+ input: this.autoconvertTypedValues(query)
5892
+ });
5893
+ } catch (e) {
5894
+ this.trace.client.emit("error", e);
5895
+ throw e;
5896
+ }
6034
5897
  }
6035
- concat(chunk) {
6036
- const combinedFields = {
6037
- content: mergeContent(this.content, chunk.content),
6038
- additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
6039
- response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),
6040
- tool_call_chunks: []
6041
- };
6042
- if (this.tool_call_chunks !== void 0 || chunk.tool_call_chunks !== void 0) {
6043
- const rawToolCalls = _mergeLists(this.tool_call_chunks, chunk.tool_call_chunks);
6044
- if (rawToolCalls !== void 0 && rawToolCalls.length > 0) {
6045
- combinedFields.tool_call_chunks = rawToolCalls;
5898
+ async handleRetrieverEnd(documents, runId, _parentRunId, _tags) {
5899
+ try {
5900
+ const contexts = documents.map((doc) => ({
5901
+ content: doc.pageContent,
5902
+ ...doc.metadata.source ? { documentId: doc.metadata.source } : {}
5903
+ }));
5904
+ const span = this.spans[runId];
5905
+ if (!span) {
5906
+ return;
6046
5907
  }
5908
+ span.end({
5909
+ contexts,
5910
+ output: this.autoconvertTypedValues(documents)
5911
+ });
5912
+ } catch (e) {
5913
+ this.trace.client.emit("error", e);
5914
+ throw e;
6047
5915
  }
6048
- if (this.usage_metadata !== void 0 || chunk.usage_metadata !== void 0) {
6049
- const left = this.usage_metadata ?? {
6050
- input_tokens: 0,
6051
- output_tokens: 0,
6052
- total_tokens: 0
6053
- };
6054
- const right = chunk.usage_metadata ?? {
6055
- input_tokens: 0,
6056
- output_tokens: 0,
6057
- total_tokens: 0
6058
- };
6059
- const usage_metadata = {
6060
- input_tokens: left.input_tokens + right.input_tokens,
6061
- output_tokens: left.output_tokens + right.output_tokens,
6062
- total_tokens: left.total_tokens + right.total_tokens
6063
- };
6064
- combinedFields.usage_metadata = usage_metadata;
6065
- }
6066
- return new _AIMessageChunk(combinedFields);
6067
5916
  }
6068
- };
6069
-
6070
- // node_modules/@langchain/core/dist/messages/function.js
6071
- var FunctionMessage = class extends BaseMessage {
6072
- static lc_name() {
6073
- return "FunctionMessage";
5917
+ async handleRetrieverError(err, runId, _parentRunId, _tags) {
5918
+ this.errorSpan({ runId, error: err });
6074
5919
  }
6075
- constructor(fields, name) {
6076
- if (typeof fields === "string") {
6077
- fields = { content: fields, name };
5920
+ async handleAgentAction(_action, runId, _parentRunId, _tags) {
5921
+ const span = this.spans[runId];
5922
+ if (!span) {
5923
+ return;
6078
5924
  }
6079
- super(fields);
6080
- }
6081
- _getType() {
6082
- return "function";
6083
- }
6084
- };
6085
- var FunctionMessageChunk = class _FunctionMessageChunk extends BaseMessageChunk {
6086
- static lc_name() {
6087
- return "FunctionMessageChunk";
6088
- }
6089
- _getType() {
6090
- return "function";
6091
- }
6092
- concat(chunk) {
6093
- return new _FunctionMessageChunk({
6094
- content: mergeContent(this.content, chunk.content),
6095
- additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
6096
- response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),
6097
- name: this.name ?? ""
5925
+ span.update({
5926
+ type: "agent"
6098
5927
  });
6099
5928
  }
6100
- };
6101
-
6102
- // node_modules/@langchain/core/dist/messages/human.js
6103
- var HumanMessage = class extends BaseMessage {
6104
- static lc_name() {
6105
- return "HumanMessage";
6106
- }
6107
- _getType() {
6108
- return "human";
5929
+ async handleAgentEnd(action, runId, _parentRunId, _tags) {
5930
+ this.endSpan({
5931
+ runId,
5932
+ output: action.returnValues
5933
+ });
6109
5934
  }
6110
- };
6111
- var HumanMessageChunk = class _HumanMessageChunk extends BaseMessageChunk {
6112
- static lc_name() {
6113
- return "HumanMessageChunk";
5935
+ buildSpan({
5936
+ type,
5937
+ serialized,
5938
+ runId,
5939
+ parentRunId,
5940
+ input,
5941
+ name
5942
+ }) {
5943
+ try {
5944
+ const parent = this.getParent(parentRunId);
5945
+ const span = parent.startSpan({
5946
+ spanId: runId,
5947
+ type,
5948
+ name: name ?? serialized.name ?? serialized.id.at(-1)?.toString(),
5949
+ input: this.autoconvertTypedValues(input)
5950
+ });
5951
+ return span;
5952
+ } catch (e) {
5953
+ this.trace.client.emit("error", e);
5954
+ throw e;
5955
+ }
6114
5956
  }
6115
- _getType() {
6116
- return "human";
5957
+ endSpan({ runId, output }) {
5958
+ try {
5959
+ const span = this.spans[runId];
5960
+ if (!span) {
5961
+ return;
5962
+ }
5963
+ span.end({
5964
+ output: this.autoconvertTypedValues(output)
5965
+ });
5966
+ } catch (e) {
5967
+ this.trace.client.emit("error", e);
5968
+ throw e;
5969
+ }
6117
5970
  }
6118
- concat(chunk) {
6119
- return new _HumanMessageChunk({
6120
- content: mergeContent(this.content, chunk.content),
6121
- additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
6122
- response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata)
5971
+ errorSpan({ runId, error }) {
5972
+ const span = this.spans[runId];
5973
+ if (!span) {
5974
+ return;
5975
+ }
5976
+ span.end({
5977
+ error
6123
5978
  });
6124
5979
  }
6125
- };
6126
-
6127
- // node_modules/@langchain/core/dist/messages/system.js
6128
- var SystemMessage = class extends BaseMessage {
6129
- static lc_name() {
6130
- return "SystemMessage";
5980
+ autoconvertTypedValues(value) {
5981
+ if (!value || typeof value === "object" && Object.keys(value).length === 0) {
5982
+ return void 0;
5983
+ }
5984
+ if (typeof value === "string") {
5985
+ return { type: "text", value };
5986
+ }
5987
+ try {
5988
+ JSON.stringify(value);
5989
+ return { type: "json", value };
5990
+ } catch (e) {
5991
+ return { type: "text", value: (0, import_javascript_stringify.stringify)(value) ?? value.toString() };
5992
+ }
6131
5993
  }
6132
- _getType() {
6133
- return "system";
5994
+ getParent(parentRunId) {
5995
+ return (parentRunId ? this.spans[parentRunId] : this.spans[Object.keys(this.spans).at(-1) ?? ""]) ?? this.trace;
6134
5996
  }
6135
5997
  };
6136
- var SystemMessageChunk = class _SystemMessageChunk extends BaseMessageChunk {
6137
- static lc_name() {
6138
- return "SystemMessageChunk";
6139
- }
6140
- _getType() {
6141
- return "system";
5998
+ var convertFromLangChainMessages = (messages) => {
5999
+ const chatMessages = [];
6000
+ for (const message of messages) {
6001
+ chatMessages.push(convertFromLangChainMessage(message));
6142
6002
  }
6143
- concat(chunk) {
6144
- return new _SystemMessageChunk({
6145
- content: mergeContent(this.content, chunk.content),
6146
- additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
6147
- response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata)
6148
- });
6003
+ return chatMessages;
6004
+ };
6005
+ var convertFromLangChainMessage = (message) => {
6006
+ let role = "user";
6007
+ const message_ = message.lc_serializable ? mapChatMessagesToStoredMessages([message])[0] : message;
6008
+ if (message_ instanceof HumanMessage || message_ instanceof HumanMessageChunk || message_.id?.at(-1) === "HumanMessage" || message_.id?.at(-1) === "HumanMessageChunk" || message_.type === "human") {
6009
+ role = "user";
6010
+ } else if (message instanceof AIMessage || message instanceof AIMessageChunk || message.id?.at(-1) === "AIMessage" || message.id?.at(-1) === "AIMessageChunk" || message_.type === "ai") {
6011
+ role = "assistant";
6012
+ } else if (message instanceof SystemMessage || message instanceof SystemMessageChunk || message.id?.at(-1) === "SystemMessage" || message.id?.at(-1) === "SystemMessageChunk" || message_.type === "system") {
6013
+ role = "system";
6014
+ } else if (message instanceof FunctionMessage || message instanceof FunctionMessageChunk || message.id?.at(-1) === "FunctionMessage" || message.id?.at(-1) === "FunctionMessageChunk" || message_.type === "function") {
6015
+ role = "function";
6016
+ } else if (message instanceof ToolMessage || message instanceof ToolMessageChunk || message.id?.at(-1) === "ToolMessage" || message.id?.at(-1) === "ToolMessageChunk" || message_.type === "tool") {
6017
+ role = "tool";
6149
6018
  }
6019
+ const content = typeof message.content === "string" ? message.content : message.content.map(
6020
+ (content2) => content2.type === "text" ? { type: "text", text: content2.text } : content2.type == "image_url" ? { type: "image_url", image_url: content2.image_url } : { type: "text", text: JSON.stringify(content2) }
6021
+ );
6022
+ const functionCall = message.additional_kwargs;
6023
+ return {
6024
+ role,
6025
+ content,
6026
+ ...functionCall && typeof functionCall === "object" && Object.keys(functionCall).length > 0 ? { function_call: functionCall } : {}
6027
+ };
6150
6028
  };
6151
6029
 
6152
- // node_modules/@langchain/core/dist/messages/utils.js
6153
- function mapChatMessagesToStoredMessages(messages) {
6154
- return messages.map((message) => message.toDict());
6030
+ // src/server/types/tracer.generated.ts
6031
+ var chatRoleSchema = z.union([
6032
+ z.literal("system"),
6033
+ z.literal("user"),
6034
+ z.literal("assistant"),
6035
+ z.literal("function"),
6036
+ z.literal("tool"),
6037
+ z.literal("unknown")
6038
+ ]);
6039
+ var functionCallSchema = z.object({
6040
+ name: z.string().optional(),
6041
+ arguments: z.string().optional()
6042
+ });
6043
+ var toolCallSchema = z.object({
6044
+ id: z.string(),
6045
+ type: z.string(),
6046
+ function: functionCallSchema
6047
+ });
6048
+ var rAGChunkSchema = z.object({
6049
+ document_id: z.string().optional().nullable(),
6050
+ chunk_id: z.string().optional().nullable(),
6051
+ content: z.union([z.string(), z.record(z.any()), z.array(z.any())])
6052
+ });
6053
+ var chatRichContentSchema = z.union([
6054
+ z.object({
6055
+ type: z.literal("text"),
6056
+ text: z.string().optional()
6057
+ }),
6058
+ z.object({
6059
+ type: z.literal("image_url"),
6060
+ image_url: z.object({
6061
+ url: z.string(),
6062
+ detail: z.union([z.literal("auto"), z.literal("low"), z.literal("high")]).optional()
6063
+ }).optional()
6064
+ })
6065
+ ]);
6066
+ var typedValueTextSchema = z.object({
6067
+ type: z.literal("text"),
6068
+ value: z.string()
6069
+ });
6070
+ var typedValueRawSchema = z.object({
6071
+ type: z.literal("raw"),
6072
+ value: z.string()
6073
+ });
6074
+ var jSONSerializableSchema = z.union([
6075
+ z.string(),
6076
+ z.number(),
6077
+ z.boolean(),
6078
+ z.record(z.any()),
6079
+ z.array(z.any())
6080
+ ]).nullable();
6081
+ var typedValueJsonSchema = z.object({
6082
+ type: z.literal("json"),
6083
+ value: jSONSerializableSchema
6084
+ });
6085
+ var moneySchema = z.object({
6086
+ currency: z.string(),
6087
+ amount: z.number()
6088
+ });
6089
+ var evaluationResultSchema = z.object({
6090
+ status: z.union([
6091
+ z.literal("processed"),
6092
+ z.literal("skipped"),
6093
+ z.literal("error")
6094
+ ]),
6095
+ passed: z.boolean().optional().nullable(),
6096
+ score: z.number().optional().nullable(),
6097
+ label: z.string().optional().nullable(),
6098
+ details: z.string().optional().nullable(),
6099
+ cost: moneySchema.optional().nullable()
6100
+ });
6101
+ var typedValueGuardrailResultSchema = z.object({
6102
+ type: z.literal("guardrail_result"),
6103
+ value: evaluationResultSchema
6104
+ });
6105
+ var typedValueEvaluationResultSchema = z.object({
6106
+ type: z.literal("evaluation_result"),
6107
+ value: evaluationResultSchema
6108
+ });
6109
+ var errorCaptureSchema = z.object({
6110
+ has_error: z.literal(true),
6111
+ message: z.string(),
6112
+ stacktrace: z.array(z.string())
6113
+ });
6114
+ var spanMetricsSchema = z.object({
6115
+ prompt_tokens: z.number().optional().nullable(),
6116
+ completion_tokens: z.number().optional().nullable(),
6117
+ tokens_estimated: z.boolean().optional().nullable(),
6118
+ cost: z.number().optional().nullable()
6119
+ });
6120
+ var reservedSpanParamsSchema = z.object({
6121
+ frequency_penalty: z.number().optional().nullable(),
6122
+ logit_bias: z.record(z.number()).optional().nullable(),
6123
+ logprobs: z.boolean().optional().nullable(),
6124
+ top_logprobs: z.number().optional().nullable(),
6125
+ max_tokens: z.number().optional().nullable(),
6126
+ n: z.number().optional().nullable(),
6127
+ presence_penalty: z.number().optional().nullable(),
6128
+ seed: z.number().optional().nullable(),
6129
+ stop: z.union([z.string(), z.array(z.string())]).optional().nullable(),
6130
+ stream: z.boolean().optional().nullable(),
6131
+ temperature: z.number().optional().nullable(),
6132
+ top_p: z.number().optional().nullable(),
6133
+ tools: z.array(z.record(z.any())).optional().nullable(),
6134
+ tool_choice: z.union([z.record(z.any()), z.string()]).optional().nullable(),
6135
+ parallel_tool_calls: z.boolean().optional().nullable(),
6136
+ functions: z.array(z.record(z.any())).optional().nullable(),
6137
+ user: z.string().optional().nullable()
6138
+ });
6139
+ var spanParamsSchema = reservedSpanParamsSchema.and(z.record(z.any()));
6140
+ var spanTimestampsSchema = z.object({
6141
+ started_at: z.number(),
6142
+ first_token_at: z.number().optional().nullable(),
6143
+ finished_at: z.number()
6144
+ });
6145
+ var spanTypesSchema = z.union([
6146
+ z.literal("span"),
6147
+ z.literal("llm"),
6148
+ z.literal("chain"),
6149
+ z.literal("tool"),
6150
+ z.literal("agent"),
6151
+ z.literal("rag"),
6152
+ z.literal("guardrail"),
6153
+ z.literal("evaluation"),
6154
+ z.literal("workflow"),
6155
+ z.literal("component"),
6156
+ z.literal("server"),
6157
+ z.literal("client"),
6158
+ z.literal("producer"),
6159
+ z.literal("consumer"),
6160
+ z.literal("task"),
6161
+ z.literal("unknown")
6162
+ ]);
6163
+ var traceInputSchema = z.object({
6164
+ value: z.string(),
6165
+ embeddings: z.object({
6166
+ model: z.string(),
6167
+ embeddings: z.array(z.number())
6168
+ }).optional(),
6169
+ satisfaction_score: z.number().optional()
6170
+ });
6171
+ var traceOutputSchema = z.object({
6172
+ value: z.string(),
6173
+ embeddings: z.object({
6174
+ model: z.string(),
6175
+ embeddings: z.array(z.number())
6176
+ }).optional()
6177
+ });
6178
+ var primitiveTypeSchema = z.union([z.string(), z.number(), z.boolean(), z.undefined()]).nullable();
6179
+ var reservedTraceMetadataSchema = z.object({
6180
+ thread_id: z.string().optional().nullable(),
6181
+ user_id: z.string().optional().nullable(),
6182
+ customer_id: z.string().optional().nullable(),
6183
+ labels: z.array(z.string()).optional().nullable(),
6184
+ topic_id: z.string().optional().nullable(),
6185
+ subtopic_id: z.string().optional().nullable(),
6186
+ sdk_version: z.string().optional().nullable(),
6187
+ sdk_language: z.string().optional().nullable()
6188
+ });
6189
+ var customMetadataSchema = z.record(
6190
+ z.union([
6191
+ primitiveTypeSchema,
6192
+ z.array(primitiveTypeSchema),
6193
+ z.record(primitiveTypeSchema),
6194
+ z.record(z.record(primitiveTypeSchema))
6195
+ ])
6196
+ );
6197
+ var traceMetadataSchema = reservedTraceMetadataSchema.and(customMetadataSchema);
6198
+ var eventSchema = z.object({
6199
+ event_id: z.string(),
6200
+ event_type: z.string(),
6201
+ project_id: z.string(),
6202
+ metrics: z.record(z.number()),
6203
+ event_details: z.record(z.string()),
6204
+ trace_id: z.string(),
6205
+ timestamps: z.object({
6206
+ started_at: z.number(),
6207
+ inserted_at: z.number(),
6208
+ updated_at: z.number()
6209
+ })
6210
+ });
6211
+ var elasticSearchEventSchema = eventSchema.omit({ metrics: true, event_details: true }).and(
6212
+ z.object({
6213
+ metrics: z.array(
6214
+ z.object({
6215
+ key: z.string(),
6216
+ value: z.number()
6217
+ })
6218
+ ),
6219
+ event_details: z.array(
6220
+ z.object({
6221
+ key: z.string(),
6222
+ value: z.string()
6223
+ })
6224
+ )
6225
+ })
6226
+ );
6227
+ var evaluationStatusSchema = z.union([
6228
+ z.literal("scheduled"),
6229
+ z.literal("in_progress"),
6230
+ z.literal("error"),
6231
+ z.literal("skipped"),
6232
+ z.literal("processed")
6233
+ ]);
6234
+ var trackEventRESTParamsValidatorSchema = eventSchema.omit({
6235
+ event_id: true,
6236
+ project_id: true,
6237
+ timestamps: true,
6238
+ event_details: true
6239
+ }).and(
6240
+ z.object({
6241
+ event_id: z.string().optional(),
6242
+ event_details: z.record(z.string()).optional(),
6243
+ timestamp: z.number().optional()
6244
+ })
6245
+ );
6246
+ var contextsSchema = z.object({
6247
+ traceId: z.string(),
6248
+ contexts: z.array(rAGChunkSchema)
6249
+ });
6250
+ var chatMessageSchema = z.object({
6251
+ role: chatRoleSchema.optional(),
6252
+ content: z.union([z.string(), z.array(chatRichContentSchema)]).optional().nullable(),
6253
+ function_call: functionCallSchema.optional().nullable(),
6254
+ tool_calls: z.array(toolCallSchema).optional().nullable(),
6255
+ tool_call_id: z.string().optional().nullable(),
6256
+ name: z.string().optional().nullable()
6257
+ });
6258
+ var typedValueChatMessagesSchema = z.object({
6259
+ type: z.literal("chat_messages"),
6260
+ value: z.array(chatMessageSchema)
6261
+ });
6262
+ var spanInputOutputSchema = z.lazy(
6263
+ () => z.union([
6264
+ typedValueTextSchema,
6265
+ typedValueChatMessagesSchema,
6266
+ typedValueGuardrailResultSchema,
6267
+ typedValueEvaluationResultSchema,
6268
+ typedValueJsonSchema,
6269
+ typedValueRawSchema,
6270
+ z.object({
6271
+ type: z.literal("list"),
6272
+ value: z.array(spanInputOutputSchema)
6273
+ })
6274
+ ])
6275
+ );
6276
+ var baseSpanSchema = z.object({
6277
+ span_id: z.string(),
6278
+ parent_id: z.string().optional().nullable(),
6279
+ trace_id: z.string(),
6280
+ type: spanTypesSchema,
6281
+ name: z.string().optional().nullable(),
6282
+ input: spanInputOutputSchema.optional().nullable(),
6283
+ output: spanInputOutputSchema.optional().nullable(),
6284
+ error: errorCaptureSchema.optional().nullable(),
6285
+ timestamps: spanTimestampsSchema,
6286
+ metrics: spanMetricsSchema.optional().nullable(),
6287
+ params: spanParamsSchema.optional().nullable()
6288
+ });
6289
+ var lLMSpanSchema = baseSpanSchema.extend({
6290
+ type: z.literal("llm"),
6291
+ vendor: z.string().optional().nullable(),
6292
+ model: z.string().optional().nullable()
6293
+ });
6294
+ var rAGSpanSchema = baseSpanSchema.extend({
6295
+ type: z.literal("rag"),
6296
+ contexts: z.array(rAGChunkSchema)
6297
+ });
6298
+ var spanSchema = z.union([
6299
+ lLMSpanSchema,
6300
+ rAGSpanSchema,
6301
+ baseSpanSchema
6302
+ ]);
6303
+ var spanInputOutputValidatorSchema = spanInputOutputSchema.and(
6304
+ z.object({
6305
+ value: z.any()
6306
+ })
6307
+ );
6308
+ var spanValidatorSchema = z.union([
6309
+ lLMSpanSchema.omit({ input: true, output: true, params: true }),
6310
+ rAGSpanSchema.omit({ input: true, output: true, params: true }),
6311
+ baseSpanSchema.omit({ input: true, output: true, params: true })
6312
+ ]).and(
6313
+ z.object({
6314
+ input: spanInputOutputValidatorSchema.optional().nullable(),
6315
+ output: spanInputOutputValidatorSchema.optional().nullable(),
6316
+ params: z.record(z.any()).optional().nullable()
6317
+ })
6318
+ );
6319
+ var evaluationSchema = z.object({
6320
+ evaluation_id: z.string(),
6321
+ evaluator_id: z.string(),
6322
+ span_id: z.string().optional().nullable(),
6323
+ name: z.string(),
6324
+ type: z.string().optional().nullable(),
6325
+ is_guardrail: z.boolean().optional().nullable(),
6326
+ status: evaluationStatusSchema,
6327
+ passed: z.boolean().optional().nullable(),
6328
+ score: z.number().optional().nullable(),
6329
+ label: z.string().optional().nullable(),
6330
+ details: z.string().optional().nullable(),
6331
+ error: errorCaptureSchema.optional().nullable(),
6332
+ retries: z.number().optional().nullable(),
6333
+ timestamps: z.object({
6334
+ inserted_at: z.number().optional().nullable(),
6335
+ started_at: z.number().optional().nullable(),
6336
+ finished_at: z.number().optional().nullable(),
6337
+ updated_at: z.number().optional().nullable()
6338
+ })
6339
+ });
6340
+ var rESTEvaluationSchema = evaluationSchema.omit({
6341
+ evaluation_id: true,
6342
+ evaluator_id: true,
6343
+ status: true,
6344
+ timestamps: true,
6345
+ retries: true
6346
+ }).and(
6347
+ z.object({
6348
+ evaluation_id: z.string().optional().nullable(),
6349
+ evaluator_id: z.string().optional().nullable(),
6350
+ status: z.union([
6351
+ z.literal("processed"),
6352
+ z.literal("skipped"),
6353
+ z.literal("error")
6354
+ ]).optional().nullable(),
6355
+ timestamps: z.object({
6356
+ started_at: z.number().optional().nullable(),
6357
+ finished_at: z.number().optional().nullable()
6358
+ }).optional().nullable()
6359
+ })
6360
+ );
6361
+ var collectorRESTParamsSchema = z.object({
6362
+ trace_id: z.union([z.string(), z.undefined()]).optional().nullable(),
6363
+ spans: z.array(spanSchema),
6364
+ metadata: z.object({
6365
+ user_id: z.union([z.string(), z.undefined()]).optional().nullable(),
6366
+ thread_id: z.union([z.string(), z.undefined()]).optional().nullable(),
6367
+ customer_id: z.union([z.string(), z.undefined()]).optional().nullable(),
6368
+ labels: z.union([z.array(z.string()), z.undefined()]).optional().nullable(),
6369
+ sdk_version: z.union([z.string(), z.undefined()]).optional().nullable(),
6370
+ sdk_language: z.union([z.string(), z.undefined()]).optional().nullable()
6371
+ }).and(customMetadataSchema).optional(),
6372
+ expected_output: z.string().optional().nullable(),
6373
+ evaluations: z.array(rESTEvaluationSchema).optional()
6374
+ });
6375
+ var collectorRESTParamsValidatorSchema = collectorRESTParamsSchema.omit({ spans: true });
6376
+ var datasetSpanSchema = z.union([
6377
+ baseSpanSchema.omit({
6378
+ project_id: true,
6379
+ trace_id: true,
6380
+ id: true,
6381
+ timestamps: true,
6382
+ metrics: true,
6383
+ params: true
6384
+ }).and(
6385
+ z.object({
6386
+ params: z.record(z.any())
6387
+ })
6388
+ ),
6389
+ lLMSpanSchema.omit({
6390
+ project_id: true,
6391
+ trace_id: true,
6392
+ id: true,
6393
+ timestamps: true,
6394
+ metrics: true,
6395
+ params: true
6396
+ }).and(
6397
+ z.object({
6398
+ params: z.record(z.any())
6399
+ })
6400
+ ),
6401
+ rAGSpanSchema.omit({
6402
+ project_id: true,
6403
+ trace_id: true,
6404
+ id: true,
6405
+ timestamps: true,
6406
+ metrics: true,
6407
+ params: true
6408
+ }).and(
6409
+ z.object({
6410
+ params: z.record(z.any())
6411
+ })
6412
+ )
6413
+ ]);
6414
+ var traceSchema = z.object({
6415
+ trace_id: z.string(),
6416
+ project_id: z.string(),
6417
+ metadata: traceMetadataSchema,
6418
+ timestamps: z.object({
6419
+ started_at: z.number(),
6420
+ inserted_at: z.number(),
6421
+ updated_at: z.number()
6422
+ }),
6423
+ input: traceInputSchema.optional(),
6424
+ output: traceOutputSchema.optional(),
6425
+ contexts: z.array(rAGChunkSchema).optional(),
6426
+ expected_output: z.object({
6427
+ value: z.string()
6428
+ }).optional(),
6429
+ metrics: z.object({
6430
+ first_token_ms: z.number().optional().nullable(),
6431
+ total_time_ms: z.number().optional().nullable(),
6432
+ prompt_tokens: z.number().optional().nullable(),
6433
+ completion_tokens: z.number().optional().nullable(),
6434
+ total_cost: z.number().optional().nullable(),
6435
+ tokens_estimated: z.boolean().optional().nullable()
6436
+ }).optional(),
6437
+ error: errorCaptureSchema.optional().nullable(),
6438
+ indexing_md5s: z.array(z.string()).optional(),
6439
+ events: z.array(eventSchema).optional(),
6440
+ evaluations: z.array(evaluationSchema).optional()
6441
+ });
6442
+
6443
+ // src/typeUtils.ts
6444
+ function camelToSnakeCase(str) {
6445
+ return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
6155
6446
  }
6156
-
6157
- // src/langchain.ts
6158
- var import_javascript_stringify = __toESM(require_dist());
6159
- var LangWatchCallbackHandler = class extends BaseCallbackHandler {
6160
- constructor({ trace }) {
6161
- super();
6162
- this.name = "LangWatchCallbackHandler";
6163
- this.spans = {};
6164
- this.trace = trace;
6165
- }
6166
- async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, _tags, metadata, name) {
6167
- this.spans[runId] = this.buildLLMSpan({
6168
- llm,
6169
- runId,
6170
- parentRunId,
6171
- input: {
6172
- type: "json",
6173
- value: prompts
6174
- },
6175
- extraParams,
6176
- metadata,
6177
- name
6178
- });
6179
- }
6180
- buildLLMSpan({
6181
- llm,
6182
- runId,
6183
- parentRunId,
6184
- input,
6185
- extraParams,
6186
- metadata,
6187
- name
6188
- }) {
6189
- try {
6190
- const parent = this.getParent(parentRunId);
6191
- const vendor = metadata?.ls_provider ?? llm.id.at(-2)?.toString();
6192
- const model = metadata?.ls_model_name ?? llm.kwargs?.model ?? "unknown";
6193
- const span = parent.startLLMSpan({
6194
- spanId: runId,
6195
- name: name ?? llm.id.at(-1)?.toString(),
6196
- input,
6197
- model: [vendor, model].filter((x) => x).join("/"),
6198
- params: {
6199
- temperature: extraParams?.invocation_params?.temperature,
6200
- ...extraParams?.invocation_params?.functions ? { functions: extraParams?.invocation_params?.functions } : {}
6201
- }
6202
- });
6203
- return span;
6204
- } catch (e) {
6205
- this.trace.client.emit("error", e);
6206
- throw e;
6207
- }
6208
- }
6209
- async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) {
6210
- this.spans[runId] = this.buildLLMSpan({
6211
- name,
6212
- llm,
6213
- runId,
6214
- parentRunId,
6215
- input: {
6216
- type: "chat_messages",
6217
- value: messages.flatMap(convertFromLangChainMessages)
6218
- },
6219
- extraParams,
6220
- metadata
6221
- });
6222
- }
6223
- async handleNewToken(_token, runId) {
6224
- const span = this.spans[runId];
6225
- if (runId && span && !span.timestamps.firstTokenAt) {
6226
- span.update({
6227
- timestamps: { ...span.timestamps, firstTokenAt: Date.now() }
6228
- });
6229
- }
6230
- }
6231
- async handleLLMEnd(response, runId, _parentRunId) {
6232
- try {
6233
- const span = this.spans[runId];
6234
- if (!span) {
6235
- return;
6236
- }
6237
- const outputs = [];
6238
- for (const generation of response.generations) {
6239
- for (const generation_ of generation) {
6240
- if ("message" in generation_) {
6241
- outputs.push({
6242
- type: "chat_messages",
6243
- value: convertFromLangChainMessages([
6244
- generation_.message
6245
- ])
6246
- });
6247
- } else if ("text" in generation_) {
6248
- outputs.push({
6249
- type: "text",
6250
- value: generation_.text
6251
- });
6252
- } else {
6253
- outputs.push({
6254
- type: "text",
6255
- value: JSON.stringify(generation_)
6256
- });
6257
- }
6258
- }
6259
- }
6260
- const output = outputs.length === 1 ? outputs[0] : { type: "list", value: outputs };
6261
- span.end({
6262
- output
6263
- // ...(metrics ? { metrics } : {}),
6264
- });
6265
- } catch (e) {
6266
- this.trace.client.emit("error", e);
6267
- throw e;
6268
- }
6269
- }
6270
- async handleLLMError(err, runId, _parentRunId) {
6271
- this.errorSpan({ runId, error: err });
6272
- }
6273
- async handleChainStart(chain, inputs, runId, parentRunId, _tags, _metadata, _runType, name) {
6274
- this.spans[runId] = this.buildSpan({
6275
- type: "chain",
6276
- serialized: chain,
6277
- runId,
6278
- parentRunId,
6279
- input: inputs,
6280
- name
6281
- });
6282
- }
6283
- async handleChainEnd(output, runId, _parentRunId) {
6284
- this.endSpan({
6285
- runId,
6286
- output
6287
- });
6288
- }
6289
- async handleChainError(err, runId, _parentRunId, _tags, _kwargs) {
6290
- this.errorSpan({ runId, error: err });
6291
- }
6292
- async handleToolStart(tool, input, runId, parentRunId, _tags, _metadata, name) {
6293
- this.spans[runId] = this.buildSpan({
6294
- type: "tool",
6295
- serialized: tool,
6296
- runId,
6297
- parentRunId,
6298
- input,
6299
- name
6300
- });
6301
- }
6302
- async handleToolEnd(output, runId, _parentRunId) {
6303
- this.endSpan({ runId, output });
6304
- }
6305
- async handleToolError(err, runId, _parentRunId, _tags) {
6306
- this.errorSpan({ runId, error: err });
6307
- }
6308
- async handleRetrieverStart(retriever, query, runId, parentRunId, _tags, _metadata, name) {
6309
- try {
6310
- const parent = this.getParent(parentRunId);
6311
- this.spans[runId] = parent.startRAGSpan({
6312
- spanId: runId,
6313
- name: name ?? retriever.name ?? retriever.id.at(-1)?.toString(),
6314
- input: this.autoconvertTypedValues(query)
6315
- });
6316
- } catch (e) {
6317
- this.trace.client.emit("error", e);
6318
- throw e;
6319
- }
6320
- }
6321
- async handleRetrieverEnd(documents, runId, _parentRunId, _tags) {
6322
- try {
6323
- const contexts = documents.map((doc) => ({
6324
- content: doc.pageContent,
6325
- ...doc.metadata.source ? { documentId: doc.metadata.source } : {}
6326
- }));
6327
- const span = this.spans[runId];
6328
- if (!span) {
6329
- return;
6330
- }
6331
- span.end({
6332
- contexts,
6333
- output: this.autoconvertTypedValues(documents)
6334
- });
6335
- } catch (e) {
6336
- this.trace.client.emit("error", e);
6337
- throw e;
6338
- }
6339
- }
6340
- async handleRetrieverError(err, runId, _parentRunId, _tags) {
6341
- this.errorSpan({ runId, error: err });
6342
- }
6343
- async handleAgentAction(_action, runId, _parentRunId, _tags) {
6344
- const span = this.spans[runId];
6345
- if (!span) {
6346
- return;
6347
- }
6348
- span.update({
6349
- type: "agent"
6350
- });
6351
- }
6352
- async handleAgentEnd(action, runId, _parentRunId, _tags) {
6353
- this.endSpan({
6354
- runId,
6355
- output: action.returnValues
6356
- });
6357
- }
6358
- buildSpan({
6359
- type,
6360
- serialized,
6361
- runId,
6362
- parentRunId,
6363
- input,
6364
- name
6365
- }) {
6366
- try {
6367
- const parent = this.getParent(parentRunId);
6368
- const span = parent.startSpan({
6369
- spanId: runId,
6370
- type,
6371
- name: name ?? serialized.name ?? serialized.id.at(-1)?.toString(),
6372
- input: this.autoconvertTypedValues(input)
6373
- });
6374
- return span;
6375
- } catch (e) {
6376
- this.trace.client.emit("error", e);
6377
- throw e;
6378
- }
6379
- }
6380
- endSpan({ runId, output }) {
6381
- try {
6382
- const span = this.spans[runId];
6383
- if (!span) {
6384
- return;
6447
+ function camelToSnakeCaseNested(obj, parentKey) {
6448
+ if (Array.isArray(obj)) {
6449
+ return obj.map(
6450
+ (item) => camelToSnakeCaseNested(item)
6451
+ );
6452
+ } else if (typeof obj === "object" && obj !== null) {
6453
+ const newObj = {};
6454
+ for (const key in obj) {
6455
+ if (obj.hasOwnProperty(key)) {
6456
+ const newKey = camelToSnakeCase(key);
6457
+ if (parentKey === "metadata" && !Object.keys(reservedTraceMetadataSchema.shape).includes(newKey) || parentKey === "params" && !Object.keys(reservedSpanParamsSchema.shape).includes(newKey)) {
6458
+ newObj[key] = obj[key];
6459
+ } else {
6460
+ newObj[newKey] = camelToSnakeCaseNested(obj[key], newKey);
6461
+ }
6385
6462
  }
6386
- span.end({
6387
- output: this.autoconvertTypedValues(output)
6388
- });
6389
- } catch (e) {
6390
- this.trace.client.emit("error", e);
6391
- throw e;
6392
6463
  }
6464
+ return newObj;
6465
+ } else {
6466
+ return obj;
6393
6467
  }
6394
- errorSpan({ runId, error }) {
6395
- const span = this.spans[runId];
6396
- if (!span) {
6397
- return;
6468
+ }
6469
+
6470
+ // node_modules/@ai-sdk/provider-utils/node_modules/nanoid/non-secure/index.js
6471
+ var customAlphabet = (alphabet, defaultSize = 21) => {
6472
+ return (size = defaultSize) => {
6473
+ let id = "";
6474
+ let i = size;
6475
+ while (i--) {
6476
+ id += alphabet[Math.random() * alphabet.length | 0];
6398
6477
  }
6399
- span.end({
6400
- error
6401
- });
6478
+ return id;
6479
+ };
6480
+ };
6481
+
6482
+ // node_modules/@ai-sdk/provider-utils/dist/index.mjs
6483
+ var import_secure_json_parse = __toESM(require_secure_json_parse(), 1);
6484
+ var generateId = customAlphabet(
6485
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
6486
+ 7
6487
+ );
6488
+ function convertUint8ArrayToBase64(array) {
6489
+ let latin1string = "";
6490
+ for (let i = 0; i < array.length; i++) {
6491
+ latin1string += String.fromCodePoint(array[i]);
6402
6492
  }
6403
- autoconvertTypedValues(value) {
6404
- if (!value || typeof value === "object" && Object.keys(value).length === 0) {
6405
- return void 0;
6406
- }
6407
- if (typeof value === "string") {
6408
- return { type: "text", value };
6409
- }
6410
- try {
6411
- JSON.stringify(value);
6412
- return { type: "json", value };
6413
- } catch (e) {
6414
- return { type: "text", value: (0, import_javascript_stringify.stringify)(value) ?? value.toString() };
6493
+ return globalThis.btoa(latin1string);
6494
+ }
6495
+
6496
+ // src/utils.ts
6497
+ var convertImageToUrl = (image, mimeType) => {
6498
+ try {
6499
+ return image instanceof URL ? image.toString() : typeof image === "string" ? image : `data:${mimeType ?? "image/jpeg"};base64,${convertUint8ArrayToBase64(
6500
+ image
6501
+ )}`;
6502
+ } catch (e) {
6503
+ console.error("[LangWatch] error converting vercel ui image to url:", e);
6504
+ return "";
6505
+ }
6506
+ };
6507
+ function convertFromVercelAIMessages(messages) {
6508
+ const lwMessages = [];
6509
+ for (const { role, content } of messages) {
6510
+ switch (role) {
6511
+ case "system": {
6512
+ lwMessages.push({ role: "system", content });
6513
+ break;
6514
+ }
6515
+ case "user": {
6516
+ if (Array.isArray(content) && content.length === 1 && content[0]?.type === "text") {
6517
+ lwMessages.push({ role: "user", content: content[0].text });
6518
+ break;
6519
+ }
6520
+ lwMessages.push({
6521
+ role: "user",
6522
+ content: Array.isArray(content) ? content.map((part) => {
6523
+ switch (part.type) {
6524
+ case "text": {
6525
+ return { type: "text", text: part.text };
6526
+ }
6527
+ case "image": {
6528
+ return {
6529
+ type: "image_url",
6530
+ image_url: {
6531
+ url: convertImageToUrl(part.image, part.mimeType)
6532
+ }
6533
+ };
6534
+ }
6535
+ }
6536
+ }) : content
6537
+ });
6538
+ break;
6539
+ }
6540
+ case "assistant": {
6541
+ let text = "";
6542
+ const toolCalls = [];
6543
+ if (Array.isArray(content)) {
6544
+ for (const part of content) {
6545
+ switch (part.type) {
6546
+ case "text": {
6547
+ text += part.text;
6548
+ break;
6549
+ }
6550
+ case "tool-call": {
6551
+ toolCalls.push({
6552
+ id: part.toolCallId,
6553
+ type: "function",
6554
+ function: {
6555
+ name: part.toolName,
6556
+ arguments: JSON.stringify(part.args)
6557
+ }
6558
+ });
6559
+ break;
6560
+ }
6561
+ default: {
6562
+ const _exhaustiveCheck = part;
6563
+ throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
6564
+ }
6565
+ }
6566
+ }
6567
+ } else {
6568
+ text = content;
6569
+ }
6570
+ lwMessages.push({
6571
+ role: "assistant",
6572
+ content: text,
6573
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
6574
+ });
6575
+ break;
6576
+ }
6577
+ case "tool": {
6578
+ for (const toolResponse of content) {
6579
+ lwMessages.push({
6580
+ role: "tool",
6581
+ tool_call_id: toolResponse.toolCallId,
6582
+ content: JSON.stringify(toolResponse.result)
6583
+ });
6584
+ }
6585
+ break;
6586
+ }
6587
+ default: {
6588
+ const _exhaustiveCheck = role;
6589
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
6590
+ }
6415
6591
  }
6416
6592
  }
6417
- getParent(parentRunId) {
6418
- return (parentRunId ? this.spans[parentRunId] : this.spans[Object.keys(this.spans).at(-1) ?? ""]) ?? this.trace;
6593
+ return lwMessages;
6594
+ }
6595
+ var captureError = (error) => {
6596
+ if (error && typeof error === "object" && "has_error" in error && "message" in error && "stacktrace" in error) {
6597
+ return error;
6598
+ } else if (error instanceof Error) {
6599
+ return {
6600
+ has_error: true,
6601
+ message: error.message,
6602
+ stacktrace: error.stack ? error.stack.split("\n") : []
6603
+ };
6604
+ } else if (typeof error === "object" && error !== null) {
6605
+ const err = error;
6606
+ const message = typeof err.message === "string" ? err.message : "An unknown error occurred";
6607
+ const stacktrace = typeof err.stack === "string" ? err.stack.split("\n") : Array.isArray(err.stack) && err.stack.length > 0 && typeof err.stack[0] === "string" ? err.stack : ["No stack trace available"];
6608
+ return {
6609
+ has_error: true,
6610
+ message,
6611
+ stacktrace
6612
+ };
6613
+ } else {
6614
+ return {
6615
+ has_error: true,
6616
+ message: String(error),
6617
+ stacktrace: []
6618
+ };
6419
6619
  }
6420
6620
  };
6421
- var convertFromLangChainMessages = (messages) => {
6422
- const chatMessages = [];
6423
- for (const message of messages) {
6424
- chatMessages.push(convertFromLangChainMessage(message));
6621
+ var autoconvertTypedValues = (value) => {
6622
+ if (typeof value === "string") {
6623
+ return { type: "text", value };
6425
6624
  }
6426
- return chatMessages;
6427
- };
6428
- var convertFromLangChainMessage = (message) => {
6429
- let role = "user";
6430
- const message_ = message.lc_serializable ? mapChatMessagesToStoredMessages([message])[0] : message;
6431
- if (message_ instanceof HumanMessage || message_ instanceof HumanMessageChunk || message_.id?.at(-1) === "HumanMessage" || message_.id?.at(-1) === "HumanMessageChunk" || message_.type === "human") {
6432
- role = "user";
6433
- } else if (message instanceof AIMessage || message instanceof AIMessageChunk || message.id?.at(-1) === "AIMessage" || message.id?.at(-1) === "AIMessageChunk" || message_.type === "ai") {
6434
- role = "assistant";
6435
- } else if (message instanceof SystemMessage || message instanceof SystemMessageChunk || message.id?.at(-1) === "SystemMessage" || message.id?.at(-1) === "SystemMessageChunk" || message_.type === "system") {
6436
- role = "system";
6437
- } else if (message instanceof FunctionMessage || message instanceof FunctionMessageChunk || message.id?.at(-1) === "FunctionMessage" || message.id?.at(-1) === "FunctionMessageChunk" || message_.type === "function") {
6438
- role = "function";
6439
- } else if (message instanceof ToolMessage || message instanceof ToolMessageChunk || message.id?.at(-1) === "ToolMessage" || message.id?.at(-1) === "ToolMessageChunk" || message_.type === "tool") {
6440
- role = "tool";
6625
+ const chatMessages = z.array(chatMessageSchema).safeParse(value);
6626
+ if (Array.isArray(value) && chatMessages.success) {
6627
+ return {
6628
+ type: "chat_messages",
6629
+ value: chatMessages.data
6630
+ };
6631
+ }
6632
+ try {
6633
+ JSON.stringify(value);
6634
+ return { type: "json", value };
6635
+ } catch (e) {
6636
+ return { type: "raw", value };
6441
6637
  }
6442
- const content = typeof message.content === "string" ? message.content : message.content.map(
6443
- (content2) => content2.type === "text" ? { type: "text", text: content2.text } : content2.type == "image_url" ? { type: "image_url", image_url: content2.image_url } : { type: "text", text: JSON.stringify(content2) }
6444
- );
6445
- const functionCall = message.additional_kwargs;
6446
- return {
6447
- role,
6448
- content,
6449
- ...functionCall && typeof functionCall === "object" && Object.keys(functionCall).length > 0 ? { function_call: functionCall } : {}
6450
- };
6451
6638
  };
6452
6639
 
6453
6640
  // src/index.ts
@@ -6534,22 +6721,118 @@ var LangWatchTrace = class {
6534
6721
  metadata
6535
6722
  }) {
6536
6723
  this.finishedSpans = {};
6724
+ this.evaluations = [];
6725
+ this.addEvaluation = ({
6726
+ evaluationId,
6727
+ span,
6728
+ name,
6729
+ type,
6730
+ isGuardrail,
6731
+ status = "processed",
6732
+ passed,
6733
+ score,
6734
+ label,
6735
+ details,
6736
+ error,
6737
+ timestamps
6738
+ }) => {
6739
+ const currentEvaluationIndex = this.evaluations.findIndex(
6740
+ (e) => evaluationId && "evaluationId" in e && e.evaluationId === evaluationId
6741
+ );
6742
+ const currentEvaluation = currentEvaluationIndex !== -1 ? this.evaluations[currentEvaluationIndex] : void 0;
6743
+ const evaluationResult = {
6744
+ status,
6745
+ ...passed !== void 0 && { passed },
6746
+ ...score !== void 0 && { score },
6747
+ ...label !== void 0 && { label },
6748
+ ...details !== void 0 && { details }
6749
+ };
6750
+ let span_ = span;
6751
+ if (!span_) {
6752
+ span_ = this.startSpan({
6753
+ type: "evaluation"
6754
+ });
6755
+ }
6756
+ if (span_.type !== "evaluation") {
6757
+ span_ = span_.startSpan({ type: "evaluation" });
6758
+ }
6759
+ span_.update({
6760
+ name,
6761
+ output: {
6762
+ type: "evaluation_result",
6763
+ value: evaluationResult
6764
+ },
6765
+ error,
6766
+ timestamps: timestamps ? {
6767
+ startedAt: timestamps.startedAt ?? span_.timestamps.startedAt,
6768
+ finishedAt: timestamps.finishedAt ?? void 0
6769
+ } : void 0
6770
+ });
6771
+ span_.end();
6772
+ const evaluation = {
6773
+ evaluationId: evaluationId ?? `eval_${nanoid()}`,
6774
+ spanId: span_.spanId,
6775
+ name,
6776
+ type,
6777
+ isGuardrail,
6778
+ status,
6779
+ passed,
6780
+ score,
6781
+ label,
6782
+ details,
6783
+ error: error ? captureError(error) : void 0,
6784
+ timestamps: timestamps ?? {
6785
+ startedAt: span_.timestamps.startedAt,
6786
+ finishedAt: span_.timestamps.finishedAt
6787
+ }
6788
+ };
6789
+ if (currentEvaluation && currentEvaluationIndex !== -1) {
6790
+ this.evaluations[currentEvaluationIndex] = {
6791
+ ...currentEvaluation,
6792
+ ...evaluation
6793
+ };
6794
+ } else {
6795
+ this.evaluations.push(evaluation);
6796
+ }
6797
+ };
6537
6798
  this.client = client;
6538
6799
  this.traceId = traceId;
6539
- this.metadata = metadata;
6800
+ this.metadata = {
6801
+ ...metadata,
6802
+ sdkVersion: version,
6803
+ sdkLanguage: "typescript"
6804
+ };
6540
6805
  }
6541
6806
  update({ metadata }) {
6542
6807
  this.metadata = {
6543
6808
  ...this.metadata,
6544
6809
  ...metadata,
6545
- ...typeof metadata.labels !== "undefined" ? { labels: [...this.metadata?.labels ?? [], ...metadata.labels] } : {}
6810
+ ...typeof metadata.labels !== "undefined" ? {
6811
+ labels: [
6812
+ ...this.metadata?.labels ?? [],
6813
+ ...metadata.labels ?? []
6814
+ ]
6815
+ } : {}
6816
+ };
6817
+ }
6818
+ setCurrentSpan(span) {
6819
+ this.currentSpan = {
6820
+ current: span,
6821
+ previous: this.currentSpan
6546
6822
  };
6547
6823
  }
6824
+ getCurrentSpan() {
6825
+ return this.currentSpan?.current;
6826
+ }
6827
+ resetCurrentSpan() {
6828
+ this.currentSpan = this.currentSpan?.previous;
6829
+ }
6548
6830
  startSpan(params) {
6549
6831
  const span = new LangWatchSpan({
6550
6832
  trace: this,
6551
6833
  ...params
6552
6834
  });
6835
+ this.setCurrentSpan(span);
6553
6836
  return span;
6554
6837
  }
6555
6838
  startLLMSpan(params) {
@@ -6557,6 +6840,7 @@ var LangWatchTrace = class {
6557
6840
  trace: this,
6558
6841
  ...params
6559
6842
  });
6843
+ this.setCurrentSpan(span);
6560
6844
  return span;
6561
6845
  }
6562
6846
  startRAGSpan(params) {
@@ -6564,8 +6848,15 @@ var LangWatchTrace = class {
6564
6848
  trace: this,
6565
6849
  ...params
6566
6850
  });
6851
+ this.setCurrentSpan(span);
6567
6852
  return span;
6568
6853
  }
6854
+ async evaluate(params) {
6855
+ return evaluate({
6856
+ trace: this,
6857
+ ...params
6858
+ });
6859
+ }
6569
6860
  getLangChainCallback() {
6570
6861
  if (!this.langchainCallback) {
6571
6862
  this.langchainCallback = new LangWatchCallbackHandler({ trace: this });
@@ -6574,6 +6865,7 @@ var LangWatchTrace = class {
6574
6865
  }
6575
6866
  onEnd(span) {
6576
6867
  this.finishedSpans[span.span_id] = span;
6868
+ this.resetCurrentSpan();
6577
6869
  this.delayedSendSpans();
6578
6870
  }
6579
6871
  delayedSendSpans() {
@@ -6588,8 +6880,9 @@ var LangWatchTrace = class {
6588
6880
  try {
6589
6881
  trace = collectorRESTParamsSchema.parse({
6590
6882
  trace_id: this.traceId,
6591
- metadata: camelToSnakeCaseNested(this.metadata),
6592
- spans: Object.values(this.finishedSpans)
6883
+ metadata: camelToSnakeCaseNested(this.metadata, "metadata"),
6884
+ spans: Object.values(this.finishedSpans),
6885
+ evaluations: camelToSnakeCaseNested(this.evaluations)
6593
6886
  });
6594
6887
  } catch (error) {
6595
6888
  if (error instanceof ZodError) {
@@ -6665,6 +6958,7 @@ var LangWatchSpan = class _LangWatchSpan {
6665
6958
  parentId: this.spanId,
6666
6959
  ...params
6667
6960
  });
6961
+ this.trace.setCurrentSpan(span);
6668
6962
  return span;
6669
6963
  }
6670
6964
  startLLMSpan(params) {
@@ -6673,6 +6967,7 @@ var LangWatchSpan = class _LangWatchSpan {
6673
6967
  parentId: this.spanId,
6674
6968
  ...params
6675
6969
  });
6970
+ this.trace.setCurrentSpan(span);
6676
6971
  return span;
6677
6972
  }
6678
6973
  startRAGSpan(params) {
@@ -6681,8 +6976,21 @@ var LangWatchSpan = class _LangWatchSpan {
6681
6976
  parentId: this.spanId,
6682
6977
  ...params
6683
6978
  });
6979
+ this.trace.setCurrentSpan(span);
6684
6980
  return span;
6685
6981
  }
6982
+ addEvaluation(params) {
6983
+ this.trace.addEvaluation({
6984
+ ...params,
6985
+ span: this
6986
+ });
6987
+ }
6988
+ async evaluate(params) {
6989
+ return evaluate({
6990
+ span: this,
6991
+ ...params
6992
+ });
6993
+ }
6686
6994
  end(params) {
6687
6995
  this.timestamps.finishedAt = Date.now();
6688
6996
  if (params) {