-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathLanguageModelsPage.tsx
More file actions
555 lines (510 loc) · 17.2 KB
/
Copy pathLanguageModelsPage.tsx
File metadata and controls
555 lines (510 loc) · 17.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
"use client";
import { useState, useMemo } from "react";
import { useSWRConfig } from "swr";
import { useAdminLLMProviders } from "@/lib/languageModels/hooks";
import { PageLoader } from "@opal/layouts";
import { Content, ContentAction, InputHorizontal, toast } from "@opal/layouts";
import {
Button,
Divider,
MessageCard,
SelectCard,
Text,
Card,
} from "@opal/components";
import { Hoverable, Disabled } from "@opal/core";
import { SvgArrowExchange, SvgSettings, SvgTrash } from "@opal/icons";
import { SettingsLayouts } from "@opal/layouts";
import { ADMIN_ROUTES } from "@/lib/admin-routes";
import * as GeneralLayouts from "@/layouts/general-layouts";
import { getProvider } from "@/lib/languageModels";
import {
refreshLlmProviderCaches,
setDefaultLlmModelAndRefresh,
} from "@/lib/languageModels/cache";
import { deleteLlmProvider } from "@/lib/languageModels/svc";
import ModelSelector from "@/sections/model-selector/ModelSelector";
import { ConfirmationModalLayout } from "@opal/layouts";
import { useCreateModal } from "@opal/components";
import { LLMProviderName, LLMProviderView } from "@/lib/languageModels/types";
import { Section } from "@/layouts/general-layouts";
import { markdown } from "@opal/utils";
import { usePHFeatureFlag, PHFeatureFlag } from "@/lib/analytics/hooks";
import CostOverridesPanel from "@/views/admin/CostOverridesPanel";
const route = ADMIN_ROUTES.LLM_MODELS;
function providerDisplayName(provider: LLMProviderView): string {
return provider.name || getProvider(provider.provider, provider).productName;
}
// ============================================================================
// Provider grouping (keyed by provider name from the API)
// ============================================================================
// The "Add Provider" area is split into labeled groups. Provider names must
// match the backend's WELL_KNOWN_PROVIDER_NAMES (minus any that lack a
// dedicated modal); order within each group controls display order.
interface ProviderGroup {
title: string;
description?: string;
// Emphasized (main-content) header vs. a lighter secondary sub-header.
emphasis?: boolean;
providerNames: string[];
// Append the custom-provider card to this group.
includeCustom?: boolean;
}
const PROVIDER_GROUPS: ProviderGroup[] = [
{
title: "Add Provider",
description: "Onyx supports both popular providers and self-hosted models.",
emphasis: true,
providerNames: [
LLMProviderName.OPENAI,
LLMProviderName.ANTHROPIC,
LLMProviderName.VERTEX_AI,
LLMProviderName.BEDROCK,
LLMProviderName.AZURE,
],
},
{
title: "Gateways & Routers",
providerNames: [
LLMProviderName.OPENROUTER,
LLMProviderName.LITELLM_PROXY,
LLMProviderName.PORTKEY,
LLMProviderName.NEBIUS_TOKENFACTORY,
LLMProviderName.BIFROST,
],
},
{
title: "Self-hosted & Custom",
providerNames: [
LLMProviderName.OLLAMA_CHAT,
LLMProviderName.LM_STUDIO,
LLMProviderName.OPENAI_COMPATIBLE,
],
includeCustom: true,
},
];
// ============================================================================
// ExistingProviderCard — card for configured (existing) providers
// ============================================================================
interface ExistingProviderCardProps {
provider: LLMProviderView;
isDefault: boolean;
isLastProvider: boolean;
onBeforeOpen?: () => void;
}
function ExistingProviderCard({
provider,
isDefault,
isLastProvider,
onBeforeOpen,
}: ExistingProviderCardProps) {
const { mutate } = useSWRConfig();
const [isOpen, setIsOpen] = useState(false);
const deleteModal = useCreateModal();
const handleOpen = () => {
onBeforeOpen?.();
setIsOpen(true);
};
const handleDelete = async () => {
try {
await deleteLlmProvider(provider.id, isLastProvider);
await refreshLlmProviderCaches(mutate);
deleteModal.toggle(false);
toast.success("Provider deleted successfully!");
} catch (e) {
const message = e instanceof Error ? e.message : "Unknown error";
toast.error(`Failed to delete provider: ${message}`);
}
};
const { icon, companyName, Modal } = getProvider(provider.provider, provider);
return (
<>
{isOpen && (
<Modal existingLlmProvider={provider} onOpenChange={setIsOpen} />
)}
{deleteModal.isOpen && (
<ConfirmationModalLayout
icon={SvgTrash}
title={markdown(`Delete *${providerDisplayName(provider)}*`)}
onClose={() => deleteModal.toggle(false)}
submit={
<Button
variant="danger"
onClick={handleDelete}
disabled={isDefault && !isLastProvider}
>
Delete
</Button>
}
>
<Section alignItems="start" gap={2}>
{isDefault && !isLastProvider ? (
<Text font="main-ui-body" color="text-03">
Cannot delete the default provider. Select another provider as
the default prior to deleting this one.
</Text>
) : (
<>
<Text font="main-ui-body" color="text-03">
{markdown(
`All LLM models from provider **${providerDisplayName(
provider
)}** will be removed and unavailable for future chats. Chat history will be preserved.`
)}
</Text>
{isLastProvider && (
<Text font="main-ui-body" color="text-03">
Connect another provider to continue using chats.
</Text>
)}
</>
)}
</Section>
</ConfirmationModalLayout>
)}
<Hoverable.Root
group="ExistingProviderCard"
interaction={deleteModal.isOpen ? "hover" : "rest"}
>
<SelectCard
state="filled"
padding={2}
rounding="lg"
onClick={handleOpen}
>
<ContentAction
icon={icon}
title={providerDisplayName(provider)}
description={companyName}
sizePreset="main-ui"
variant="section"
padding={2}
tag={isDefault ? { title: "Default", color: "blue" } : undefined}
rightChildren={
<div className="flex flex-row">
<Hoverable.Item
group="ExistingProviderCard"
variant="appear-on-hover"
>
<Button
icon={SvgTrash}
prominence="tertiary"
aria-label={`Delete ${providerDisplayName(provider)}`}
onClick={(e) => {
e.stopPropagation();
deleteModal.toggle(true);
}}
/>
</Hoverable.Item>
<Button
icon={SvgSettings}
prominence="tertiary"
aria-label={`Edit ${providerDisplayName(provider)}`}
onClick={(e) => {
e.stopPropagation();
handleOpen();
}}
/>
</div>
}
/>
</SelectCard>
</Hoverable.Root>
</>
);
}
// ============================================================================
// NewProviderCard — card for the "Add Provider" list
// ============================================================================
interface NewProviderCardProps {
providerName: string;
isFirstProvider: boolean;
onBeforeOpen?: () => void;
}
function NewProviderCard({
providerName,
isFirstProvider,
onBeforeOpen,
}: NewProviderCardProps) {
const [isOpen, setIsOpen] = useState(false);
const { icon, productName, companyName, Modal } = getProvider(providerName);
const handleOpen = () => {
onBeforeOpen?.();
setIsOpen(true);
};
return (
<SelectCard
state="empty"
padding={2}
rounding="lg"
onClick={handleOpen}
>
<ContentAction
icon={icon}
title={productName}
description={companyName}
sizePreset="main-ui"
variant="section"
padding={2}
rightChildren={
<Button
rightIcon={SvgArrowExchange}
prominence="tertiary"
onClick={(e) => {
e.stopPropagation();
handleOpen();
}}
>
Connect
</Button>
}
/>
{isOpen && (
<Modal
shouldMarkAsDefault={isFirstProvider}
onOpenChange={setIsOpen}
/>
)}
</SelectCard>
);
}
// ============================================================================
// NewCustomProviderCard — card for adding a custom LLM provider
// ============================================================================
interface NewCustomProviderCardProps {
isFirstProvider: boolean;
onBeforeOpen?: () => void;
}
function NewCustomProviderCard({
isFirstProvider,
onBeforeOpen,
}: NewCustomProviderCardProps) {
const [isOpen, setIsOpen] = useState(false);
const { icon, productName, companyName, Modal } = getProvider("custom");
const handleOpen = () => {
onBeforeOpen?.();
setIsOpen(true);
};
return (
<>
{isOpen && (
<Modal
shouldMarkAsDefault={isFirstProvider}
onOpenChange={setIsOpen}
/>
)}
<SelectCard
state="empty"
padding={2}
rounding="lg"
onClick={handleOpen}
>
<ContentAction
icon={icon}
title={productName}
description={companyName}
sizePreset="main-ui"
variant="section"
padding={2}
rightChildren={
<Button
rightIcon={SvgArrowExchange}
prominence="tertiary"
onClick={(e) => {
e.stopPropagation();
handleOpen();
}}
>
Set Up
</Button>
}
/>
</SelectCard>
</>
);
}
// ============================================================================
// LanguageModelsPage — main page component
// ============================================================================
export default function LanguageModelsPage() {
const { mutate } = useSWRConfig();
const { llmProviders: existingLlmProviders, defaultText } =
useAdminLLMProviders();
const isConfigurationDisabled = usePHFeatureFlag(
PHFeatureFlag.LANGUAGE_MODEL_CONFIGURATION_DISABLED
);
const [isDefaultModelSelectorOpen, setIsDefaultModelSelectorOpen] =
useState(false);
// Resolve the current default to a model_configuration_id for ModelSelector
const defaultModelConfigId = useMemo(() => {
if (!defaultText || !existingLlmProviders) return null;
const provider = existingLlmProviders.find(
(p) => p.id === defaultText.provider_id
);
return (
provider?.model_configurations.find(
(m) => m.name === defaultText.model_name
)?.id ?? null
);
}, [defaultText, existingLlmProviders]);
if (!existingLlmProviders) {
return <PageLoader />;
}
const hasProviders = existingLlmProviders.length > 0;
const isFirstProvider = !hasProviders;
// Pre-sort providers so the default appears first
const sortedProviders = [...existingLlmProviders].sort((a, b) => {
const aIsDefault = defaultText?.provider_id === a.id;
const bIsDefault = defaultText?.provider_id === b.id;
if (aIsDefault && !bIsDefault) return -1;
if (!aIsDefault && bIsDefault) return 1;
return 0;
});
// Pre-filter to providers that have at least one visible model
const providersWithVisibleModels = existingLlmProviders
.map((provider) => ({
provider,
visibleModels: provider.model_configurations.filter((m) => m.is_visible),
}))
.filter(({ visibleModels }) => visibleModels.length > 0);
// Default model logic — use the global default from the API response
const currentDefaultValue = defaultText
? `${defaultText.provider_id}:${defaultText.model_name}`
: undefined;
async function handleDefaultModelChange(compositeValue: string) {
const separatorIndex = compositeValue.indexOf(":");
const providerId = Number(compositeValue.slice(0, separatorIndex));
const modelName = compositeValue.slice(separatorIndex + 1);
await setDefaultLlmModelAndRefresh(providerId, modelName, mutate);
}
return (
<SettingsLayouts.Root>
<SettingsLayouts.Header icon={route.icon} title={route.title} divider />
<SettingsLayouts.Body>
{hasProviders ? (
<Card border="solid" rounding="lg">
<InputHorizontal
title="Default Model"
description="This model will be used by Onyx by default in your chats."
center
withLabel
>
<ModelSelector
value={defaultModelConfigId}
onChange={(opt) => {
const provider = existingLlmProviders?.find(
(p) =>
p.provider === opt.provider &&
(p.name === opt.name || (!p.name && !opt.name))
);
if (provider) {
void handleDefaultModelChange(
`${provider.id}:${opt.modelName}`
);
}
}}
side="bottom"
open={isDefaultModelSelectorOpen}
onOpenChange={setIsDefaultModelSelectorOpen}
/>
</InputHorizontal>
</Card>
) : (
<MessageCard
variant="info"
title="Set up an LLM provider to start chatting."
/>
)}
{/* ── Available Providers (only when providers exist) ── */}
{hasProviders && (
<>
<GeneralLayouts.Section
gap={3}
height="fit"
alignItems="stretch"
justifyContent="start"
>
<Content
title="Available Providers"
sizePreset="main-content"
variant="section"
/>
<div className="flex flex-col gap-2">
{sortedProviders.map((provider) => (
<ExistingProviderCard
key={provider.id}
provider={provider}
isDefault={defaultText?.provider_id === provider.id}
isLastProvider={sortedProviders.length === 1}
onBeforeOpen={() =>
setIsDefaultModelSelectorOpen(false)
}
/>
))}
</div>
</GeneralLayouts.Section>
<Divider paddingParallel={0} paddingPerpendicular={0} />
</>
)}
{/* ── LLM configuration disablement notice ── */}
{isConfigurationDisabled && (
<MessageCard
title="New LLM configuration temporarily unavailable."
description="Existing LLM providers can still be used and updated."
headerPadding={1}
/>
)}
{/* ── Add Provider groups (always visible) ── */}
<Disabled disabled={isConfigurationDisabled}>
<div className="@container/providercards flex flex-col gap-8">
{PROVIDER_GROUPS.map((group) => (
<GeneralLayouts.Section
key={group.title}
gap={3}
height="fit"
alignItems="stretch"
justifyContent="start"
>
{group.emphasis ? (
<Content
title={group.title}
description={group.description}
sizePreset="main-content"
variant="section"
/>
) : (
<Text font="main-ui-action" color="text-03">
{group.title}
</Text>
)}
<div className="grid grid-cols-1 @xl/providercards:grid-cols-2 gap-2">
{group.providerNames.map((name) => (
<NewProviderCard
key={name}
providerName={name}
isFirstProvider={isFirstProvider}
onBeforeOpen={() =>
setIsDefaultModelSelectorOpen(false)
}
/>
))}
{group.includeCustom && (
<NewCustomProviderCard
isFirstProvider={isFirstProvider}
onBeforeOpen={() =>
setIsDefaultModelSelectorOpen(false)
}
/>
)}
</div>
</GeneralLayouts.Section>
))}
</div>
</Disabled>
<Divider paddingParallel={0} paddingPerpendicular={0} />
{/* ── Cost Overrides — negotiated per-model rates for usage costing ── */}
<CostOverridesPanel />
</SettingsLayouts.Body>
</SettingsLayouts.Root>
);
}