@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
@@ -1,278 +0,0 @@
1
- import { LDContext } from '@launchdarkly/js-server-sdk-common';
2
-
3
- import { name as aiSdkName, version as aiSdkVersion } from '../package.json';
4
- import { LDAIConfigTracker } from './api/config';
5
- import { LDAIMetricSummary } from './api/config/LDAIConfigTracker';
6
- import { EvalScore } from './api/judge/types';
7
- import {
8
- createBedrockTokenUsage,
9
- createOpenAiUsage,
10
- createVercelAISDKTokenUsage,
11
- LDAIMetrics,
12
- LDFeedbackKind,
13
- LDTokenUsage,
14
- } from './api/metrics';
15
- import { LDClientMin } from './LDClientMin';
16
-
17
- export class LDAIConfigTrackerImpl implements LDAIConfigTracker {
18
- private _trackedMetrics: LDAIMetricSummary = {};
19
-
20
- constructor(
21
- private _ldClient: LDClientMin,
22
- private _configKey: string,
23
- private _variationKey: string,
24
- private _version: number,
25
- private _modelName: string,
26
- private _providerName: string,
27
- private _context: LDContext,
28
- ) {}
29
-
30
- getTrackData(): {
31
- variationKey: string;
32
- configKey: string;
33
- version: number;
34
- modelName: string;
35
- providerName: string;
36
- aiSdkName: string;
37
- aiSdkVersion: string;
38
- } {
39
- return {
40
- variationKey: this._variationKey,
41
- configKey: this._configKey,
42
- version: this._version,
43
- modelName: this._modelName,
44
- providerName: this._providerName,
45
- aiSdkName,
46
- aiSdkVersion,
47
- };
48
- }
49
-
50
- trackDuration(duration: number): void {
51
- this._trackedMetrics.durationMs = duration;
52
- this._ldClient.track('$ld:ai:duration:total', this._context, this.getTrackData(), duration);
53
- }
54
-
55
- async trackDurationOf<TRes>(func: () => Promise<TRes>): Promise<TRes> {
56
- const startTime = Date.now();
57
- try {
58
- // Be sure to await here so that we can track the duration of the function and also handle errors.
59
- const result = await func();
60
- return result;
61
- } finally {
62
- const endTime = Date.now();
63
- const duration = endTime - startTime; // duration in milliseconds
64
- this.trackDuration(duration);
65
- }
66
- }
67
-
68
- trackTimeToFirstToken(timeToFirstTokenMs: number) {
69
- this._trackedMetrics.timeToFirstTokenMs = timeToFirstTokenMs;
70
- this._ldClient.track(
71
- '$ld:ai:tokens:ttf',
72
- this._context,
73
- this.getTrackData(),
74
- timeToFirstTokenMs,
75
- );
76
- }
77
-
78
- trackEvalScores(scores: Record<string, EvalScore>) {
79
- // Track each evaluation score individually
80
- Object.entries(scores).forEach(([metricKey, evalScore]) => {
81
- this._ldClient.track(metricKey, this._context, this.getTrackData(), evalScore.score);
82
- });
83
- }
84
-
85
- trackFeedback(feedback: { kind: LDFeedbackKind }): void {
86
- this._trackedMetrics.feedback = feedback;
87
- if (feedback.kind === LDFeedbackKind.Positive) {
88
- this._ldClient.track('$ld:ai:feedback:user:positive', this._context, this.getTrackData(), 1);
89
- } else if (feedback.kind === LDFeedbackKind.Negative) {
90
- this._ldClient.track('$ld:ai:feedback:user:negative', this._context, this.getTrackData(), 1);
91
- }
92
- }
93
-
94
- trackSuccess(): void {
95
- this._trackedMetrics.success = true;
96
- this._ldClient.track('$ld:ai:generation:success', this._context, this.getTrackData(), 1);
97
- }
98
-
99
- trackError(): void {
100
- this._trackedMetrics.success = false;
101
- this._ldClient.track('$ld:ai:generation:error', this._context, this.getTrackData(), 1);
102
- }
103
-
104
- async trackMetricsOf<TRes>(
105
- metricsExtractor: (result: TRes) => LDAIMetrics,
106
- func: () => Promise<TRes>,
107
- ): Promise<TRes> {
108
- let result: TRes;
109
-
110
- try {
111
- result = await this.trackDurationOf(func);
112
- } catch (err) {
113
- this.trackError();
114
- throw err;
115
- }
116
-
117
- // Extract metrics after successful AI call
118
- const metrics = metricsExtractor(result);
119
-
120
- // Track success/error based on metrics
121
- if (metrics.success) {
122
- this.trackSuccess();
123
- } else {
124
- this.trackError();
125
- }
126
-
127
- // Track token usage if available
128
- if (metrics.usage) {
129
- this.trackTokens(metrics.usage);
130
- }
131
-
132
- return result;
133
- }
134
-
135
- trackStreamMetricsOf<TStream>(
136
- streamCreator: () => TStream,
137
- metricsExtractor: (stream: TStream) => Promise<LDAIMetrics>,
138
- ): TStream {
139
- const startTime = Date.now();
140
-
141
- try {
142
- // Create the stream synchronously
143
- const stream = streamCreator();
144
-
145
- // Start background metrics tracking (fire and forget)
146
- this._trackStreamMetricsInBackground(stream, metricsExtractor, startTime);
147
-
148
- // Return stream immediately for consumption
149
- return stream;
150
- } catch (error) {
151
- // Track error if stream creation fails
152
- this.trackDuration(Date.now() - startTime);
153
- this.trackError();
154
- throw error;
155
- }
156
- }
157
-
158
- private async _trackStreamMetricsInBackground<TStream>(
159
- stream: TStream,
160
- metricsExtractor: (stream: TStream) => Promise<LDAIMetrics>,
161
- startTime: number,
162
- ): Promise<void> {
163
- try {
164
- // Wait for metrics to be available
165
- const metrics = await metricsExtractor(stream);
166
-
167
- // Track success/error based on metrics
168
- if (metrics.success) {
169
- this.trackSuccess();
170
- } else {
171
- this.trackError();
172
- }
173
-
174
- // Track token usage if available
175
- if (metrics.usage) {
176
- this.trackTokens(metrics.usage);
177
- }
178
- } catch (error) {
179
- // If metrics extraction fails, track error
180
- this.trackError();
181
- } finally {
182
- // Track duration regardless of success/error
183
- this.trackDuration(Date.now() - startTime);
184
- }
185
- }
186
-
187
- async trackOpenAIMetrics<
188
- TRes extends {
189
- usage?: {
190
- total_tokens?: number;
191
- prompt_tokens?: number;
192
- completion_tokens?: number;
193
- };
194
- },
195
- >(func: () => Promise<TRes>): Promise<TRes> {
196
- try {
197
- const result = await this.trackDurationOf(func);
198
- this.trackSuccess();
199
- if (result.usage) {
200
- this.trackTokens(createOpenAiUsage(result.usage));
201
- }
202
- return result;
203
- } catch (err) {
204
- this.trackError();
205
- throw err;
206
- }
207
- }
208
-
209
- trackBedrockConverseMetrics<
210
- TRes extends {
211
- $metadata: { httpStatusCode?: number };
212
- metrics?: { latencyMs?: number };
213
- usage?: {
214
- inputTokens?: number;
215
- outputTokens?: number;
216
- totalTokens?: number;
217
- };
218
- },
219
- >(res: TRes): TRes {
220
- if (res.$metadata?.httpStatusCode === 200) {
221
- this.trackSuccess();
222
- } else if (res.$metadata?.httpStatusCode && res.$metadata.httpStatusCode >= 400) {
223
- this.trackError();
224
- }
225
- if (res.metrics && res.metrics.latencyMs) {
226
- this.trackDuration(res.metrics.latencyMs);
227
- }
228
- if (res.usage) {
229
- this.trackTokens(createBedrockTokenUsage(res.usage));
230
- }
231
- return res;
232
- }
233
-
234
- async trackVercelAISDKGenerateTextMetrics<
235
- TRes extends {
236
- usage?: {
237
- totalTokens?: number;
238
- inputTokens?: number;
239
- promptTokens?: number;
240
- outputTokens?: number;
241
- completionTokens?: number;
242
- };
243
- },
244
- >(func: () => Promise<TRes>): Promise<TRes> {
245
- try {
246
- const result = await this.trackDurationOf(func);
247
- this.trackSuccess();
248
- if (result.usage) {
249
- this.trackTokens(createVercelAISDKTokenUsage(result.usage));
250
- }
251
- return result;
252
- } catch (err) {
253
- this.trackError();
254
- throw err;
255
- }
256
- }
257
-
258
- trackTokens(tokens: LDTokenUsage): void {
259
- this._trackedMetrics.tokens = tokens;
260
- const trackData = this.getTrackData();
261
- if (tokens.total > 0) {
262
- this._ldClient.track('$ld:ai:tokens:total', this._context, trackData, tokens.total);
263
- }
264
- if (tokens.input > 0) {
265
- this._ldClient.track('$ld:ai:tokens:input', this._context, trackData, tokens.input);
266
- }
267
- if (tokens.output > 0) {
268
- this._ldClient.track('$ld:ai:tokens:output', this._context, trackData, tokens.output);
269
- }
270
- }
271
-
272
- /**
273
- * Get a summary of the tracked metrics.
274
- */
275
- getSummary(): LDAIMetricSummary {
276
- return { ...this._trackedMetrics };
277
- }
278
- }
@@ -1,18 +0,0 @@
1
- import { LDContext, LDFlagValue, LDLogger } from '@launchdarkly/js-server-sdk-common';
2
-
3
- /**
4
- * Interface which represents the required interface components for a sever SDK
5
- * to work with the AI SDK.
6
- */
7
- export interface LDClientMin {
8
- variation(
9
- key: string,
10
- context: LDContext,
11
- defaultValue: LDFlagValue,
12
- callback?: (err: any, res: LDFlagValue) => void,
13
- ): Promise<LDFlagValue>;
14
-
15
- track(key: string, context: LDContext, data?: any, metricValue?: number): void;
16
-
17
- readonly logger?: LDLogger;
18
- }
@@ -1,325 +0,0 @@
1
- import { LDContext } from '@launchdarkly/js-server-sdk-common';
2
-
3
- import { TrackedChat } from './chat';
4
- import {
5
- LDAIAgentConfig,
6
- LDAIAgentConfigDefault,
7
- LDAIAgentRequestConfig,
8
- LDAICompletionConfig,
9
- LDAICompletionConfigDefault,
10
- LDAIJudgeConfig,
11
- LDAIJudgeConfigDefault,
12
- } from './config';
13
- import { Judge } from './judge/Judge';
14
- import { SupportedAIProvider } from './providers';
15
-
16
- /**
17
- * Interface for performing AI operations using LaunchDarkly.
18
- */
19
- export interface LDAIClient {
20
- /**
21
- * Retrieves and processes a completion AI Config based on the provided key, LaunchDarkly context,
22
- * and variables. This includes the model configuration and the customized messages.
23
- *
24
- * @param key The key of the AI Config.
25
- * @param context The LaunchDarkly context object that contains relevant information about the
26
- * current environment, user, or session. This context may influence how the configuration is
27
- * processed or personalized.
28
- * @param defaultValue A fallback value containing model configuration and messages. This will
29
- * be used if the configuration is not available from LaunchDarkly.
30
- * @param variables A map of key-value pairs representing dynamic variables to be injected into
31
- * the message content. The keys correspond to placeholders within the template, and the values
32
- * are the corresponding replacements.
33
- *
34
- * @returns The AI `config`, customized `messages`, and a `tracker`. If the configuration cannot be accessed from
35
- * LaunchDarkly, then the return value will include information from the `defaultValue`. The returned `tracker` can
36
- * be used to track AI operation metrics (latency, token usage, etc.).
37
- *
38
- * @example
39
- * ```
40
- * const key = "welcome_prompt";
41
- * const context = {...};
42
- * const variables = {username: 'john'};
43
- * const defaultValue = {
44
- * enabled: false,
45
- * model: { name: 'gpt-4' },
46
- * provider: { name: 'openai' },
47
- * };
48
- *
49
- * const result = completionConfig(key, context, defaultValue, variables);
50
- * // Output:
51
- * {
52
- * enabled: true,
53
- * config: {
54
- * modelId: "gpt-4o",
55
- * temperature: 0.2,
56
- * maxTokens: 4096,
57
- * userDefinedKey: "myValue",
58
- * },
59
- * messages: [
60
- * {
61
- * role: "system",
62
- * content: "You are an amazing GPT."
63
- * },
64
- * {
65
- * role: "user",
66
- * content: "Explain how you're an amazing GPT."
67
- * }
68
- * ],
69
- * tracker: ...
70
- * }
71
- * ```
72
- */
73
- completionConfig(
74
- key: string,
75
- context: LDContext,
76
- defaultValue: LDAICompletionConfigDefault,
77
- variables?: Record<string, unknown>,
78
- ): Promise<LDAICompletionConfig>;
79
-
80
- /**
81
- * @deprecated Use `completionConfig` instead. This method will be removed in a future version.
82
- */
83
- config(
84
- key: string,
85
- context: LDContext,
86
- defaultValue: LDAICompletionConfigDefault,
87
- variables?: Record<string, unknown>,
88
- ): Promise<LDAICompletionConfig>;
89
-
90
- /**
91
- * Retrieves and processes a single AI Config agent based on the provided key, LaunchDarkly context,
92
- * and variables. This includes the model configuration and the customized instructions.
93
- *
94
- * @param key The key of the AI Config agent.
95
- * @param context The LaunchDarkly context object that contains relevant information about the
96
- * current environment, user, or session. This context may influence how the configuration is
97
- * processed or personalized.
98
- * @param defaultValue A fallback value containing model configuration and instructions.
99
- * @param variables A map of key-value pairs representing dynamic variables to be injected into
100
- * the instructions. The keys correspond to placeholders within the template, and the values
101
- * are the corresponding replacements.
102
- *
103
- * @returns An AI agent with customized `instructions` and a `tracker`. If the configuration
104
- * cannot be accessed from LaunchDarkly, then the return value will include information from the
105
- * `defaultValue`. The returned `tracker` can be used to track AI operation metrics (latency, token usage, etc.).
106
- *
107
- * @example
108
- * ```
109
- * const key = "research_agent";
110
- * const context = {...};
111
- * const variables = { topic: 'climate change' };
112
- * const agentConfig = await client.agentConfig(key, context, {
113
- * enabled: true,
114
- * model: { name: 'gpt-4' },
115
- * provider: { name: 'openai' },
116
- * instructions: 'You are a research assistant.',
117
- * }, variables);
118
- *
119
- * const researchResult = agentConfig.instructions; // Interpolated instructions
120
- * agentConfig.tracker.trackSuccess();
121
- * ```
122
- */
123
- agentConfig(
124
- key: string,
125
- context: LDContext,
126
- defaultValue: LDAIAgentConfigDefault,
127
- variables?: Record<string, unknown>,
128
- ): Promise<LDAIAgentConfig>;
129
-
130
- /**
131
- * @deprecated Use `agentConfig` instead. This method will be removed in a future version.
132
- */
133
- agent(
134
- key: string,
135
- context: LDContext,
136
- defaultValue: LDAIAgentConfigDefault,
137
- variables?: Record<string, unknown>,
138
- ): Promise<LDAIAgentConfig>;
139
-
140
- /**
141
- * Retrieves and processes a Judge AI Config based on the provided key, LaunchDarkly context,
142
- * and variables. This includes the model configuration and the customized messages for evaluation.
143
- *
144
- * @param key The key of the Judge AI Config.
145
- * @param context The LaunchDarkly context object that contains relevant information about the
146
- * current environment, user, or session. This context may influence how the configuration is
147
- * processed or personalized.
148
- * @param defaultValue A fallback value containing model configuration and messages. This will
149
- * be used if the configuration is not available from LaunchDarkly.
150
- * @param variables Optional variables for template interpolation in messages and instructions.
151
- * @returns A promise that resolves to a tracked judge configuration.
152
- *
153
- * @example
154
- * ```typescript
155
- * const judgeConf = await client.judgeConfig(key, context, {
156
- * enabled: true,
157
- * model: { name: 'gpt-4' },
158
- * provider: { name: 'openai' },
159
- * evaluationMetricKeys: ['$ld:ai:judge:relevance'],
160
- * messages: [{ role: 'system', content: 'You are a relevance judge.' }]
161
- * }, variables);
162
- *
163
- * const config = judgeConf.config; // Interpolated configuration
164
- * judgeConf.tracker.trackSuccess();
165
- * ```
166
- */
167
- judgeConfig(
168
- key: string,
169
- context: LDContext,
170
- defaultValue: LDAIJudgeConfigDefault,
171
- variables?: Record<string, unknown>,
172
- ): Promise<LDAIJudgeConfig>;
173
-
174
- /**
175
- * Retrieves and processes multiple AI Config agents based on the provided agent configurations
176
- * and LaunchDarkly context. This includes the model configuration and the customized instructions.
177
- *
178
- * @param agentConfigs An array of agent configurations, each containing the agent key, default configuration,
179
- * and variables for instructions interpolation.
180
- * @param context The LaunchDarkly context object that contains relevant information about the
181
- * current environment, user, or session. This context may influence how the configuration is
182
- * processed or personalized.
183
- *
184
- * @returns A map of agent keys to their respective AI agents with customized `instructions` and `tracker`.
185
- * If a configuration cannot be accessed from LaunchDarkly, then the return value will include information
186
- * from the respective `defaultValue`. The returned `tracker` can be used to track AI operation metrics
187
- * (latency, token usage, etc.).
188
- *
189
- * @example
190
- * ```
191
- * const agentConfigsList = [
192
- * {
193
- * key: 'research_agent',
194
- * defaultValue: {
195
- * enabled: true,
196
- * model: { name: 'gpt-4' },
197
- * provider: { name: 'openai' },
198
- * instructions: 'You are a research assistant.'
199
- * },
200
- * variables: { topic: 'climate change' }
201
- * },
202
- * {
203
- * key: 'writing_agent',
204
- * defaultValue: {
205
- * enabled: true,
206
- * model: { name: 'gpt-4' },
207
- * provider: { name: 'openai' },
208
- * instructions: 'You are a writing assistant.'
209
- * },
210
- * variables: { style: 'academic' }
211
- * }
212
- * ] as const;
213
- * const context = {...};
214
- *
215
- * const configs = await client.agentConfigs(agentConfigsList, context);
216
- * const researchResult = configs["research_agent"].instructions; // Interpolated instructions
217
- * configs["research_agent"].tracker.trackSuccess();
218
- * ```
219
- */
220
- agentConfigs<const T extends readonly LDAIAgentRequestConfig[]>(
221
- agentConfigs: T,
222
- context: LDContext,
223
- ): Promise<Record<T[number]['key'], LDAIAgentConfig>>;
224
-
225
- /**
226
- * @deprecated Use `agentConfigs` instead. This method will be removed in a future version.
227
- */
228
- agents<const T extends readonly LDAIAgentRequestConfig[]>(
229
- agentConfigs: T,
230
- context: LDContext,
231
- ): Promise<Record<T[number]['key'], LDAIAgentConfig>>;
232
-
233
- /**
234
- * Returns a TrackedChat instance for chat interactions.
235
- * This method serves as the primary entry point for creating TrackedChat instances from configuration.
236
- *
237
- * @param key The key identifying the AI chat configuration to use.
238
- * @param context The standard LDContext used when evaluating flags.
239
- * @param defaultValue A default value representing a standard AI chat config result.
240
- * @param variables Dictionary of values for instruction interpolation.
241
- * The variables will also be used for judge evaluation. For the judge only, the variables
242
- * `message_history` and `response_to_evaluate` are reserved and will be ignored.
243
- * @param defaultAiProvider Optional default AI provider to use.
244
- * @returns A promise that resolves to the TrackedChat instance, or null if the configuration is disabled.
245
- *
246
- * @example
247
- * ```
248
- * const key = "customer_support_chat";
249
- * const context = {...};
250
- * const defaultValue = {
251
- * enabled: false,
252
- * model: { name: "gpt-4" },
253
- * provider: { name: "openai" },
254
- * messages: [
255
- * { role: "system", content: "You are a helpful customer support agent." }
256
- * ]
257
- * };
258
- * const variables = { customerName: 'John' };
259
- *
260
- * const chat = await client.createChat(key, context, defaultValue, variables);
261
- * if (chat) {
262
- * const response = await chat.invoke("I need help with my order");
263
- * console.log(response.message.content);
264
- * }
265
- * ```
266
- */
267
- createChat(
268
- key: string,
269
- context: LDContext,
270
- defaultValue: LDAICompletionConfigDefault,
271
- variables?: Record<string, unknown>,
272
- defaultAiProvider?: SupportedAIProvider,
273
- ): Promise<TrackedChat | undefined>;
274
-
275
- /**
276
- * @deprecated Use `createChat` instead. This method will be removed in a future version.
277
- */
278
- initChat(
279
- key: string,
280
- context: LDContext,
281
- defaultValue: LDAICompletionConfigDefault,
282
- variables?: Record<string, unknown>,
283
- defaultAiProvider?: SupportedAIProvider,
284
- ): Promise<TrackedChat | undefined>;
285
-
286
- /**
287
- * Creates and returns a new Judge instance for AI evaluation.
288
- *
289
- * @param key The key identifying the AI judge configuration to use
290
- * @param context Standard LDContext used when evaluating flags
291
- * @param defaultValue A default value representing a standard AI config result
292
- * @param variables Dictionary of values for instruction interpolation.
293
- * The variables `message_history` and `response_to_evaluate` are reserved for the judge and will be ignored.
294
- * @param defaultAiProvider Optional default AI provider to use.
295
- * @returns Promise that resolves to a Judge instance or undefined if disabled/unsupported
296
- *
297
- * @example
298
- * ```
299
- * const judge = await client.createJudge(
300
- * "relevance-judge",
301
- * context,
302
- * {
303
- * enabled: true,
304
- * model: { name: "gpt-4" },
305
- * provider: { name: "openai" },
306
- * evaluationMetricKeys: ['$ld:ai:judge:relevance'],
307
- * messages: [{ role: 'system', content: 'You are a relevance judge.' }]
308
- * },
309
- * { metric: "relevance" }
310
- * );
311
- *
312
- * if (judge) {
313
- * const result = await judge.evaluate("User question", "AI response");
314
- * console.log('Relevance score:', result.evals.relevance?.score);
315
- * }
316
- * ```
317
- */
318
- createJudge(
319
- key: string,
320
- context: LDContext,
321
- defaultValue: LDAIJudgeConfigDefault,
322
- variables?: Record<string, unknown>,
323
- defaultAiProvider?: SupportedAIProvider,
324
- ): Promise<Judge | undefined>;
325
- }