@launchdarkly/server-sdk-ai 0.14.1 → 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 +11 -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 -521
  10. package/__tests__/LDAIClientImpl.test.ts +0 -594
  11. package/__tests__/LDAIConfigTrackerImpl.test.ts +0 -815
  12. package/__tests__/TokenUsage.test.ts +0 -119
  13. package/__tests__/TrackedChat.test.ts +0 -231
  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 -74
  20. package/dist/src/LDAIConfigTrackerImpl.d.ts.map +0 -1
  21. package/dist/src/LDAIConfigTrackerImpl.js +0 -207
  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 -209
  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 -145
  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 -206
  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 -151
  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 -37
  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 -139
  141. package/docs/interfaces/LDAIAgentConfig.html +0 -178
  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 -178
  146. package/docs/interfaces/LDAICompletionConfigDefault.html +0 -155
  147. package/docs/interfaces/LDAIConfig.html +0 -158
  148. package/docs/interfaces/LDAIConfigDefault.html +0 -133
  149. package/docs/interfaces/LDAIConfigTracker.html +0 -530
  150. package/docs/interfaces/LDAIJudgeConfig.html +0 -178
  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 -288
  169. package/src/LDClientMin.ts +0 -18
  170. package/src/api/LDAIClient.ts +0 -325
  171. package/src/api/chat/TrackedChat.ts +0 -163
  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 -238
  175. package/src/api/config/LDAIConfigUtils.ts +0 -212
  176. package/src/api/config/index.ts +0 -3
  177. package/src/api/config/types.ts +0 -260
  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 -218
  181. package/src/api/judge/index.ts +0 -2
  182. package/src/api/judge/types.ts +0 -41
  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,163 +0,0 @@
1
- import { LDLogger } from '@launchdarkly/js-server-sdk-common';
2
-
3
- import { LDAIConfigTracker } from '../config/LDAIConfigTracker';
4
- import { LDAICompletionConfig, LDMessage } from '../config/types';
5
- import { Judge } from '../judge/Judge';
6
- import { JudgeResponse } from '../judge/types';
7
- import { AIProvider } from '../providers/AIProvider';
8
- import { ChatResponse } from './types';
9
-
10
- /**
11
- * Concrete implementation of TrackedChat that provides chat functionality
12
- * by delegating to an AIProvider implementation.
13
- * This class handles conversation management and tracking, while delegating
14
- * the actual model invocation to the provider.
15
- */
16
- export class TrackedChat {
17
- protected messages: LDMessage[];
18
-
19
- constructor(
20
- protected readonly aiConfig: LDAICompletionConfig,
21
- protected readonly tracker: LDAIConfigTracker,
22
- protected readonly provider: AIProvider,
23
- protected readonly judges: Record<string, Judge> = {},
24
- private readonly _logger?: LDLogger,
25
- ) {
26
- this.messages = [];
27
- }
28
-
29
- /**
30
- * Invoke the chat model with a prompt string.
31
- * This method handles conversation management and tracking, delegating to the provider's invokeModel method.
32
- */
33
- async invoke(prompt: string): Promise<ChatResponse> {
34
- // Convert prompt string to LDMessage with role 'user' and add to conversation history
35
- const userMessage: LDMessage = {
36
- role: 'user',
37
- content: prompt,
38
- };
39
- this.messages.push(userMessage);
40
-
41
- // Prepend config messages to conversation history for model invocation
42
- const configMessages = this.aiConfig.messages || [];
43
- const allMessages = [...configMessages, ...this.messages];
44
-
45
- // Delegate to provider-specific implementation with tracking
46
- const response = await this.tracker.trackMetricsOf(
47
- (result: ChatResponse) => result.metrics,
48
- () => this.provider.invokeModel(allMessages),
49
- );
50
-
51
- if (
52
- this.aiConfig.judgeConfiguration?.judges &&
53
- this.aiConfig.judgeConfiguration.judges.length > 0
54
- ) {
55
- response.evaluations = this._evaluateWithJudges(this.messages, response);
56
- }
57
-
58
- this.messages.push(response.message);
59
- return response;
60
- }
61
-
62
- /**
63
- * Evaluates the response with all configured judges.
64
- * Returns a promise that resolves to an array of evaluation results.
65
- *
66
- * @param messages Array of messages representing the conversation history
67
- * @param response The AI response to be evaluated
68
- * @returns Promise resolving to array of judge evaluation results
69
- */
70
- private async _evaluateWithJudges(
71
- messages: LDMessage[],
72
- response: ChatResponse,
73
- ): Promise<Array<JudgeResponse | undefined>> {
74
- const judgeConfigs = this.aiConfig.judgeConfiguration!.judges;
75
-
76
- // Start all judge evaluations in parallel
77
- const evaluationPromises = judgeConfigs.map(async (judgeConfig) => {
78
- const judge = this.judges[judgeConfig.key];
79
- if (!judge) {
80
- this._logger?.warn(
81
- `Judge configuration is not enabled: ${judgeConfig.key}`,
82
- this.tracker.getTrackData(),
83
- );
84
- return undefined;
85
- }
86
-
87
- const judgeResponse = await judge.evaluateMessages(
88
- messages,
89
- response,
90
- judgeConfig.samplingRate,
91
- );
92
-
93
- if (judgeResponse && judgeResponse.success) {
94
- this.tracker.trackJudgeResponse(judgeResponse);
95
- }
96
-
97
- return judgeResponse;
98
- });
99
-
100
- // ensure all evaluations complete even if some fail
101
- const results = await Promise.allSettled(evaluationPromises);
102
-
103
- return results.map((result) => (result.status === 'fulfilled' ? result.value : undefined));
104
- }
105
-
106
- /**
107
- * Get the underlying AI configuration used to initialize this TrackedChat.
108
- */
109
- getConfig(): LDAICompletionConfig {
110
- return this.aiConfig;
111
- }
112
-
113
- /**
114
- * Get the underlying AI configuration tracker used to initialize this TrackedChat.
115
- */
116
- getTracker(): LDAIConfigTracker {
117
- return this.tracker;
118
- }
119
-
120
- /**
121
- * Get the underlying AI provider instance.
122
- * This provides direct access to the provider for advanced use cases.
123
- */
124
- getProvider(): AIProvider {
125
- return this.provider;
126
- }
127
-
128
- /**
129
- * Get the judges associated with this TrackedChat.
130
- * Returns a record of judge instances keyed by their configuration keys.
131
- */
132
- getJudges(): Record<string, Judge> {
133
- return this.judges;
134
- }
135
-
136
- /**
137
- * Append messages to the conversation history.
138
- * Adds messages to the conversation history without invoking the model,
139
- * which is useful for managing multi-turn conversations or injecting context.
140
- *
141
- * @param messages Array of messages to append to the conversation history
142
- */
143
- appendMessages(messages: LDMessage[]): void {
144
- this.messages.push(...messages);
145
- }
146
-
147
- /**
148
- * Get all messages in the conversation history.
149
- *
150
- * @param includeConfigMessages Whether to include the config messages from the AIConfig.
151
- * Defaults to false.
152
- * @returns Array of messages. When includeConfigMessages is true, returns both config
153
- * messages and conversation history with config messages prepended. When false,
154
- * returns only the conversation history messages.
155
- */
156
- getMessages(includeConfigMessages: boolean = false): LDMessage[] {
157
- if (includeConfigMessages) {
158
- const configMessages = this.aiConfig.messages || [];
159
- return [...configMessages, ...this.messages];
160
- }
161
- return [...this.messages];
162
- }
163
- }
@@ -1,2 +0,0 @@
1
- export * from './types';
2
- export * from './TrackedChat';
@@ -1,24 +0,0 @@
1
- import { LDMessage } from '../config/types';
2
- import { JudgeResponse } from '../judge/types';
3
- import { LDAIMetrics } from '../metrics/LDAIMetrics';
4
-
5
- /**
6
- * Chat response structure.
7
- */
8
- export interface ChatResponse {
9
- /**
10
- * The response message from the AI.
11
- */
12
- message: LDMessage;
13
-
14
- /**
15
- * Metrics information including success status and token usage.
16
- */
17
- metrics: LDAIMetrics;
18
-
19
- /**
20
- * Promise that resolves to judge evaluation results.
21
- * Only present when judges are configured for evaluation.
22
- */
23
- evaluations?: Promise<Array<JudgeResponse | undefined>>;
24
- }
@@ -1,238 +0,0 @@
1
- import { EvalScore, JudgeResponse } from '../judge/types';
2
- import { LDAIMetrics, LDFeedbackKind, LDTokenUsage } from '../metrics';
3
-
4
- /**
5
- * Metrics which have been tracked.
6
- */
7
- export interface LDAIMetricSummary {
8
- /**
9
- * The duration of generation.
10
- */
11
- durationMs?: number;
12
-
13
- /**
14
- * Information about token usage.
15
- */
16
- tokens?: LDTokenUsage;
17
-
18
- /**
19
- * Was generation successful.
20
- */
21
- success?: boolean;
22
-
23
- /**
24
- * Any sentiment about the generation.
25
- */
26
- feedback?: { kind: LDFeedbackKind };
27
-
28
- /**
29
- * Time to first token for this generation.
30
- */
31
- timeToFirstTokenMs?: number;
32
- }
33
-
34
- /**
35
- * The LDAIConfigTracker is used to track various details about AI operations.
36
- */
37
- export interface LDAIConfigTracker {
38
- /**
39
- * Get the data for tracking.
40
- */
41
- getTrackData(): {
42
- variationKey: string;
43
- configKey: string;
44
- version: number;
45
- modelName: string;
46
- providerName: string;
47
- aiSdkName: string;
48
- aiSdkVersion: string;
49
- };
50
- /**
51
- * Track the duration of generation.
52
- *
53
- * Ideally this would not include overhead time such as network communication.
54
- *
55
- * @param durationMs The duration in milliseconds.
56
- */
57
- trackDuration(durationMs: number): void;
58
-
59
- /**
60
- * Track information about token usage.
61
- *
62
- * @param tokens Token usage information.
63
- */
64
- trackTokens(tokens: LDTokenUsage): void;
65
-
66
- /**
67
- * Generation was successful.
68
- */
69
- trackSuccess(): void;
70
-
71
- /**
72
- * An error was encountered during generation.
73
- */
74
- trackError(): void;
75
-
76
- /**
77
- * Track sentiment about the generation.
78
- *
79
- * @param feedback Feedback about the generation.
80
- */
81
- trackFeedback(feedback: { kind: LDFeedbackKind }): void;
82
-
83
- /**
84
- * Track the time to first token for this generation.
85
- *
86
- * @param timeToFirstTokenMs The duration in milliseconds.
87
- */
88
- trackTimeToFirstToken(timeToFirstTokenMs: number): void;
89
-
90
- /**
91
- * Track evaluation scores for multiple metrics.
92
- *
93
- * @param scores Record mapping metric keys to their evaluation scores
94
- */
95
- trackEvalScores(scores: Record<string, EvalScore>): void;
96
-
97
- /**
98
- * Track a judge response containing evaluation scores and judge configuration key.
99
- *
100
- * @param response Judge response containing evaluation scores and judge configuration key
101
- */
102
- trackJudgeResponse(response: JudgeResponse): void;
103
-
104
- /**
105
- * Track the duration of execution of the provided function.
106
- *
107
- * If the provided function throws, then this method will also throw.
108
- * In the case the provided function throws, this function will still record the duration.
109
- *
110
- * This function does not automatically record an error when the function throws.
111
- *
112
- * @param func The function to track the duration of.
113
- * @returns The result of the function.
114
- */
115
- trackDurationOf(func: () => Promise<any>): Promise<any>;
116
-
117
- /**
118
- * Track metrics for a generic AI operation.
119
- *
120
- * This function will track the duration of the operation, extract metrics using the provided
121
- * metrics extractor function, and track success or error status accordingly.
122
- *
123
- * If the provided function throws, then this method will also throw.
124
- * In the case the provided function throws, this function will record the duration and an error.
125
- * A failed operation will not have any token usage data.
126
- *
127
- * @param metricsExtractor Function that extracts LDAIMetrics from the operation result
128
- * @param func Function which executes the operation
129
- * @returns The result of the operation
130
- */
131
- trackMetricsOf<TRes>(
132
- metricsExtractor: (result: TRes) => LDAIMetrics,
133
- func: () => Promise<TRes>,
134
- ): Promise<TRes>;
135
-
136
- /**
137
- * Track metrics for a streaming AI operation.
138
- *
139
- * This function will track the duration of the operation, extract metrics using the provided
140
- * metrics extractor function, and track success or error status accordingly.
141
- *
142
- * Unlike trackMetricsOf, this method is designed for streaming operations where:
143
- * - The stream is created and returned immediately (synchronously)
144
- * - Metrics are extracted asynchronously in the background once the stream completes
145
- * - Duration is tracked from stream creation to metrics extraction completion
146
- *
147
- * The stream is returned immediately so the caller can begin consuming it without waiting.
148
- * Metrics extraction happens in the background and does not block stream consumption.
149
- *
150
- * If the stream creator throws, then this method will also throw and record an error.
151
- * If metrics extraction fails, the error is logged but does not affect stream consumption.
152
- *
153
- * @param streamCreator Function that creates and returns the stream (synchronous)
154
- * @param metricsExtractor Function that asynchronously extracts metrics from the stream
155
- * @returns The stream result (returned immediately, not a Promise)
156
- */
157
- trackStreamMetricsOf<TStream>(
158
- streamCreator: () => TStream,
159
- metricsExtractor: (stream: TStream) => Promise<LDAIMetrics>,
160
- ): TStream;
161
-
162
- /**
163
- * Track an OpenAI operation.
164
- *
165
- * This function will track the duration of the operation, the token usage, and the success or error status.
166
- *
167
- * If the provided function throws, then this method will also throw.
168
- * In the case the provided function throws, this function will record the duration and an error.
169
- * A failed operation will not have any token usage data.
170
- *
171
- * @param func Function which executes the operation.
172
- * @returns The result of the operation.
173
- */
174
- trackOpenAIMetrics<
175
- TRes extends {
176
- usage?: {
177
- total_tokens?: number;
178
- prompt_tokens?: number;
179
- completion_tokens?: number;
180
- };
181
- },
182
- >(
183
- func: () => Promise<TRes>,
184
- ): Promise<TRes>;
185
-
186
- /**
187
- * Track an operation which uses Bedrock.
188
- *
189
- * This function will track the duration of the operation, the token usage, and the success or error status.
190
- *
191
- * @param res The result of the Bedrock operation.
192
- * @returns The input operation.
193
- */
194
- trackBedrockConverseMetrics<
195
- TRes extends {
196
- $metadata: { httpStatusCode?: number };
197
- metrics?: { latencyMs?: number };
198
- usage?: {
199
- inputTokens?: number;
200
- outputTokens?: number;
201
- totalTokens?: number;
202
- };
203
- },
204
- >(
205
- res: TRes,
206
- ): TRes;
207
-
208
- /**
209
- * Track a Vercel AI SDK generateText operation.
210
- *
211
- * This function will track the duration of the operation, the token usage, and the success or error status.
212
- *
213
- * If the provided function throws, then this method will also throw.
214
- * In the case the provided function throws, this function will record the duration and an error.
215
- * A failed operation will not have any token usage data.
216
- *
217
- * @param func Function which executes the operation.
218
- * @returns The result of the operation.
219
- */
220
- trackVercelAISDKGenerateTextMetrics<
221
- TRes extends {
222
- usage?: {
223
- totalTokens?: number;
224
- inputTokens?: number;
225
- promptTokens?: number;
226
- outputTokens?: number;
227
- completionTokens?: number;
228
- };
229
- },
230
- >(
231
- func: () => Promise<TRes>,
232
- ): Promise<TRes>;
233
-
234
- /**
235
- * Get a summary of the tracked metrics.
236
- */
237
- getSummary(): LDAIMetricSummary;
238
- }
@@ -1,212 +0,0 @@
1
- import { LDAIConfigTracker } from './LDAIConfigTracker';
2
- import {
3
- LDAIAgentConfig,
4
- LDAICompletionConfig,
5
- LDAIConfigDefaultKind,
6
- LDAIConfigKind,
7
- LDAIConfigMode,
8
- LDAIJudgeConfig,
9
- LDJudgeConfiguration,
10
- LDMessage,
11
- LDModelConfig,
12
- LDProviderConfig,
13
- } from './types';
14
-
15
- /**
16
- * Internal flag value structure returned by LaunchDarkly.
17
- * This represents the raw data structure that LaunchDarkly returns for AI configuration flags.
18
- *
19
- * @internal - Not meant for external use
20
- */
21
- export interface LDAIConfigFlagValue {
22
- _ldMeta?: {
23
- variationKey?: string;
24
- enabled: boolean;
25
- version?: number;
26
- mode?: LDAIConfigMode;
27
- };
28
- model?: LDModelConfig;
29
- messages?: LDMessage[];
30
- provider?: LDProviderConfig;
31
- instructions?: string;
32
- evaluationMetricKeys?: string[];
33
- judgeConfiguration?: LDJudgeConfiguration;
34
- }
35
-
36
- /**
37
- * Utility class for converting between AI configuration types and LaunchDarkly flag values.
38
- *
39
- * @internal - This class and its types are internal implementation details and should not be used by SDK consumers.
40
- */
41
- export class LDAIConfigUtils {
42
- /**
43
- * Converts a default AI configuration to a LaunchDarkly flag value format.
44
- *
45
- * @param config The default AI configuration to convert
46
- * @param mode The mode for the configuration
47
- * @returns The flag value structure for LaunchDarkly
48
- */
49
- static toFlagValue(config: LDAIConfigDefaultKind, mode: LDAIConfigMode): LDAIConfigFlagValue {
50
- const flagValue: LDAIConfigFlagValue = {
51
- _ldMeta: {
52
- variationKey: '', // Not available when converting from config
53
- enabled: config.enabled ?? false,
54
- mode,
55
- },
56
- model: config.model,
57
- };
58
-
59
- if ('messages' in config && config.messages !== undefined) {
60
- flagValue.messages = config.messages;
61
- }
62
- if (config.provider !== undefined) {
63
- flagValue.provider = config.provider;
64
- }
65
- if ('instructions' in config && config.instructions !== undefined) {
66
- flagValue.instructions = config.instructions;
67
- }
68
- if ('evaluationMetricKeys' in config && config.evaluationMetricKeys !== undefined) {
69
- flagValue.evaluationMetricKeys = config.evaluationMetricKeys;
70
- }
71
- if ('judgeConfiguration' in config && config.judgeConfiguration !== undefined) {
72
- flagValue.judgeConfiguration = config.judgeConfiguration;
73
- }
74
-
75
- return flagValue;
76
- }
77
-
78
- /**
79
- * Converts a LaunchDarkly flag value to the appropriate AI configuration type.
80
- *
81
- * @param flagValue The flag value from LaunchDarkly
82
- * @param tracker The tracker to add to the config
83
- * @returns The appropriate AI configuration type
84
- */
85
- static fromFlagValue(
86
- key: string,
87
- flagValue: LDAIConfigFlagValue,
88
- tracker: LDAIConfigTracker,
89
- ): LDAIConfigKind {
90
- // Determine the actual mode from flag value
91
- // eslint-disable-next-line no-underscore-dangle
92
- const flagValueMode = flagValue._ldMeta?.mode;
93
-
94
- switch (flagValueMode) {
95
- case 'agent':
96
- return this.toAgentConfig(key, flagValue, tracker);
97
- case 'judge':
98
- return this.toJudgeConfig(key, flagValue, tracker);
99
- case 'completion':
100
- default:
101
- return this.toCompletionConfig(key, flagValue, tracker);
102
- }
103
- }
104
-
105
- /**
106
- * Creates a disabled configuration of the specified mode.
107
- *
108
- * @param mode The mode for the disabled config
109
- * @returns A disabled config of the appropriate type
110
- */
111
- static createDisabledConfig(key: string, mode: LDAIConfigMode): LDAIConfigKind {
112
- switch (mode) {
113
- case 'agent':
114
- return {
115
- key,
116
- enabled: false,
117
- tracker: undefined,
118
- } as LDAIAgentConfig;
119
- case 'judge':
120
- return {
121
- key,
122
- enabled: false,
123
- tracker: undefined,
124
- evaluationMetricKeys: [],
125
- } as LDAIJudgeConfig;
126
- case 'completion':
127
- default:
128
- // Default to completion config for completion mode or any unexpected mode
129
- return {
130
- key,
131
- enabled: false,
132
- tracker: undefined,
133
- } as LDAICompletionConfig;
134
- }
135
- }
136
-
137
- /**
138
- * Creates the base configuration that all config types share.
139
- *
140
- * @param flagValue The flag value from LaunchDarkly
141
- * @returns Base configuration object
142
- */
143
- private static _toBaseConfig(key: string, flagValue: LDAIConfigFlagValue) {
144
- return {
145
- key,
146
- // eslint-disable-next-line no-underscore-dangle
147
- enabled: flagValue._ldMeta?.enabled ?? false,
148
- model: flagValue.model,
149
- provider: flagValue.provider,
150
- };
151
- }
152
-
153
- /**
154
- * Creates a completion config from flag value data.
155
- *
156
- * @param flagValue The flag value from LaunchDarkly
157
- * @param tracker The tracker to add to the config
158
- * @returns A completion configuration
159
- */
160
- static toCompletionConfig(
161
- key: string,
162
- flagValue: LDAIConfigFlagValue,
163
- tracker: LDAIConfigTracker,
164
- ): LDAICompletionConfig {
165
- return {
166
- ...this._toBaseConfig(key, flagValue),
167
- tracker,
168
- messages: flagValue.messages,
169
- judgeConfiguration: flagValue.judgeConfiguration,
170
- };
171
- }
172
-
173
- /**
174
- * Creates an agent config from flag value data.
175
- *
176
- * @param flagValue The flag value from LaunchDarkly
177
- * @param tracker The tracker to add to the config
178
- * @returns An agent configuration
179
- */
180
- static toAgentConfig(
181
- key: string,
182
- flagValue: LDAIConfigFlagValue,
183
- tracker: LDAIConfigTracker,
184
- ): LDAIAgentConfig {
185
- return {
186
- ...this._toBaseConfig(key, flagValue),
187
- tracker,
188
- instructions: flagValue.instructions,
189
- judgeConfiguration: flagValue.judgeConfiguration,
190
- };
191
- }
192
-
193
- /**
194
- * Creates a judge config from flag value data.
195
- *
196
- * @param flagValue The flag value from LaunchDarkly
197
- * @param tracker The tracker to add to the config
198
- * @returns A judge configuration
199
- */
200
- static toJudgeConfig(
201
- key: string,
202
- flagValue: LDAIConfigFlagValue,
203
- tracker: LDAIConfigTracker,
204
- ): LDAIJudgeConfig {
205
- return {
206
- ...this._toBaseConfig(key, flagValue),
207
- tracker,
208
- messages: flagValue.messages,
209
- evaluationMetricKeys: flagValue.evaluationMetricKeys || [],
210
- };
211
- }
212
- }
@@ -1,3 +0,0 @@
1
- export * from './types';
2
- // LDAIConfigUtils is intentionally not exported - it's an internal utility class
3
- export { LDAIConfigTracker } from './LDAIConfigTracker';