@launchdarkly/server-sdk-ai 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/index.cjs +1117 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +1022 -0
  5. package/dist/index.d.ts +1022 -0
  6. package/dist/index.js +1071 -0
  7. package/dist/index.js.map +1 -0
  8. package/package.json +22 -5
  9. package/__tests__/Judge.test.ts +0 -496
  10. package/__tests__/LDAIClientImpl.test.ts +0 -589
  11. package/__tests__/LDAIConfigTrackerImpl.test.ts +0 -815
  12. package/__tests__/TokenUsage.test.ts +0 -119
  13. package/__tests__/TrackedChat.test.ts +0 -230
  14. package/dist/package.json +0 -53
  15. package/dist/src/LDAIClientImpl.d.ts +0 -39
  16. package/dist/src/LDAIClientImpl.d.ts.map +0 -1
  17. package/dist/src/LDAIClientImpl.js +0 -164
  18. package/dist/src/LDAIClientImpl.js.map +0 -1
  19. package/dist/src/LDAIConfigTrackerImpl.d.ts +0 -73
  20. package/dist/src/LDAIConfigTrackerImpl.d.ts.map +0 -1
  21. package/dist/src/LDAIConfigTrackerImpl.js +0 -203
  22. package/dist/src/LDAIConfigTrackerImpl.js.map +0 -1
  23. package/dist/src/LDClientMin.d.ts +0 -11
  24. package/dist/src/LDClientMin.d.ts.map +0 -1
  25. package/dist/src/LDClientMin.js +0 -3
  26. package/dist/src/LDClientMin.js.map +0 -1
  27. package/dist/src/api/LDAIClient.d.ts +0 -258
  28. package/dist/src/api/LDAIClient.d.ts.map +0 -1
  29. package/dist/src/api/LDAIClient.js +0 -3
  30. package/dist/src/api/LDAIClient.js.map +0 -1
  31. package/dist/src/api/chat/TrackedChat.d.ts +0 -72
  32. package/dist/src/api/chat/TrackedChat.d.ts.map +0 -1
  33. package/dist/src/api/chat/TrackedChat.js +0 -125
  34. package/dist/src/api/chat/TrackedChat.js.map +0 -1
  35. package/dist/src/api/chat/index.d.ts +0 -3
  36. package/dist/src/api/chat/index.d.ts.map +0 -1
  37. package/dist/src/api/chat/index.js +0 -19
  38. package/dist/src/api/chat/index.js.map +0 -1
  39. package/dist/src/api/chat/types.d.ts +0 -22
  40. package/dist/src/api/chat/types.d.ts.map +0 -1
  41. package/dist/src/api/chat/types.js +0 -3
  42. package/dist/src/api/chat/types.js.map +0 -1
  43. package/dist/src/api/config/LDAIConfigTracker.d.ts +0 -203
  44. package/dist/src/api/config/LDAIConfigTracker.d.ts.map +0 -1
  45. package/dist/src/api/config/LDAIConfigTracker.js +0 -3
  46. package/dist/src/api/config/LDAIConfigTracker.js.map +0 -1
  47. package/dist/src/api/config/LDAIConfigUtils.d.ts +0 -2
  48. package/dist/src/api/config/LDAIConfigUtils.d.ts.map +0 -1
  49. package/dist/src/api/config/LDAIConfigUtils.js +0 -141
  50. package/dist/src/api/config/LDAIConfigUtils.js.map +0 -1
  51. package/dist/src/api/config/index.d.ts +0 -3
  52. package/dist/src/api/config/index.d.ts.map +0 -1
  53. package/dist/src/api/config/index.js +0 -18
  54. package/dist/src/api/config/index.js.map +0 -1
  55. package/dist/src/api/config/types.d.ts +0 -202
  56. package/dist/src/api/config/types.d.ts.map +0 -1
  57. package/dist/src/api/config/types.js +0 -3
  58. package/dist/src/api/config/types.js.map +0 -1
  59. package/dist/src/api/index.d.ts +0 -7
  60. package/dist/src/api/index.d.ts.map +0 -1
  61. package/dist/src/api/index.js +0 -23
  62. package/dist/src/api/index.js.map +0 -1
  63. package/dist/src/api/judge/EvaluationSchemaBuilder.d.ts +0 -11
  64. package/dist/src/api/judge/EvaluationSchemaBuilder.d.ts.map +0 -1
  65. package/dist/src/api/judge/EvaluationSchemaBuilder.js +0 -52
  66. package/dist/src/api/judge/EvaluationSchemaBuilder.js.map +0 -1
  67. package/dist/src/api/judge/Judge.d.ts +0 -63
  68. package/dist/src/api/judge/Judge.d.ts.map +0 -1
  69. package/dist/src/api/judge/Judge.js +0 -149
  70. package/dist/src/api/judge/Judge.js.map +0 -1
  71. package/dist/src/api/judge/index.d.ts +0 -3
  72. package/dist/src/api/judge/index.d.ts.map +0 -1
  73. package/dist/src/api/judge/index.js +0 -6
  74. package/dist/src/api/judge/index.js.map +0 -1
  75. package/dist/src/api/judge/types.d.ts +0 -35
  76. package/dist/src/api/judge/types.d.ts.map +0 -1
  77. package/dist/src/api/judge/types.js +0 -3
  78. package/dist/src/api/judge/types.js.map +0 -1
  79. package/dist/src/api/metrics/BedrockTokenUsage.d.ts +0 -7
  80. package/dist/src/api/metrics/BedrockTokenUsage.d.ts.map +0 -1
  81. package/dist/src/api/metrics/BedrockTokenUsage.js +0 -12
  82. package/dist/src/api/metrics/BedrockTokenUsage.js.map +0 -1
  83. package/dist/src/api/metrics/LDAIMetrics.d.ts +0 -17
  84. package/dist/src/api/metrics/LDAIMetrics.d.ts.map +0 -1
  85. package/dist/src/api/metrics/LDAIMetrics.js +0 -3
  86. package/dist/src/api/metrics/LDAIMetrics.js.map +0 -1
  87. package/dist/src/api/metrics/LDFeedbackKind.d.ts +0 -14
  88. package/dist/src/api/metrics/LDFeedbackKind.d.ts.map +0 -1
  89. package/dist/src/api/metrics/LDFeedbackKind.js +0 -18
  90. package/dist/src/api/metrics/LDFeedbackKind.js.map +0 -1
  91. package/dist/src/api/metrics/LDTokenUsage.d.ts +0 -18
  92. package/dist/src/api/metrics/LDTokenUsage.d.ts.map +0 -1
  93. package/dist/src/api/metrics/LDTokenUsage.js +0 -3
  94. package/dist/src/api/metrics/LDTokenUsage.js.map +0 -1
  95. package/dist/src/api/metrics/OpenAiUsage.d.ts +0 -7
  96. package/dist/src/api/metrics/OpenAiUsage.d.ts.map +0 -1
  97. package/dist/src/api/metrics/OpenAiUsage.js +0 -13
  98. package/dist/src/api/metrics/OpenAiUsage.js.map +0 -1
  99. package/dist/src/api/metrics/VercelAISDKTokenUsage.d.ts +0 -9
  100. package/dist/src/api/metrics/VercelAISDKTokenUsage.d.ts.map +0 -1
  101. package/dist/src/api/metrics/VercelAISDKTokenUsage.js +0 -13
  102. package/dist/src/api/metrics/VercelAISDKTokenUsage.js.map +0 -1
  103. package/dist/src/api/metrics/index.d.ts +0 -7
  104. package/dist/src/api/metrics/index.d.ts.map +0 -1
  105. package/dist/src/api/metrics/index.js +0 -23
  106. package/dist/src/api/metrics/index.js.map +0 -1
  107. package/dist/src/api/providers/AIProvider.d.ts +0 -52
  108. package/dist/src/api/providers/AIProvider.d.ts.map +0 -1
  109. package/dist/src/api/providers/AIProvider.js +0 -88
  110. package/dist/src/api/providers/AIProvider.js.map +0 -1
  111. package/dist/src/api/providers/AIProviderFactory.d.ts +0 -39
  112. package/dist/src/api/providers/AIProviderFactory.d.ts.map +0 -1
  113. package/dist/src/api/providers/AIProviderFactory.js +0 -102
  114. package/dist/src/api/providers/AIProviderFactory.js.map +0 -1
  115. package/dist/src/api/providers/index.d.ts +0 -3
  116. package/dist/src/api/providers/index.d.ts.map +0 -1
  117. package/dist/src/api/providers/index.js +0 -19
  118. package/dist/src/api/providers/index.js.map +0 -1
  119. package/dist/src/index.d.ts +0 -19
  120. package/dist/src/index.d.ts.map +0 -1
  121. package/dist/src/index.js +0 -29
  122. package/dist/src/index.js.map +0 -1
  123. package/docs/.nojekyll +0 -1
  124. package/docs/assets/highlight.css +0 -92
  125. package/docs/assets/main.js +0 -58
  126. package/docs/assets/search.js +0 -1
  127. package/docs/assets/style.css +0 -1379
  128. package/docs/classes/AIProvider.html +0 -210
  129. package/docs/classes/AIProviderFactory.html +0 -208
  130. package/docs/classes/Judge.html +0 -322
  131. package/docs/classes/TrackedChat.html +0 -322
  132. package/docs/enums/LDFeedbackKind.html +0 -115
  133. package/docs/functions/createBedrockTokenUsage.html +0 -94
  134. package/docs/functions/createOpenAiUsage.html +0 -94
  135. package/docs/functions/createVercelAISDKTokenUsage.html +0 -98
  136. package/docs/functions/initAi.html +0 -93
  137. package/docs/index.html +0 -136
  138. package/docs/interfaces/ChatResponse.html +0 -130
  139. package/docs/interfaces/EvalScore.html +0 -119
  140. package/docs/interfaces/JudgeResponse.html +0 -129
  141. package/docs/interfaces/LDAIAgentConfig.html +0 -167
  142. package/docs/interfaces/LDAIAgentConfigDefault.html +0 -155
  143. package/docs/interfaces/LDAIAgentRequestConfig.html +0 -129
  144. package/docs/interfaces/LDAIClient.html +0 -449
  145. package/docs/interfaces/LDAICompletionConfig.html +0 -167
  146. package/docs/interfaces/LDAICompletionConfigDefault.html +0 -155
  147. package/docs/interfaces/LDAIConfig.html +0 -148
  148. package/docs/interfaces/LDAIConfigDefault.html +0 -133
  149. package/docs/interfaces/LDAIConfigTracker.html +0 -510
  150. package/docs/interfaces/LDAIJudgeConfig.html +0 -167
  151. package/docs/interfaces/LDAIJudgeConfigDefault.html +0 -155
  152. package/docs/interfaces/LDAIMetrics.html +0 -121
  153. package/docs/interfaces/LDJudge.html +0 -119
  154. package/docs/interfaces/LDJudgeConfiguration.html +0 -109
  155. package/docs/interfaces/LDLogger.html +0 -189
  156. package/docs/interfaces/LDMessage.html +0 -119
  157. package/docs/interfaces/LDModelConfig.html +0 -139
  158. package/docs/interfaces/LDProviderConfig.html +0 -105
  159. package/docs/interfaces/LDTokenUsage.html +0 -129
  160. package/docs/interfaces/StructuredResponse.html +0 -129
  161. package/docs/types/LDAIConfigDefaultKind.html +0 -81
  162. package/docs/types/LDAIConfigKind.html +0 -81
  163. package/docs/types/LDAIConfigMode.html +0 -81
  164. package/docs/types/SupportedAIProvider.html +0 -81
  165. package/docs/variables/SUPPORTED_AI_PROVIDERS.html +0 -81
  166. package/jest.config.js +0 -7
  167. package/src/LDAIClientImpl.ts +0 -327
  168. package/src/LDAIConfigTrackerImpl.ts +0 -278
  169. package/src/LDClientMin.ts +0 -18
  170. package/src/api/LDAIClient.ts +0 -325
  171. package/src/api/chat/TrackedChat.ts +0 -159
  172. package/src/api/chat/index.ts +0 -2
  173. package/src/api/chat/types.ts +0 -24
  174. package/src/api/config/LDAIConfigTracker.ts +0 -231
  175. package/src/api/config/LDAIConfigUtils.ts +0 -201
  176. package/src/api/config/index.ts +0 -3
  177. package/src/api/config/types.ts +0 -256
  178. package/src/api/index.ts +0 -6
  179. package/src/api/judge/EvaluationSchemaBuilder.ts +0 -54
  180. package/src/api/judge/Judge.ts +0 -216
  181. package/src/api/judge/index.ts +0 -2
  182. package/src/api/judge/types.ts +0 -39
  183. package/src/api/metrics/BedrockTokenUsage.ts +0 -13
  184. package/src/api/metrics/LDAIMetrics.ts +0 -18
  185. package/src/api/metrics/LDFeedbackKind.ts +0 -13
  186. package/src/api/metrics/LDTokenUsage.ts +0 -19
  187. package/src/api/metrics/OpenAiUsage.ts +0 -13
  188. package/src/api/metrics/VercelAISDKTokenUsage.ts +0 -15
  189. package/src/api/metrics/index.ts +0 -6
  190. package/src/api/providers/AIProvider.ts +0 -94
  191. package/src/api/providers/AIProviderFactory.ts +0 -152
  192. package/src/api/providers/index.ts +0 -2
  193. package/src/index.ts +0 -24
  194. package/tsconfig.eslint.json +0 -5
  195. package/tsconfig.json +0 -21
  196. package/tsconfig.ref.json +0 -7
  197. package/typedoc.json +0 -5
package/dist/index.js ADDED
@@ -0,0 +1,1071 @@
1
+ // src/LDAIClientImpl.ts
2
+ import Mustache2 from "mustache";
3
+
4
+ // src/api/chat/TrackedChat.ts
5
+ var TrackedChat = class {
6
+ constructor(aiConfig, tracker, provider, judges = {}, _logger) {
7
+ this.aiConfig = aiConfig;
8
+ this.tracker = tracker;
9
+ this.provider = provider;
10
+ this.judges = judges;
11
+ this._logger = _logger;
12
+ this.messages = [];
13
+ }
14
+ /**
15
+ * Invoke the chat model with a prompt string.
16
+ * This method handles conversation management and tracking, delegating to the provider's invokeModel method.
17
+ */
18
+ async invoke(prompt) {
19
+ const userMessage = {
20
+ role: "user",
21
+ content: prompt
22
+ };
23
+ this.messages.push(userMessage);
24
+ const configMessages = this.aiConfig.messages || [];
25
+ const allMessages = [...configMessages, ...this.messages];
26
+ const response = await this.tracker.trackMetricsOf(
27
+ (result) => result.metrics,
28
+ () => this.provider.invokeModel(allMessages)
29
+ );
30
+ if (this.aiConfig.judgeConfiguration?.judges && this.aiConfig.judgeConfiguration.judges.length > 0) {
31
+ response.evaluations = this._evaluateWithJudges(this.messages, response);
32
+ }
33
+ this.messages.push(response.message);
34
+ return response;
35
+ }
36
+ /**
37
+ * Evaluates the response with all configured judges.
38
+ * Returns a promise that resolves to an array of evaluation results.
39
+ *
40
+ * @param messages Array of messages representing the conversation history
41
+ * @param response The AI response to be evaluated
42
+ * @returns Promise resolving to array of judge evaluation results
43
+ */
44
+ async _evaluateWithJudges(messages, response) {
45
+ const judgeConfigs = this.aiConfig.judgeConfiguration.judges;
46
+ const evaluationPromises = judgeConfigs.map(async (judgeConfig) => {
47
+ const judge = this.judges[judgeConfig.key];
48
+ if (!judge) {
49
+ this._logger?.warn(
50
+ `Judge configuration is not enabled: ${judgeConfig.key}`,
51
+ this.tracker.getTrackData()
52
+ );
53
+ return void 0;
54
+ }
55
+ const judgeResponse = await judge.evaluateMessages(
56
+ messages,
57
+ response,
58
+ judgeConfig.samplingRate
59
+ );
60
+ if (judgeResponse && judgeResponse.success) {
61
+ this.tracker.trackJudgeResponse(judgeResponse);
62
+ }
63
+ return judgeResponse;
64
+ });
65
+ const results = await Promise.allSettled(evaluationPromises);
66
+ return results.map((result) => result.status === "fulfilled" ? result.value : void 0);
67
+ }
68
+ /**
69
+ * Get the underlying AI configuration used to initialize this TrackedChat.
70
+ */
71
+ getConfig() {
72
+ return this.aiConfig;
73
+ }
74
+ /**
75
+ * Get the underlying AI configuration tracker used to initialize this TrackedChat.
76
+ */
77
+ getTracker() {
78
+ return this.tracker;
79
+ }
80
+ /**
81
+ * Get the underlying AI provider instance.
82
+ * This provides direct access to the provider for advanced use cases.
83
+ */
84
+ getProvider() {
85
+ return this.provider;
86
+ }
87
+ /**
88
+ * Get the judges associated with this TrackedChat.
89
+ * Returns a record of judge instances keyed by their configuration keys.
90
+ */
91
+ getJudges() {
92
+ return this.judges;
93
+ }
94
+ /**
95
+ * Append messages to the conversation history.
96
+ * Adds messages to the conversation history without invoking the model,
97
+ * which is useful for managing multi-turn conversations or injecting context.
98
+ *
99
+ * @param messages Array of messages to append to the conversation history
100
+ */
101
+ appendMessages(messages) {
102
+ this.messages.push(...messages);
103
+ }
104
+ /**
105
+ * Get all messages in the conversation history.
106
+ *
107
+ * @param includeConfigMessages Whether to include the config messages from the AIConfig.
108
+ * Defaults to false.
109
+ * @returns Array of messages. When includeConfigMessages is true, returns both config
110
+ * messages and conversation history with config messages prepended. When false,
111
+ * returns only the conversation history messages.
112
+ */
113
+ getMessages(includeConfigMessages = false) {
114
+ if (includeConfigMessages) {
115
+ const configMessages = this.aiConfig.messages || [];
116
+ return [...configMessages, ...this.messages];
117
+ }
118
+ return [...this.messages];
119
+ }
120
+ };
121
+
122
+ // src/api/config/LDAIConfigUtils.ts
123
+ var LDAIConfigUtils = class {
124
+ /**
125
+ * Converts a default AI configuration to a LaunchDarkly flag value format.
126
+ *
127
+ * @param config The default AI configuration to convert
128
+ * @param mode The mode for the configuration
129
+ * @returns The flag value structure for LaunchDarkly
130
+ */
131
+ static toFlagValue(config, mode) {
132
+ const flagValue = {
133
+ _ldMeta: {
134
+ variationKey: "",
135
+ // Not available when converting from config
136
+ enabled: config.enabled ?? false,
137
+ mode
138
+ },
139
+ model: config.model
140
+ };
141
+ if ("messages" in config && config.messages !== void 0) {
142
+ flagValue.messages = config.messages;
143
+ }
144
+ if (config.provider !== void 0) {
145
+ flagValue.provider = config.provider;
146
+ }
147
+ if ("instructions" in config && config.instructions !== void 0) {
148
+ flagValue.instructions = config.instructions;
149
+ }
150
+ if ("evaluationMetricKeys" in config && config.evaluationMetricKeys !== void 0) {
151
+ flagValue.evaluationMetricKeys = config.evaluationMetricKeys;
152
+ }
153
+ if ("judgeConfiguration" in config && config.judgeConfiguration !== void 0) {
154
+ flagValue.judgeConfiguration = config.judgeConfiguration;
155
+ }
156
+ return flagValue;
157
+ }
158
+ /**
159
+ * Converts a LaunchDarkly flag value to the appropriate AI configuration type.
160
+ *
161
+ * @param flagValue The flag value from LaunchDarkly
162
+ * @param tracker The tracker to add to the config
163
+ * @returns The appropriate AI configuration type
164
+ */
165
+ static fromFlagValue(key, flagValue, tracker) {
166
+ const flagValueMode = flagValue._ldMeta?.mode;
167
+ switch (flagValueMode) {
168
+ case "agent":
169
+ return this.toAgentConfig(key, flagValue, tracker);
170
+ case "judge":
171
+ return this.toJudgeConfig(key, flagValue, tracker);
172
+ case "completion":
173
+ default:
174
+ return this.toCompletionConfig(key, flagValue, tracker);
175
+ }
176
+ }
177
+ /**
178
+ * Creates a disabled configuration of the specified mode.
179
+ *
180
+ * @param mode The mode for the disabled config
181
+ * @returns A disabled config of the appropriate type
182
+ */
183
+ static createDisabledConfig(key, mode) {
184
+ switch (mode) {
185
+ case "agent":
186
+ return {
187
+ key,
188
+ enabled: false,
189
+ tracker: void 0
190
+ };
191
+ case "judge":
192
+ return {
193
+ key,
194
+ enabled: false,
195
+ tracker: void 0,
196
+ evaluationMetricKeys: []
197
+ };
198
+ case "completion":
199
+ default:
200
+ return {
201
+ key,
202
+ enabled: false,
203
+ tracker: void 0
204
+ };
205
+ }
206
+ }
207
+ /**
208
+ * Creates the base configuration that all config types share.
209
+ *
210
+ * @param flagValue The flag value from LaunchDarkly
211
+ * @returns Base configuration object
212
+ */
213
+ static _toBaseConfig(key, flagValue) {
214
+ return {
215
+ key,
216
+ // eslint-disable-next-line no-underscore-dangle
217
+ enabled: flagValue._ldMeta?.enabled ?? false,
218
+ model: flagValue.model,
219
+ provider: flagValue.provider
220
+ };
221
+ }
222
+ /**
223
+ * Creates a completion config from flag value data.
224
+ *
225
+ * @param flagValue The flag value from LaunchDarkly
226
+ * @param tracker The tracker to add to the config
227
+ * @returns A completion configuration
228
+ */
229
+ static toCompletionConfig(key, flagValue, tracker) {
230
+ return {
231
+ ...this._toBaseConfig(key, flagValue),
232
+ tracker,
233
+ messages: flagValue.messages,
234
+ judgeConfiguration: flagValue.judgeConfiguration
235
+ };
236
+ }
237
+ /**
238
+ * Creates an agent config from flag value data.
239
+ *
240
+ * @param flagValue The flag value from LaunchDarkly
241
+ * @param tracker The tracker to add to the config
242
+ * @returns An agent configuration
243
+ */
244
+ static toAgentConfig(key, flagValue, tracker) {
245
+ return {
246
+ ...this._toBaseConfig(key, flagValue),
247
+ tracker,
248
+ instructions: flagValue.instructions,
249
+ judgeConfiguration: flagValue.judgeConfiguration
250
+ };
251
+ }
252
+ /**
253
+ * Creates a judge config from flag value data.
254
+ *
255
+ * @param flagValue The flag value from LaunchDarkly
256
+ * @param tracker The tracker to add to the config
257
+ * @returns A judge configuration
258
+ */
259
+ static toJudgeConfig(key, flagValue, tracker) {
260
+ return {
261
+ ...this._toBaseConfig(key, flagValue),
262
+ tracker,
263
+ messages: flagValue.messages,
264
+ evaluationMetricKeys: flagValue.evaluationMetricKeys || []
265
+ };
266
+ }
267
+ };
268
+
269
+ // src/api/judge/Judge.ts
270
+ import Mustache from "mustache";
271
+
272
+ // src/api/judge/EvaluationSchemaBuilder.ts
273
+ var EvaluationSchemaBuilder = class {
274
+ static build(evaluationMetricKeys) {
275
+ return {
276
+ type: "object",
277
+ properties: {
278
+ evaluations: {
279
+ type: "object",
280
+ description: `Object containing evaluation results for ${evaluationMetricKeys.join(", ")} metrics`,
281
+ properties: this._buildKeyProperties(evaluationMetricKeys),
282
+ required: evaluationMetricKeys,
283
+ additionalProperties: false
284
+ }
285
+ },
286
+ required: ["evaluations"],
287
+ additionalProperties: false
288
+ };
289
+ }
290
+ static _buildKeyProperties(evaluationMetricKeys) {
291
+ return evaluationMetricKeys.reduce(
292
+ (acc, key) => {
293
+ acc[key] = this._buildKeySchema(key);
294
+ return acc;
295
+ },
296
+ {}
297
+ );
298
+ }
299
+ static _buildKeySchema(key) {
300
+ return {
301
+ type: "object",
302
+ properties: {
303
+ score: {
304
+ type: "number",
305
+ minimum: 0,
306
+ maximum: 1,
307
+ description: `Score between 0.0 and 1.0 for ${key}`
308
+ },
309
+ reasoning: {
310
+ type: "string",
311
+ description: `Reasoning behind the score for ${key}`
312
+ }
313
+ },
314
+ required: ["score", "reasoning"],
315
+ additionalProperties: false
316
+ };
317
+ }
318
+ };
319
+
320
+ // src/api/judge/Judge.ts
321
+ var Judge = class {
322
+ constructor(_aiConfig, _aiConfigTracker, _aiProvider, logger) {
323
+ this._aiConfig = _aiConfig;
324
+ this._aiConfigTracker = _aiConfigTracker;
325
+ this._aiProvider = _aiProvider;
326
+ this._logger = logger;
327
+ this._evaluationResponseStructure = EvaluationSchemaBuilder.build(
328
+ this._aiConfig.evaluationMetricKeys
329
+ );
330
+ }
331
+ /**
332
+ * Evaluates an AI response using the judge's configuration.
333
+ *
334
+ * @param input The input prompt or question that was provided to the AI
335
+ * @param output The AI-generated response to be evaluated
336
+ * @param samplingRate Sampling rate (0-1) to determine if evaluation should be processed (defaults to 1)
337
+ * @returns Promise that resolves to evaluation results or undefined if not sampled
338
+ */
339
+ async evaluate(input, output, samplingRate = 1) {
340
+ try {
341
+ if (!this._aiConfig.evaluationMetricKeys || this._aiConfig.evaluationMetricKeys.length === 0) {
342
+ this._logger?.warn(
343
+ "Judge configuration is missing required evaluationMetricKeys",
344
+ this._aiConfigTracker.getTrackData()
345
+ );
346
+ return void 0;
347
+ }
348
+ if (!this._aiConfig.messages) {
349
+ this._logger?.warn(
350
+ "Judge configuration must include messages",
351
+ this._aiConfigTracker.getTrackData()
352
+ );
353
+ return void 0;
354
+ }
355
+ if (Math.random() > samplingRate) {
356
+ this._logger?.debug(`Judge evaluation skipped due to sampling rate: ${samplingRate}`);
357
+ return void 0;
358
+ }
359
+ const messages = this._constructEvaluationMessages(input, output);
360
+ const response = await this._aiConfigTracker.trackMetricsOf(
361
+ (result) => result.metrics,
362
+ () => this._aiProvider.invokeStructuredModel(messages, this._evaluationResponseStructure)
363
+ );
364
+ let { success } = response.metrics;
365
+ const evals = this._parseEvaluationResponse(response.data);
366
+ if (Object.keys(evals).length !== this._aiConfig.evaluationMetricKeys.length) {
367
+ this._logger?.warn(
368
+ "Judge evaluation did not return all evaluations",
369
+ this._aiConfigTracker.getTrackData()
370
+ );
371
+ success = false;
372
+ }
373
+ return {
374
+ evals,
375
+ success,
376
+ judgeConfigKey: this._aiConfig.key
377
+ };
378
+ } catch (error) {
379
+ this._logger?.error("Judge evaluation failed:", error);
380
+ return {
381
+ evals: {},
382
+ success: false,
383
+ error: error instanceof Error ? error.message : "Unknown error",
384
+ judgeConfigKey: this._aiConfig.key
385
+ };
386
+ }
387
+ }
388
+ /**
389
+ * Evaluates an AI response from chat messages and response.
390
+ *
391
+ * @param messages Array of messages representing the conversation history
392
+ * @param response The AI response to be evaluated
393
+ * @param samplingRatio Sampling ratio (0-1) to determine if evaluation should be processed (defaults to 1)
394
+ * @returns Promise that resolves to evaluation results or undefined if not sampled
395
+ */
396
+ async evaluateMessages(messages, response, samplingRatio = 1) {
397
+ const input = messages.length === 0 ? "" : messages.map((msg) => msg.content).join("\r\n");
398
+ const output = response.message.content;
399
+ return this.evaluate(input, output, samplingRatio);
400
+ }
401
+ /**
402
+ * Returns the AI Config used by this judge.
403
+ */
404
+ getAIConfig() {
405
+ return this._aiConfig;
406
+ }
407
+ /**
408
+ * Returns the tracker associated with this judge.
409
+ */
410
+ getTracker() {
411
+ return this._aiConfigTracker;
412
+ }
413
+ /**
414
+ * Returns the AI provider used by this judge.
415
+ */
416
+ getProvider() {
417
+ return this._aiProvider;
418
+ }
419
+ /**
420
+ * Constructs evaluation messages by combining judge's config messages with input/output.
421
+ */
422
+ _constructEvaluationMessages(input, output) {
423
+ const messages = this._aiConfig.messages.map((msg) => ({
424
+ ...msg,
425
+ content: this._interpolateMessage(msg.content, {
426
+ message_history: input,
427
+ response_to_evaluate: output
428
+ })
429
+ }));
430
+ return messages;
431
+ }
432
+ /**
433
+ * Interpolates message content with variables using Mustache templating.
434
+ */
435
+ _interpolateMessage(content, variables) {
436
+ return Mustache.render(content, variables, void 0, { escape: (item) => item });
437
+ }
438
+ /**
439
+ * Parses the structured evaluation response from the AI provider.
440
+ */
441
+ _parseEvaluationResponse(data) {
442
+ const evaluations = data.evaluations;
443
+ const results = {};
444
+ if (!data.evaluations || typeof data.evaluations !== "object") {
445
+ this._logger?.warn("Invalid response: missing or invalid evaluations object");
446
+ return results;
447
+ }
448
+ this._aiConfig.evaluationMetricKeys.forEach((metricKey) => {
449
+ const evaluation = evaluations[metricKey];
450
+ if (!evaluation || typeof evaluation !== "object") {
451
+ this._logger?.warn(
452
+ `Missing evaluation for metric key: ${metricKey}`,
453
+ this._aiConfigTracker.getTrackData()
454
+ );
455
+ return;
456
+ }
457
+ const evalData = evaluation;
458
+ if (typeof evalData.score !== "number" || evalData.score < 0 || evalData.score > 1) {
459
+ this._logger?.warn(
460
+ `Invalid score evaluated for ${metricKey}: ${evalData.score}. Score must be a number between 0 and 1 inclusive`,
461
+ this._aiConfigTracker.getTrackData()
462
+ );
463
+ return;
464
+ }
465
+ if (typeof evalData.reasoning !== "string") {
466
+ this._logger?.warn(
467
+ `Invalid reasoning evaluated for ${metricKey}: ${evalData.reasoning}. Reasoning must be a string`,
468
+ this._aiConfigTracker.getTrackData()
469
+ );
470
+ return;
471
+ }
472
+ results[metricKey] = {
473
+ score: evalData.score,
474
+ reasoning: evalData.reasoning
475
+ };
476
+ });
477
+ return results;
478
+ }
479
+ };
480
+
481
+ // src/api/providers/AIProvider.ts
482
+ var AIProvider = class {
483
+ constructor(logger) {
484
+ this.logger = logger;
485
+ }
486
+ /**
487
+ * Invoke the chat model with an array of messages.
488
+ * This method should convert messages to provider format, invoke the model,
489
+ * and return a ChatResponse with the result and metrics.
490
+ *
491
+ * Default implementation takes no action and returns a placeholder response.
492
+ * Provider implementations should override this method.
493
+ *
494
+ * @param messages Array of LDMessage objects representing the conversation
495
+ * @returns Promise that resolves to a ChatResponse containing the model's response
496
+ */
497
+ async invokeModel(_messages) {
498
+ this.logger?.warn("invokeModel not implemented by this provider");
499
+ return {
500
+ message: {
501
+ role: "assistant",
502
+ content: ""
503
+ },
504
+ metrics: {
505
+ success: false,
506
+ usage: {
507
+ total: 0,
508
+ input: 0,
509
+ output: 0
510
+ }
511
+ }
512
+ };
513
+ }
514
+ /**
515
+ * Invoke the chat model with structured output support.
516
+ * This method should convert messages to provider format, invoke the model with
517
+ * structured output configuration, and return a structured response.
518
+ *
519
+ * Default implementation takes no action and returns a placeholder response.
520
+ * Provider implementations should override this method.
521
+ *
522
+ * @param messages Array of LDMessage objects representing the conversation
523
+ * @param responseStructure Dictionary of output configurations keyed by output name
524
+ * @returns Promise that resolves to a structured response
525
+ */
526
+ async invokeStructuredModel(_messages, _responseStructure) {
527
+ this.logger?.warn("invokeStructuredModel not implemented by this provider");
528
+ return {
529
+ data: {},
530
+ rawResponse: "",
531
+ metrics: {
532
+ success: false,
533
+ usage: {
534
+ total: 0,
535
+ input: 0,
536
+ output: 0
537
+ }
538
+ }
539
+ };
540
+ }
541
+ /**
542
+ * Static method that constructs an instance of the provider.
543
+ * Each provider implementation must provide their own static create method
544
+ * that accepts an AIConfig and returns a configured instance.
545
+ *
546
+ * @param aiConfig The LaunchDarkly AI configuration
547
+ * @param logger Optional logger for the provider
548
+ * @returns Promise that resolves to a configured provider instance
549
+ */
550
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
551
+ static async create(aiConfig, logger) {
552
+ throw new Error("Provider implementations must override the static create method");
553
+ }
554
+ };
555
+
556
+ // src/api/providers/AIProviderFactory.ts
557
+ var SUPPORTED_AI_PROVIDERS = [
558
+ "openai",
559
+ // Multi-provider packages should be last in the list
560
+ "langchain",
561
+ "vercel"
562
+ ];
563
+ var AIProviderFactory = class {
564
+ /**
565
+ * Create an AIProvider instance based on the AI configuration.
566
+ * This method attempts to load provider-specific implementations dynamically.
567
+ * Returns undefined if the provider is not supported.
568
+ *
569
+ * @param aiConfig The AI configuration
570
+ * @param logger Optional logger for logging provider initialization
571
+ * @param defaultAiProvider Optional default AI provider to use
572
+ */
573
+ static async create(aiConfig, logger, defaultAiProvider) {
574
+ const providerName = aiConfig.provider?.name?.toLowerCase();
575
+ const providersToTry = this._getProvidersToTry(defaultAiProvider, providerName);
576
+ for (const providerType of providersToTry) {
577
+ logger?.debug(
578
+ `Attempting to create AIProvider for: ${aiConfig.provider?.name} with provider type: ${providerType}`
579
+ );
580
+ const provider = await this._tryCreateProvider(providerType, aiConfig, logger);
581
+ if (provider) {
582
+ logger?.debug(`Successfully created AIProvider for: ${aiConfig.provider?.name}`);
583
+ return provider;
584
+ }
585
+ }
586
+ logger?.warn(
587
+ `Provider is not supported or failed to initialize: ${aiConfig.provider?.name ?? "unknown"}`
588
+ );
589
+ return void 0;
590
+ }
591
+ /**
592
+ * Determine which providers to try based on defaultAiProvider and providerName.
593
+ */
594
+ static _getProvidersToTry(defaultAiProvider, providerName) {
595
+ if (defaultAiProvider) {
596
+ return [defaultAiProvider];
597
+ }
598
+ const providerSet = /* @__PURE__ */ new Set();
599
+ if (providerName && SUPPORTED_AI_PROVIDERS.includes(providerName)) {
600
+ providerSet.add(providerName);
601
+ }
602
+ const multiProviderPackages = ["langchain", "vercel"];
603
+ multiProviderPackages.forEach((provider) => {
604
+ providerSet.add(provider);
605
+ });
606
+ return Array.from(providerSet);
607
+ }
608
+ /**
609
+ * Try to create a provider of the specified type.
610
+ */
611
+ static async _tryCreateProvider(providerType, aiConfig, logger) {
612
+ try {
613
+ let module;
614
+ switch (providerType) {
615
+ case "openai": {
616
+ module = await import("@launchdarkly/server-sdk-ai-openai");
617
+ const provider = await module.OpenAIProvider.create(aiConfig, logger);
618
+ return provider;
619
+ }
620
+ case "langchain": {
621
+ module = await import("@launchdarkly/server-sdk-ai-langchain");
622
+ const provider = await module.LangChainProvider.create(aiConfig, logger);
623
+ return provider;
624
+ }
625
+ case "vercel": {
626
+ module = await import("@launchdarkly/server-sdk-ai-vercel");
627
+ const provider = await module.VercelProvider.create(aiConfig, logger);
628
+ return provider;
629
+ }
630
+ default:
631
+ return void 0;
632
+ }
633
+ } catch (error) {
634
+ logger?.warn(
635
+ `Unable to create AIProvider. Check that you have installed the correct package. ${error.message}`
636
+ );
637
+ return void 0;
638
+ }
639
+ }
640
+ };
641
+
642
+ // src/api/metrics/BedrockTokenUsage.ts
643
+ function createBedrockTokenUsage(data) {
644
+ return {
645
+ total: data.totalTokens || 0,
646
+ input: data.inputTokens || 0,
647
+ output: data.outputTokens || 0
648
+ };
649
+ }
650
+
651
+ // src/api/metrics/OpenAiUsage.ts
652
+ function createOpenAiUsage(data) {
653
+ return {
654
+ total: data.total_tokens ?? 0,
655
+ input: data.prompt_tokens ?? 0,
656
+ output: data.completion_tokens ?? 0
657
+ };
658
+ }
659
+
660
+ // src/api/metrics/LDFeedbackKind.ts
661
+ var LDFeedbackKind = /* @__PURE__ */ ((LDFeedbackKind2) => {
662
+ LDFeedbackKind2["Positive"] = "positive";
663
+ LDFeedbackKind2["Negative"] = "negative";
664
+ return LDFeedbackKind2;
665
+ })(LDFeedbackKind || {});
666
+
667
+ // src/api/metrics/VercelAISDKTokenUsage.ts
668
+ function createVercelAISDKTokenUsage(data) {
669
+ return {
670
+ total: data.totalTokens ?? 0,
671
+ input: data.inputTokens ?? data.promptTokens ?? 0,
672
+ output: data.outputTokens ?? data.completionTokens ?? 0
673
+ };
674
+ }
675
+
676
+ // src/sdkInfo.ts
677
+ var aiSdkName = "@launchdarkly/server-sdk-ai";
678
+ var aiSdkVersion = "0.15.0";
679
+
680
+ // src/LDAIConfigTrackerImpl.ts
681
+ var LDAIConfigTrackerImpl = class {
682
+ constructor(_ldClient, _configKey, _variationKey, _version, _modelName, _providerName, _context) {
683
+ this._ldClient = _ldClient;
684
+ this._configKey = _configKey;
685
+ this._variationKey = _variationKey;
686
+ this._version = _version;
687
+ this._modelName = _modelName;
688
+ this._providerName = _providerName;
689
+ this._context = _context;
690
+ this._trackedMetrics = {};
691
+ }
692
+ getTrackData() {
693
+ return {
694
+ variationKey: this._variationKey,
695
+ configKey: this._configKey,
696
+ version: this._version,
697
+ modelName: this._modelName,
698
+ providerName: this._providerName,
699
+ aiSdkName,
700
+ aiSdkVersion
701
+ };
702
+ }
703
+ trackDuration(duration) {
704
+ this._trackedMetrics.durationMs = duration;
705
+ this._ldClient.track("$ld:ai:duration:total", this._context, this.getTrackData(), duration);
706
+ }
707
+ async trackDurationOf(func) {
708
+ const startTime = Date.now();
709
+ try {
710
+ const result = await func();
711
+ return result;
712
+ } finally {
713
+ const endTime = Date.now();
714
+ const duration = endTime - startTime;
715
+ this.trackDuration(duration);
716
+ }
717
+ }
718
+ trackTimeToFirstToken(timeToFirstTokenMs) {
719
+ this._trackedMetrics.timeToFirstTokenMs = timeToFirstTokenMs;
720
+ this._ldClient.track(
721
+ "$ld:ai:tokens:ttf",
722
+ this._context,
723
+ this.getTrackData(),
724
+ timeToFirstTokenMs
725
+ );
726
+ }
727
+ trackEvalScores(scores) {
728
+ Object.entries(scores).forEach(([metricKey, evalScore]) => {
729
+ this._ldClient.track(metricKey, this._context, this.getTrackData(), evalScore.score);
730
+ });
731
+ }
732
+ trackJudgeResponse(response) {
733
+ Object.entries(response.evals).forEach(([metricKey, evalScore]) => {
734
+ this._ldClient.track(
735
+ metricKey,
736
+ this._context,
737
+ { ...this.getTrackData(), judgeConfigKey: response.judgeConfigKey },
738
+ evalScore.score
739
+ );
740
+ });
741
+ }
742
+ trackFeedback(feedback) {
743
+ this._trackedMetrics.feedback = feedback;
744
+ if (feedback.kind === "positive" /* Positive */) {
745
+ this._ldClient.track("$ld:ai:feedback:user:positive", this._context, this.getTrackData(), 1);
746
+ } else if (feedback.kind === "negative" /* Negative */) {
747
+ this._ldClient.track("$ld:ai:feedback:user:negative", this._context, this.getTrackData(), 1);
748
+ }
749
+ }
750
+ trackSuccess() {
751
+ this._trackedMetrics.success = true;
752
+ this._ldClient.track("$ld:ai:generation:success", this._context, this.getTrackData(), 1);
753
+ }
754
+ trackError() {
755
+ this._trackedMetrics.success = false;
756
+ this._ldClient.track("$ld:ai:generation:error", this._context, this.getTrackData(), 1);
757
+ }
758
+ async trackMetricsOf(metricsExtractor, func) {
759
+ let result;
760
+ try {
761
+ result = await this.trackDurationOf(func);
762
+ } catch (err) {
763
+ this.trackError();
764
+ throw err;
765
+ }
766
+ const metrics = metricsExtractor(result);
767
+ if (metrics.success) {
768
+ this.trackSuccess();
769
+ } else {
770
+ this.trackError();
771
+ }
772
+ if (metrics.usage) {
773
+ this.trackTokens(metrics.usage);
774
+ }
775
+ return result;
776
+ }
777
+ trackStreamMetricsOf(streamCreator, metricsExtractor) {
778
+ const startTime = Date.now();
779
+ try {
780
+ const stream = streamCreator();
781
+ this._trackStreamMetricsInBackground(stream, metricsExtractor, startTime);
782
+ return stream;
783
+ } catch (error) {
784
+ this.trackDuration(Date.now() - startTime);
785
+ this.trackError();
786
+ throw error;
787
+ }
788
+ }
789
+ async _trackStreamMetricsInBackground(stream, metricsExtractor, startTime) {
790
+ try {
791
+ const metrics = await metricsExtractor(stream);
792
+ if (metrics.success) {
793
+ this.trackSuccess();
794
+ } else {
795
+ this.trackError();
796
+ }
797
+ if (metrics.usage) {
798
+ this.trackTokens(metrics.usage);
799
+ }
800
+ } catch (error) {
801
+ this.trackError();
802
+ } finally {
803
+ this.trackDuration(Date.now() - startTime);
804
+ }
805
+ }
806
+ async trackOpenAIMetrics(func) {
807
+ try {
808
+ const result = await this.trackDurationOf(func);
809
+ this.trackSuccess();
810
+ if (result.usage) {
811
+ this.trackTokens(createOpenAiUsage(result.usage));
812
+ }
813
+ return result;
814
+ } catch (err) {
815
+ this.trackError();
816
+ throw err;
817
+ }
818
+ }
819
+ trackBedrockConverseMetrics(res) {
820
+ if (res.$metadata?.httpStatusCode === 200) {
821
+ this.trackSuccess();
822
+ } else if (res.$metadata?.httpStatusCode && res.$metadata.httpStatusCode >= 400) {
823
+ this.trackError();
824
+ }
825
+ if (res.metrics && res.metrics.latencyMs) {
826
+ this.trackDuration(res.metrics.latencyMs);
827
+ }
828
+ if (res.usage) {
829
+ this.trackTokens(createBedrockTokenUsage(res.usage));
830
+ }
831
+ return res;
832
+ }
833
+ async trackVercelAISDKGenerateTextMetrics(func) {
834
+ try {
835
+ const result = await this.trackDurationOf(func);
836
+ this.trackSuccess();
837
+ if (result.usage) {
838
+ this.trackTokens(createVercelAISDKTokenUsage(result.usage));
839
+ }
840
+ return result;
841
+ } catch (err) {
842
+ this.trackError();
843
+ throw err;
844
+ }
845
+ }
846
+ trackTokens(tokens) {
847
+ this._trackedMetrics.tokens = tokens;
848
+ const trackData = this.getTrackData();
849
+ if (tokens.total > 0) {
850
+ this._ldClient.track("$ld:ai:tokens:total", this._context, trackData, tokens.total);
851
+ }
852
+ if (tokens.input > 0) {
853
+ this._ldClient.track("$ld:ai:tokens:input", this._context, trackData, tokens.input);
854
+ }
855
+ if (tokens.output > 0) {
856
+ this._ldClient.track("$ld:ai:tokens:output", this._context, trackData, tokens.output);
857
+ }
858
+ }
859
+ /**
860
+ * Get a summary of the tracked metrics.
861
+ */
862
+ getSummary() {
863
+ return { ...this._trackedMetrics };
864
+ }
865
+ };
866
+
867
+ // src/LDAIClientImpl.ts
868
+ var TRACK_CONFIG_SINGLE = "$ld:ai:config:function:single";
869
+ var TRACK_CONFIG_CREATE_CHAT = "$ld:ai:config:function:createChat";
870
+ var TRACK_JUDGE_SINGLE = "$ld:ai:judge:function:single";
871
+ var TRACK_JUDGE_CREATE = "$ld:ai:judge:function:createJudge";
872
+ var TRACK_AGENT_SINGLE = "$ld:ai:agent:function:single";
873
+ var TRACK_AGENT_MULTIPLE = "$ld:ai:agent:function:multiple";
874
+ var LDAIClientImpl = class {
875
+ constructor(_ldClient) {
876
+ this._ldClient = _ldClient;
877
+ this._logger = _ldClient.logger;
878
+ }
879
+ _interpolateTemplate(template, variables) {
880
+ return Mustache2.render(template, variables, void 0, { escape: (item) => item });
881
+ }
882
+ async _evaluate(key, context, defaultValue, mode, variables) {
883
+ const ldFlagValue = LDAIConfigUtils.toFlagValue(defaultValue, mode);
884
+ const value = await this._ldClient.variation(key, context, ldFlagValue);
885
+ const flagMode = value._ldMeta?.mode ?? "completion";
886
+ if (flagMode !== mode) {
887
+ this._logger?.warn(
888
+ `AI Config mode mismatch for ${key}: expected ${mode}, got ${flagMode}. Returning disabled config.`
889
+ );
890
+ return LDAIConfigUtils.createDisabledConfig(key, mode);
891
+ }
892
+ const tracker = new LDAIConfigTrackerImpl(
893
+ this._ldClient,
894
+ key,
895
+ // eslint-disable-next-line no-underscore-dangle
896
+ value._ldMeta?.variationKey ?? "",
897
+ // eslint-disable-next-line no-underscore-dangle
898
+ value._ldMeta?.version ?? 1,
899
+ value.model?.name ?? "",
900
+ value.provider?.name ?? "",
901
+ context
902
+ );
903
+ const config = LDAIConfigUtils.fromFlagValue(key, value, tracker);
904
+ return this._applyInterpolation(config, context, variables);
905
+ }
906
+ _applyInterpolation(config, context, variables) {
907
+ const allVariables = { ...variables, ldctx: context };
908
+ if ("messages" in config && config.messages) {
909
+ return {
910
+ ...config,
911
+ messages: config.messages.map((entry) => ({
912
+ ...entry,
913
+ content: this._interpolateTemplate(entry.content, allVariables)
914
+ }))
915
+ };
916
+ }
917
+ if ("instructions" in config && config.instructions) {
918
+ return {
919
+ ...config,
920
+ instructions: this._interpolateTemplate(config.instructions, allVariables)
921
+ };
922
+ }
923
+ return config;
924
+ }
925
+ async _initializeJudges(judgeConfigs, context, variables, defaultAiProvider) {
926
+ const judges = {};
927
+ const judgePromises = judgeConfigs.map(async (judgeConfig) => {
928
+ const judge = await this.createJudge(
929
+ judgeConfig.key,
930
+ context,
931
+ { enabled: false },
932
+ variables,
933
+ defaultAiProvider
934
+ );
935
+ return judge ? { key: judgeConfig.key, judge } : null;
936
+ });
937
+ const results = await Promise.all(judgePromises);
938
+ results.forEach((result) => {
939
+ if (result) {
940
+ judges[result.key] = result.judge;
941
+ }
942
+ });
943
+ return judges;
944
+ }
945
+ async completionConfig(key, context, defaultValue, variables) {
946
+ this._ldClient.track(TRACK_CONFIG_SINGLE, context, key, 1);
947
+ const config = await this._evaluate(key, context, defaultValue, "completion", variables);
948
+ return config;
949
+ }
950
+ /**
951
+ * @deprecated Use `completionConfig` instead. This method will be removed in a future version.
952
+ */
953
+ async config(key, context, defaultValue, variables) {
954
+ return this.completionConfig(key, context, defaultValue, variables);
955
+ }
956
+ async judgeConfig(key, context, defaultValue, variables) {
957
+ this._ldClient.track(TRACK_JUDGE_SINGLE, context, key, 1);
958
+ const config = await this._evaluate(key, context, defaultValue, "judge", variables);
959
+ return config;
960
+ }
961
+ async agentConfig(key, context, defaultValue, variables) {
962
+ this._ldClient.track(TRACK_AGENT_SINGLE, context, key, 1);
963
+ const config = await this._evaluate(key, context, defaultValue, "agent", variables);
964
+ return config;
965
+ }
966
+ /**
967
+ * @deprecated Use `agentConfig` instead. This method will be removed in a future version.
968
+ */
969
+ async agent(key, context, defaultValue, variables) {
970
+ return this.agentConfig(key, context, defaultValue, variables);
971
+ }
972
+ async agentConfigs(agentConfigs, context) {
973
+ this._ldClient.track(TRACK_AGENT_MULTIPLE, context, agentConfigs.length, agentConfigs.length);
974
+ const agents = {};
975
+ await Promise.all(
976
+ agentConfigs.map(async (config) => {
977
+ const agent = await this._evaluate(
978
+ config.key,
979
+ context,
980
+ config.defaultValue,
981
+ "agent",
982
+ config.variables
983
+ );
984
+ agents[config.key] = agent;
985
+ })
986
+ );
987
+ return agents;
988
+ }
989
+ /**
990
+ * @deprecated Use `agentConfigs` instead. This method will be removed in a future version.
991
+ */
992
+ async agents(agentConfigs, context) {
993
+ return this.agentConfigs(agentConfigs, context);
994
+ }
995
+ async createChat(key, context, defaultValue, variables, defaultAiProvider) {
996
+ this._ldClient.track(TRACK_CONFIG_CREATE_CHAT, context, key, 1);
997
+ const config = await this.completionConfig(key, context, defaultValue, variables);
998
+ if (!config.enabled || !config.tracker) {
999
+ this._logger?.info(`Chat configuration is disabled: ${key}`);
1000
+ return void 0;
1001
+ }
1002
+ const provider = await AIProviderFactory.create(config, this._logger, defaultAiProvider);
1003
+ if (!provider) {
1004
+ return void 0;
1005
+ }
1006
+ const judges = await this._initializeJudges(
1007
+ config.judgeConfiguration?.judges ?? [],
1008
+ context,
1009
+ variables,
1010
+ defaultAiProvider
1011
+ );
1012
+ return new TrackedChat(config, config.tracker, provider, judges, this._logger);
1013
+ }
1014
+ async createJudge(key, context, defaultValue, variables, defaultAiProvider) {
1015
+ this._ldClient.track(TRACK_JUDGE_CREATE, context, key, 1);
1016
+ try {
1017
+ if (variables?.message_history !== void 0) {
1018
+ this._logger?.warn(
1019
+ "The variable 'message_history' is reserved by the judge and will be ignored."
1020
+ );
1021
+ }
1022
+ if (variables?.response_to_evaluate !== void 0) {
1023
+ this._logger?.warn(
1024
+ "The variable 'response_to_evaluate' is reserved by the judge and will be ignored."
1025
+ );
1026
+ }
1027
+ const extendedVariables = {
1028
+ ...variables,
1029
+ message_history: "{{message_history}}",
1030
+ response_to_evaluate: "{{response_to_evaluate}}"
1031
+ };
1032
+ const judgeConfig = await this.judgeConfig(key, context, defaultValue, extendedVariables);
1033
+ if (!judgeConfig.enabled || !judgeConfig.tracker) {
1034
+ this._logger?.info(`Judge configuration is disabled: ${key}`);
1035
+ return void 0;
1036
+ }
1037
+ const provider = await AIProviderFactory.create(judgeConfig, this._logger, defaultAiProvider);
1038
+ if (!provider) {
1039
+ return void 0;
1040
+ }
1041
+ return new Judge(judgeConfig, judgeConfig.tracker, provider, this._logger);
1042
+ } catch (error) {
1043
+ this._logger?.error(`Failed to initialize judge ${key}:`, error);
1044
+ return void 0;
1045
+ }
1046
+ }
1047
+ /**
1048
+ * @deprecated Use `createChat` instead. This method will be removed in a future version.
1049
+ */
1050
+ async initChat(key, context, defaultValue, variables, defaultAiProvider) {
1051
+ return this.createChat(key, context, defaultValue, variables, defaultAiProvider);
1052
+ }
1053
+ };
1054
+
1055
+ // src/index.ts
1056
+ function initAi(ldClient) {
1057
+ return new LDAIClientImpl(ldClient);
1058
+ }
1059
+ export {
1060
+ AIProvider,
1061
+ AIProviderFactory,
1062
+ Judge,
1063
+ LDFeedbackKind,
1064
+ SUPPORTED_AI_PROVIDERS,
1065
+ TrackedChat,
1066
+ createBedrockTokenUsage,
1067
+ createOpenAiUsage,
1068
+ createVercelAISDKTokenUsage,
1069
+ initAi
1070
+ };
1071
+ //# sourceMappingURL=index.js.map