@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.
- package/CHANGELOG.md +11 -0
- package/dist/index.cjs +1117 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1022 -0
- package/dist/index.d.ts +1022 -0
- package/dist/index.js +1071 -0
- package/dist/index.js.map +1 -0
- package/package.json +22 -5
- package/__tests__/Judge.test.ts +0 -521
- package/__tests__/LDAIClientImpl.test.ts +0 -594
- package/__tests__/LDAIConfigTrackerImpl.test.ts +0 -815
- package/__tests__/TokenUsage.test.ts +0 -119
- package/__tests__/TrackedChat.test.ts +0 -231
- package/dist/package.json +0 -53
- package/dist/src/LDAIClientImpl.d.ts +0 -39
- package/dist/src/LDAIClientImpl.d.ts.map +0 -1
- package/dist/src/LDAIClientImpl.js +0 -164
- package/dist/src/LDAIClientImpl.js.map +0 -1
- package/dist/src/LDAIConfigTrackerImpl.d.ts +0 -74
- package/dist/src/LDAIConfigTrackerImpl.d.ts.map +0 -1
- package/dist/src/LDAIConfigTrackerImpl.js +0 -207
- package/dist/src/LDAIConfigTrackerImpl.js.map +0 -1
- package/dist/src/LDClientMin.d.ts +0 -11
- package/dist/src/LDClientMin.d.ts.map +0 -1
- package/dist/src/LDClientMin.js +0 -3
- package/dist/src/LDClientMin.js.map +0 -1
- package/dist/src/api/LDAIClient.d.ts +0 -258
- package/dist/src/api/LDAIClient.d.ts.map +0 -1
- package/dist/src/api/LDAIClient.js +0 -3
- package/dist/src/api/LDAIClient.js.map +0 -1
- package/dist/src/api/chat/TrackedChat.d.ts +0 -72
- package/dist/src/api/chat/TrackedChat.d.ts.map +0 -1
- package/dist/src/api/chat/TrackedChat.js +0 -125
- package/dist/src/api/chat/TrackedChat.js.map +0 -1
- package/dist/src/api/chat/index.d.ts +0 -3
- package/dist/src/api/chat/index.d.ts.map +0 -1
- package/dist/src/api/chat/index.js +0 -19
- package/dist/src/api/chat/index.js.map +0 -1
- package/dist/src/api/chat/types.d.ts +0 -22
- package/dist/src/api/chat/types.d.ts.map +0 -1
- package/dist/src/api/chat/types.js +0 -3
- package/dist/src/api/chat/types.js.map +0 -1
- package/dist/src/api/config/LDAIConfigTracker.d.ts +0 -209
- package/dist/src/api/config/LDAIConfigTracker.d.ts.map +0 -1
- package/dist/src/api/config/LDAIConfigTracker.js +0 -3
- package/dist/src/api/config/LDAIConfigTracker.js.map +0 -1
- package/dist/src/api/config/LDAIConfigUtils.d.ts +0 -2
- package/dist/src/api/config/LDAIConfigUtils.d.ts.map +0 -1
- package/dist/src/api/config/LDAIConfigUtils.js +0 -145
- package/dist/src/api/config/LDAIConfigUtils.js.map +0 -1
- package/dist/src/api/config/index.d.ts +0 -3
- package/dist/src/api/config/index.d.ts.map +0 -1
- package/dist/src/api/config/index.js +0 -18
- package/dist/src/api/config/index.js.map +0 -1
- package/dist/src/api/config/types.d.ts +0 -206
- package/dist/src/api/config/types.d.ts.map +0 -1
- package/dist/src/api/config/types.js +0 -3
- package/dist/src/api/config/types.js.map +0 -1
- package/dist/src/api/index.d.ts +0 -7
- package/dist/src/api/index.d.ts.map +0 -1
- package/dist/src/api/index.js +0 -23
- package/dist/src/api/index.js.map +0 -1
- package/dist/src/api/judge/EvaluationSchemaBuilder.d.ts +0 -11
- package/dist/src/api/judge/EvaluationSchemaBuilder.d.ts.map +0 -1
- package/dist/src/api/judge/EvaluationSchemaBuilder.js +0 -52
- package/dist/src/api/judge/EvaluationSchemaBuilder.js.map +0 -1
- package/dist/src/api/judge/Judge.d.ts +0 -63
- package/dist/src/api/judge/Judge.d.ts.map +0 -1
- package/dist/src/api/judge/Judge.js +0 -151
- package/dist/src/api/judge/Judge.js.map +0 -1
- package/dist/src/api/judge/index.d.ts +0 -3
- package/dist/src/api/judge/index.d.ts.map +0 -1
- package/dist/src/api/judge/index.js +0 -6
- package/dist/src/api/judge/index.js.map +0 -1
- package/dist/src/api/judge/types.d.ts +0 -37
- package/dist/src/api/judge/types.d.ts.map +0 -1
- package/dist/src/api/judge/types.js +0 -3
- package/dist/src/api/judge/types.js.map +0 -1
- package/dist/src/api/metrics/BedrockTokenUsage.d.ts +0 -7
- package/dist/src/api/metrics/BedrockTokenUsage.d.ts.map +0 -1
- package/dist/src/api/metrics/BedrockTokenUsage.js +0 -12
- package/dist/src/api/metrics/BedrockTokenUsage.js.map +0 -1
- package/dist/src/api/metrics/LDAIMetrics.d.ts +0 -17
- package/dist/src/api/metrics/LDAIMetrics.d.ts.map +0 -1
- package/dist/src/api/metrics/LDAIMetrics.js +0 -3
- package/dist/src/api/metrics/LDAIMetrics.js.map +0 -1
- package/dist/src/api/metrics/LDFeedbackKind.d.ts +0 -14
- package/dist/src/api/metrics/LDFeedbackKind.d.ts.map +0 -1
- package/dist/src/api/metrics/LDFeedbackKind.js +0 -18
- package/dist/src/api/metrics/LDFeedbackKind.js.map +0 -1
- package/dist/src/api/metrics/LDTokenUsage.d.ts +0 -18
- package/dist/src/api/metrics/LDTokenUsage.d.ts.map +0 -1
- package/dist/src/api/metrics/LDTokenUsage.js +0 -3
- package/dist/src/api/metrics/LDTokenUsage.js.map +0 -1
- package/dist/src/api/metrics/OpenAiUsage.d.ts +0 -7
- package/dist/src/api/metrics/OpenAiUsage.d.ts.map +0 -1
- package/dist/src/api/metrics/OpenAiUsage.js +0 -13
- package/dist/src/api/metrics/OpenAiUsage.js.map +0 -1
- package/dist/src/api/metrics/VercelAISDKTokenUsage.d.ts +0 -9
- package/dist/src/api/metrics/VercelAISDKTokenUsage.d.ts.map +0 -1
- package/dist/src/api/metrics/VercelAISDKTokenUsage.js +0 -13
- package/dist/src/api/metrics/VercelAISDKTokenUsage.js.map +0 -1
- package/dist/src/api/metrics/index.d.ts +0 -7
- package/dist/src/api/metrics/index.d.ts.map +0 -1
- package/dist/src/api/metrics/index.js +0 -23
- package/dist/src/api/metrics/index.js.map +0 -1
- package/dist/src/api/providers/AIProvider.d.ts +0 -52
- package/dist/src/api/providers/AIProvider.d.ts.map +0 -1
- package/dist/src/api/providers/AIProvider.js +0 -88
- package/dist/src/api/providers/AIProvider.js.map +0 -1
- package/dist/src/api/providers/AIProviderFactory.d.ts +0 -39
- package/dist/src/api/providers/AIProviderFactory.d.ts.map +0 -1
- package/dist/src/api/providers/AIProviderFactory.js +0 -102
- package/dist/src/api/providers/AIProviderFactory.js.map +0 -1
- package/dist/src/api/providers/index.d.ts +0 -3
- package/dist/src/api/providers/index.d.ts.map +0 -1
- package/dist/src/api/providers/index.js +0 -19
- package/dist/src/api/providers/index.js.map +0 -1
- package/dist/src/index.d.ts +0 -19
- package/dist/src/index.d.ts.map +0 -1
- package/dist/src/index.js +0 -29
- package/dist/src/index.js.map +0 -1
- package/docs/.nojekyll +0 -1
- package/docs/assets/highlight.css +0 -92
- package/docs/assets/main.js +0 -58
- package/docs/assets/search.js +0 -1
- package/docs/assets/style.css +0 -1379
- package/docs/classes/AIProvider.html +0 -210
- package/docs/classes/AIProviderFactory.html +0 -208
- package/docs/classes/Judge.html +0 -322
- package/docs/classes/TrackedChat.html +0 -322
- package/docs/enums/LDFeedbackKind.html +0 -115
- package/docs/functions/createBedrockTokenUsage.html +0 -94
- package/docs/functions/createOpenAiUsage.html +0 -94
- package/docs/functions/createVercelAISDKTokenUsage.html +0 -98
- package/docs/functions/initAi.html +0 -93
- package/docs/index.html +0 -136
- package/docs/interfaces/ChatResponse.html +0 -130
- package/docs/interfaces/EvalScore.html +0 -119
- package/docs/interfaces/JudgeResponse.html +0 -139
- package/docs/interfaces/LDAIAgentConfig.html +0 -178
- package/docs/interfaces/LDAIAgentConfigDefault.html +0 -155
- package/docs/interfaces/LDAIAgentRequestConfig.html +0 -129
- package/docs/interfaces/LDAIClient.html +0 -449
- package/docs/interfaces/LDAICompletionConfig.html +0 -178
- package/docs/interfaces/LDAICompletionConfigDefault.html +0 -155
- package/docs/interfaces/LDAIConfig.html +0 -158
- package/docs/interfaces/LDAIConfigDefault.html +0 -133
- package/docs/interfaces/LDAIConfigTracker.html +0 -530
- package/docs/interfaces/LDAIJudgeConfig.html +0 -178
- package/docs/interfaces/LDAIJudgeConfigDefault.html +0 -155
- package/docs/interfaces/LDAIMetrics.html +0 -121
- package/docs/interfaces/LDJudge.html +0 -119
- package/docs/interfaces/LDJudgeConfiguration.html +0 -109
- package/docs/interfaces/LDLogger.html +0 -189
- package/docs/interfaces/LDMessage.html +0 -119
- package/docs/interfaces/LDModelConfig.html +0 -139
- package/docs/interfaces/LDProviderConfig.html +0 -105
- package/docs/interfaces/LDTokenUsage.html +0 -129
- package/docs/interfaces/StructuredResponse.html +0 -129
- package/docs/types/LDAIConfigDefaultKind.html +0 -81
- package/docs/types/LDAIConfigKind.html +0 -81
- package/docs/types/LDAIConfigMode.html +0 -81
- package/docs/types/SupportedAIProvider.html +0 -81
- package/docs/variables/SUPPORTED_AI_PROVIDERS.html +0 -81
- package/jest.config.js +0 -7
- package/src/LDAIClientImpl.ts +0 -327
- package/src/LDAIConfigTrackerImpl.ts +0 -288
- package/src/LDClientMin.ts +0 -18
- package/src/api/LDAIClient.ts +0 -325
- package/src/api/chat/TrackedChat.ts +0 -163
- package/src/api/chat/index.ts +0 -2
- package/src/api/chat/types.ts +0 -24
- package/src/api/config/LDAIConfigTracker.ts +0 -238
- package/src/api/config/LDAIConfigUtils.ts +0 -212
- package/src/api/config/index.ts +0 -3
- package/src/api/config/types.ts +0 -260
- package/src/api/index.ts +0 -6
- package/src/api/judge/EvaluationSchemaBuilder.ts +0 -54
- package/src/api/judge/Judge.ts +0 -218
- package/src/api/judge/index.ts +0 -2
- package/src/api/judge/types.ts +0 -41
- package/src/api/metrics/BedrockTokenUsage.ts +0 -13
- package/src/api/metrics/LDAIMetrics.ts +0 -18
- package/src/api/metrics/LDFeedbackKind.ts +0 -13
- package/src/api/metrics/LDTokenUsage.ts +0 -19
- package/src/api/metrics/OpenAiUsage.ts +0 -13
- package/src/api/metrics/VercelAISDKTokenUsage.ts +0 -15
- package/src/api/metrics/index.ts +0 -6
- package/src/api/providers/AIProvider.ts +0 -94
- package/src/api/providers/AIProviderFactory.ts +0 -152
- package/src/api/providers/index.ts +0 -2
- package/src/index.ts +0 -24
- package/tsconfig.eslint.json +0 -5
- package/tsconfig.json +0 -21
- package/tsconfig.ref.json +0 -7
- package/typedoc.json +0 -5
|
@@ -1,288 +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, JudgeResponse } 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
|
-
Object.entries(scores).forEach(([metricKey, evalScore]) => {
|
|
80
|
-
this._ldClient.track(metricKey, this._context, this.getTrackData(), evalScore.score);
|
|
81
|
-
});
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
trackJudgeResponse(response: JudgeResponse) {
|
|
85
|
-
Object.entries(response.evals).forEach(([metricKey, evalScore]) => {
|
|
86
|
-
this._ldClient.track(
|
|
87
|
-
metricKey,
|
|
88
|
-
this._context,
|
|
89
|
-
{ ...this.getTrackData(), judgeConfigKey: response.judgeConfigKey },
|
|
90
|
-
evalScore.score,
|
|
91
|
-
);
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
trackFeedback(feedback: { kind: LDFeedbackKind }): void {
|
|
96
|
-
this._trackedMetrics.feedback = feedback;
|
|
97
|
-
if (feedback.kind === LDFeedbackKind.Positive) {
|
|
98
|
-
this._ldClient.track('$ld:ai:feedback:user:positive', this._context, this.getTrackData(), 1);
|
|
99
|
-
} else if (feedback.kind === LDFeedbackKind.Negative) {
|
|
100
|
-
this._ldClient.track('$ld:ai:feedback:user:negative', this._context, this.getTrackData(), 1);
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
trackSuccess(): void {
|
|
105
|
-
this._trackedMetrics.success = true;
|
|
106
|
-
this._ldClient.track('$ld:ai:generation:success', this._context, this.getTrackData(), 1);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
trackError(): void {
|
|
110
|
-
this._trackedMetrics.success = false;
|
|
111
|
-
this._ldClient.track('$ld:ai:generation:error', this._context, this.getTrackData(), 1);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
async trackMetricsOf<TRes>(
|
|
115
|
-
metricsExtractor: (result: TRes) => LDAIMetrics,
|
|
116
|
-
func: () => Promise<TRes>,
|
|
117
|
-
): Promise<TRes> {
|
|
118
|
-
let result: TRes;
|
|
119
|
-
|
|
120
|
-
try {
|
|
121
|
-
result = await this.trackDurationOf(func);
|
|
122
|
-
} catch (err) {
|
|
123
|
-
this.trackError();
|
|
124
|
-
throw err;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
// Extract metrics after successful AI call
|
|
128
|
-
const metrics = metricsExtractor(result);
|
|
129
|
-
|
|
130
|
-
// Track success/error based on metrics
|
|
131
|
-
if (metrics.success) {
|
|
132
|
-
this.trackSuccess();
|
|
133
|
-
} else {
|
|
134
|
-
this.trackError();
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// Track token usage if available
|
|
138
|
-
if (metrics.usage) {
|
|
139
|
-
this.trackTokens(metrics.usage);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
return result;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
trackStreamMetricsOf<TStream>(
|
|
146
|
-
streamCreator: () => TStream,
|
|
147
|
-
metricsExtractor: (stream: TStream) => Promise<LDAIMetrics>,
|
|
148
|
-
): TStream {
|
|
149
|
-
const startTime = Date.now();
|
|
150
|
-
|
|
151
|
-
try {
|
|
152
|
-
// Create the stream synchronously
|
|
153
|
-
const stream = streamCreator();
|
|
154
|
-
|
|
155
|
-
// Start background metrics tracking (fire and forget)
|
|
156
|
-
this._trackStreamMetricsInBackground(stream, metricsExtractor, startTime);
|
|
157
|
-
|
|
158
|
-
// Return stream immediately for consumption
|
|
159
|
-
return stream;
|
|
160
|
-
} catch (error) {
|
|
161
|
-
// Track error if stream creation fails
|
|
162
|
-
this.trackDuration(Date.now() - startTime);
|
|
163
|
-
this.trackError();
|
|
164
|
-
throw error;
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
private async _trackStreamMetricsInBackground<TStream>(
|
|
169
|
-
stream: TStream,
|
|
170
|
-
metricsExtractor: (stream: TStream) => Promise<LDAIMetrics>,
|
|
171
|
-
startTime: number,
|
|
172
|
-
): Promise<void> {
|
|
173
|
-
try {
|
|
174
|
-
// Wait for metrics to be available
|
|
175
|
-
const metrics = await metricsExtractor(stream);
|
|
176
|
-
|
|
177
|
-
// Track success/error based on metrics
|
|
178
|
-
if (metrics.success) {
|
|
179
|
-
this.trackSuccess();
|
|
180
|
-
} else {
|
|
181
|
-
this.trackError();
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// Track token usage if available
|
|
185
|
-
if (metrics.usage) {
|
|
186
|
-
this.trackTokens(metrics.usage);
|
|
187
|
-
}
|
|
188
|
-
} catch (error) {
|
|
189
|
-
// If metrics extraction fails, track error
|
|
190
|
-
this.trackError();
|
|
191
|
-
} finally {
|
|
192
|
-
// Track duration regardless of success/error
|
|
193
|
-
this.trackDuration(Date.now() - startTime);
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
async trackOpenAIMetrics<
|
|
198
|
-
TRes extends {
|
|
199
|
-
usage?: {
|
|
200
|
-
total_tokens?: number;
|
|
201
|
-
prompt_tokens?: number;
|
|
202
|
-
completion_tokens?: number;
|
|
203
|
-
};
|
|
204
|
-
},
|
|
205
|
-
>(func: () => Promise<TRes>): Promise<TRes> {
|
|
206
|
-
try {
|
|
207
|
-
const result = await this.trackDurationOf(func);
|
|
208
|
-
this.trackSuccess();
|
|
209
|
-
if (result.usage) {
|
|
210
|
-
this.trackTokens(createOpenAiUsage(result.usage));
|
|
211
|
-
}
|
|
212
|
-
return result;
|
|
213
|
-
} catch (err) {
|
|
214
|
-
this.trackError();
|
|
215
|
-
throw err;
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
trackBedrockConverseMetrics<
|
|
220
|
-
TRes extends {
|
|
221
|
-
$metadata: { httpStatusCode?: number };
|
|
222
|
-
metrics?: { latencyMs?: number };
|
|
223
|
-
usage?: {
|
|
224
|
-
inputTokens?: number;
|
|
225
|
-
outputTokens?: number;
|
|
226
|
-
totalTokens?: number;
|
|
227
|
-
};
|
|
228
|
-
},
|
|
229
|
-
>(res: TRes): TRes {
|
|
230
|
-
if (res.$metadata?.httpStatusCode === 200) {
|
|
231
|
-
this.trackSuccess();
|
|
232
|
-
} else if (res.$metadata?.httpStatusCode && res.$metadata.httpStatusCode >= 400) {
|
|
233
|
-
this.trackError();
|
|
234
|
-
}
|
|
235
|
-
if (res.metrics && res.metrics.latencyMs) {
|
|
236
|
-
this.trackDuration(res.metrics.latencyMs);
|
|
237
|
-
}
|
|
238
|
-
if (res.usage) {
|
|
239
|
-
this.trackTokens(createBedrockTokenUsage(res.usage));
|
|
240
|
-
}
|
|
241
|
-
return res;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
async trackVercelAISDKGenerateTextMetrics<
|
|
245
|
-
TRes extends {
|
|
246
|
-
usage?: {
|
|
247
|
-
totalTokens?: number;
|
|
248
|
-
inputTokens?: number;
|
|
249
|
-
promptTokens?: number;
|
|
250
|
-
outputTokens?: number;
|
|
251
|
-
completionTokens?: number;
|
|
252
|
-
};
|
|
253
|
-
},
|
|
254
|
-
>(func: () => Promise<TRes>): Promise<TRes> {
|
|
255
|
-
try {
|
|
256
|
-
const result = await this.trackDurationOf(func);
|
|
257
|
-
this.trackSuccess();
|
|
258
|
-
if (result.usage) {
|
|
259
|
-
this.trackTokens(createVercelAISDKTokenUsage(result.usage));
|
|
260
|
-
}
|
|
261
|
-
return result;
|
|
262
|
-
} catch (err) {
|
|
263
|
-
this.trackError();
|
|
264
|
-
throw err;
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
trackTokens(tokens: LDTokenUsage): void {
|
|
269
|
-
this._trackedMetrics.tokens = tokens;
|
|
270
|
-
const trackData = this.getTrackData();
|
|
271
|
-
if (tokens.total > 0) {
|
|
272
|
-
this._ldClient.track('$ld:ai:tokens:total', this._context, trackData, tokens.total);
|
|
273
|
-
}
|
|
274
|
-
if (tokens.input > 0) {
|
|
275
|
-
this._ldClient.track('$ld:ai:tokens:input', this._context, trackData, tokens.input);
|
|
276
|
-
}
|
|
277
|
-
if (tokens.output > 0) {
|
|
278
|
-
this._ldClient.track('$ld:ai:tokens:output', this._context, trackData, tokens.output);
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
/**
|
|
283
|
-
* Get a summary of the tracked metrics.
|
|
284
|
-
*/
|
|
285
|
-
getSummary(): LDAIMetricSummary {
|
|
286
|
-
return { ...this._trackedMetrics };
|
|
287
|
-
}
|
|
288
|
-
}
|
package/src/LDClientMin.ts
DELETED
|
@@ -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
|
-
}
|
package/src/api/LDAIClient.ts
DELETED
|
@@ -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
|
-
}
|