-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathuseModelComparison.hook.tsx
More file actions
387 lines (339 loc) · 14.2 KB
/
useModelComparison.hook.tsx
File metadata and controls
387 lines (339 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
/**
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { useState, useCallback, useMemo, useRef } from 'react';
import { useAuth } from '../../../auth/useAuth';
import { ChatOpenAI } from '@langchain/openai';
import { SelectProps } from '@cloudscape-design/components';
import { IModel, ModelStatus } from '../../../shared/model/model-management.model';
import { RESTAPI_URI, RESTAPI_VERSION } from '../../utils';
import { useAppDispatch } from '../../../config/store';
import { useNotificationService } from '../../../shared/util/hooks';
import { MODEL_COMPARISON_CONFIG, MESSAGES } from '../config/modelComparison.config';
import { IChatConfiguration } from '../../../shared/model/chat.configurations.model';
export type ComparisonResponse = {
modelId: string;
response: string;
loading: boolean;
streaming: boolean;
error?: string;
usage?: any;
};
export type ModelSelection = {
id: string;
selectedModel: SelectProps.Option | null;
};
export const useModelComparison = (models: IModel[], chatConfig: IChatConfiguration) => {
const dispatch = useAppDispatch();
const auth = useAuth();
const notificationService = useNotificationService(dispatch);
const [modelSelections, setModelSelections] = useState<ModelSelection[]>([
{ id: '1', selectedModel: null },
{ id: '2', selectedModel: null }
]);
const [prompt, setPrompt] = useState<string>('');
const [responses, setResponses] = useState<ComparisonResponse[]>([]);
const [isComparing, setIsComparing] = useState<boolean>(false);
const stopRequested = useRef(false);
// Filter models to only show InService text generation models - memoized for performance
const availableModels = useMemo(() =>
models
.filter((model) =>
model.status === ModelStatus.InService &&
model.modelType === 'textgen'
)
.map((model) => ({
label: model.modelName,
value: model.modelId,
description: model.modelId
})),
[models]
);
const createOpenAiClient = useCallback((modelId: string, streaming: boolean = false) => {
const model = models.find((m) => m.modelId === modelId);
if (!model) return null;
const sessionConfig = chatConfig.sessionConfiguration;
const modelArgs = sessionConfig.modelArgs;
const modelConfig = {
modelName: model.modelId,
// Use auth token as API key - LangChain will pass it in the Authorization header
apiKey: auth.user?.id_token || 'dummy-key',
maxRetries: 0,
configuration: {
baseURL: `${RESTAPI_URI}/${RESTAPI_VERSION}/serve`,
},
streaming,
maxTokens: sessionConfig.max_tokens || MODEL_COMPARISON_CONFIG.DEFAULT_MAX_TOKENS,
temperature: modelArgs.temperature,
topP: modelArgs.top_p,
frequencyPenalty: modelArgs.frequency_penalty,
presencePenalty: modelArgs.presence_penalty,
n: modelArgs.n,
seed: modelArgs.seed,
stop: modelArgs.stop,
};
return new ChatOpenAI(modelConfig);
}, [models, auth.user?.id_token, chatConfig]);
const generateModelResponse = async (
modelId: string,
userPrompt: string,
updateCallback: (modelId: string, update: Partial<ComparisonResponse>) => void
): Promise<void> => {
const startTime = performance.now(); // Start client timer
const useStreaming = chatConfig.sessionConfiguration.streaming || false;
const llmClient = createOpenAiClient(modelId, useStreaming);
if (!llmClient) {
throw new Error(`Failed to create client for model ${modelId}`);
}
// Create messages similar to Chat.tsx
const systemMessage = chatConfig.promptConfiguration.promptTemplate || MODEL_COMPARISON_CONFIG.DEFAULT_SYSTEM_MESSAGE;
const messages = [
{
role: 'system',
content: systemMessage
},
{
role: 'user',
content: userPrompt
}
];
try {
if (useStreaming) {
// Set streaming state
updateCallback(modelId, { streaming: true });
const stream = await llmClient.stream(messages);
const responseChunks: string[] = [];
for await (const chunk of stream) {
// Check if stop was requested
if (stopRequested.current) {
const responseTime = (performance.now() - startTime) / 1000;
updateCallback(modelId, {
response: responseChunks.join(''),
loading: false,
streaming: false,
usage: {
responseTime: parseFloat(responseTime.toFixed(2))
}
});
return;
}
const content = chunk.content as string;
responseChunks.push(content);
// Update response with accumulated content
updateCallback(modelId, {
response: responseChunks.join(''),
streaming: true
});
}
// Calculate response time and finalize streaming
const responseTime = (performance.now() - startTime) / 1000;
updateCallback(modelId, {
response: responseChunks.join(''),
loading: false,
streaming: false,
usage: {
responseTime: parseFloat(responseTime.toFixed(2))
}
});
} else {
// Check if stop was requested before non-streaming call
if (stopRequested.current) {
const responseTime = (performance.now() - startTime) / 1000;
updateCallback(modelId, {
response: '',
loading: false,
streaming: false,
usage: {
responseTime: parseFloat(responseTime.toFixed(2))
}
});
return;
}
// Non-streaming response
const response = await llmClient.invoke(messages);
// Debug: Log the response structure to understand how to extract usage info
console.log('LangChain response structure:', {
response_metadata: response.response_metadata,
additional_kwargs: response.additional_kwargs,
full_response: response
});
// Calculate response time
const responseTime = (performance.now() - startTime) / 1000;
// Extract usage information from response metadata (LangChain converts to camelCase)
const usage = response.response_metadata?.tokenUsage;
console.log('Extracted values:', {
usage,
tokenUsage: response.response_metadata?.tokenUsage,
additional_kwargs: response.additional_kwargs
});
const finalUsage = {
...usage,
responseTime: parseFloat(responseTime.toFixed(2))
};
updateCallback(modelId, {
response: response.content as string,
loading: false,
streaming: false,
usage: finalUsage,
});
}
} catch (error) {
console.error(`Error generating response for model ${modelId}:`, error);
throw new Error(`Failed to generate response: ${error instanceof Error ? error.message : 'Unknown error'}`, {
cause: error,
});
}
};
const addModelComparison = useCallback(() => {
setModelSelections((prev) => {
if (prev.length < MODEL_COMPARISON_CONFIG.MAX_MODELS) {
const newId = (prev.length + 1).toString();
return [...prev, { id: newId, selectedModel: null }];
}
return prev;
});
}, []);
const removeModelComparison = useCallback((idToRemove: string) => {
setModelSelections((prev) => {
if (prev.length > MODEL_COMPARISON_CONFIG.MIN_MODELS) {
return prev.filter((selection) => selection.id !== idToRemove);
}
return prev;
});
}, []);
const updateModelSelection = useCallback((id: string, selectedModel: SelectProps.Option | null) => {
setModelSelections((prev) =>
prev.map((selection) =>
selection.id === id ? { ...selection, selectedModel } : selection
)
);
}, []);
// Get available models for a specific dropdown, excluding already selected models - memoized
const getAvailableModelsForSelection = useCallback((currentSelectionId: string) => {
const selectedModelIds = modelSelections
.filter((selection) => selection.id !== currentSelectionId && selection.selectedModel)
.map((selection) => selection.selectedModel!.value);
return availableModels.filter((model) => !selectedModelIds.includes(model.value));
}, [modelSelections, availableModels]);
const handleCompare = async () => {
const selectedModels = modelSelections
.filter((selection) => selection.selectedModel)
.map((selection) => selection.selectedModel!);
if (selectedModels.length < MODEL_COMPARISON_CONFIG.MIN_MODELS) {
return;
}
setIsComparing(true);
stopRequested.current = false;
const initialResponses = selectedModels.map((model) => ({
modelId: model.value!,
response: '',
loading: true,
streaming: false
}));
setResponses(initialResponses);
// Update individual responses as they complete
const updateResponse = (modelId: string, update: Partial<ComparisonResponse>) => {
setResponses((prevResponses) =>
prevResponses.map((response) =>
response.modelId === modelId
? { ...response, ...update }
: response
)
);
};
// Make API calls to all selected models and update each as it completes
const responsePromises = selectedModels.map(async (model) => {
const modelStartTime = performance.now();
try {
await generateModelResponse(model.value!, prompt, updateResponse);
} catch (error) {
const responseTime = (performance.now() - modelStartTime) / 1000;
updateResponse(model.value!, {
response: '',
loading: false,
streaming: false,
error: error.message || MESSAGES.FAILED_TO_GET_RESPONSE,
usage: {
responseTime: parseFloat(responseTime.toFixed(2))
}
});
}
});
// Wait for all requests to complete before setting isComparing to false
try {
await Promise.all(responsePromises);
} catch (error) {
console.error('Error in model comparison:', error);
notificationService.generateNotification(
MESSAGES.FAILED_TO_COMPARE_MODELS,
'error',
undefined,
error.message ? <p>{error.message}</p> : undefined
);
} finally {
setIsComparing(false);
}
};
const stopComparison = useCallback(() => {
stopRequested.current = true;
setIsComparing(false);
notificationService.generateNotification('Model comparison stopped by user', 'info');
// Update any still-loading responses to stopped state
setResponses((prevResponses) =>
prevResponses.map((response) =>
response.loading || response.streaming
? { ...response, loading: false, streaming: false }
: response
)
);
}, [notificationService]);
const resetComparison = useCallback(() => {
setModelSelections([
{ id: '1', selectedModel: null },
{ id: '2', selectedModel: null }
]);
setPrompt('');
setResponses([]);
setIsComparing(false);
stopRequested.current = false;
}, []);
// Memoize expensive calculations
const selectedModelsCount = useMemo(() =>
modelSelections.filter((selection) => selection.selectedModel).length,
[modelSelections]
);
const canCompare = useMemo(() =>
selectedModelsCount >= MODEL_COMPARISON_CONFIG.MIN_MODELS && !isComparing,
[selectedModelsCount, isComparing]
);
// Determine if we should show stop button - simplified like Chat.tsx
const shouldShowStopButton = isComparing;
return {
// State
modelSelections,
prompt,
responses,
isComparing,
availableModels,
canCompare,
shouldShowStopButton,
// Actions
setPrompt,
addModelComparison,
removeModelComparison,
updateModelSelection,
getAvailableModelsForSelection,
handleCompare,
stopComparison,
resetComparison
};
};