forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupstream-ratio-sync-helpers.ts
More file actions
409 lines (350 loc) 路 11.3 KB
/
Copy pathupstream-ratio-sync-helpers.ts
File metadata and controls
409 lines (350 loc) 路 11.3 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
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { RatioType } from '../types'
import {
MODELS_DEV_PRESET_ID,
MODELS_DEV_PRESET_NAME,
OFFICIAL_CHANNEL_ID,
OFFICIAL_CHANNEL_NAME,
RATIO_TYPE_OPTIONS,
} from './constants'
export type RatioDifferenceEntry = {
current: number | string | null
upstreams: Record<string, number | string | 'same'>
confidence: Record<string, boolean>
}
export type ModelRow = {
key: string
model: string
ratioTypes: Partial<Record<RatioType, RatioDifferenceEntry>>
billingConflict: boolean
}
export type ResolutionsMap = Record<string, Record<string, number | string>>
export type ResolutionSelection = {
model: string
ratioType: RatioType
value: number | string
sourceName: string
}
export type ResolvedResolutionSelection = ResolutionSelection & {
ratioType: RatioType
}
export type ResolutionRemoval = {
model: string
ratioType: RatioType
}
export type ResolutionRemovalPlan = Map<string, Set<RatioType>>
export const RATIO_SYNC_FIELDS: RatioType[] = [
'model_ratio',
'completion_ratio',
'cache_ratio',
'create_cache_ratio',
'image_ratio',
'audio_ratio',
'audio_completion_ratio',
]
export const SYNC_FIELD_ORDER: RatioType[] = [
...RATIO_SYNC_FIELDS,
'model_price',
'billing_mode',
'billing_expr',
]
export const NUMERIC_SYNC_FIELDS = new Set<string>([
...RATIO_SYNC_FIELDS,
'model_price',
])
export function getSyncFieldLabel(
ratioType: string,
t: (key: string) => string
): string {
const opt = RATIO_TYPE_OPTIONS.find((o) => o.value === ratioType)
if (opt) return t(opt.label)
return ratioType
}
export function getOrderedRatioTypes(
ratioTypes: Partial<Record<RatioType, RatioDifferenceEntry>>,
filter?: string
): RatioType[] {
const keys = Object.keys(ratioTypes) as RatioType[]
const ordered = [
...SYNC_FIELD_ORDER.filter((f) => keys.includes(f)),
...keys.filter((f) => !SYNC_FIELD_ORDER.includes(f)),
]
if (!filter || filter === '__all__') return ordered
return ordered.filter((f) => f === filter)
}
export function getPreferredSyncField(
ratioTypes: Partial<Record<RatioType, RatioDifferenceEntry>>,
ratioType: RatioType,
sourceName: string
): RatioType {
const exprValue = ratioTypes.billing_expr?.upstreams?.[sourceName]
if (
ratioType !== 'billing_expr' &&
exprValue !== null &&
exprValue !== undefined &&
exprValue !== 'same'
) {
return 'billing_expr'
}
return ratioType
}
export function getVisibleRatioTypesForSource(
ratioTypes: Partial<Record<RatioType, RatioDifferenceEntry>>,
sourceName: string,
filter?: string
): RatioType[] {
return getOrderedRatioTypes(ratioTypes, filter).filter(
(ratioType) =>
getPreferredSyncField(ratioTypes, ratioType, sourceName) === ratioType
)
}
export function getAlignedRatioTypes(
ratioTypes: Partial<Record<RatioType, RatioDifferenceEntry>>,
sourceNames: string[],
filter?: string
): RatioType[] {
const ordered = getOrderedRatioTypes(ratioTypes, filter)
if (sourceNames.length === 0) return ordered
const visible = new Set<RatioType>()
sourceNames.forEach((sourceName) => {
getVisibleRatioTypesForSource(ratioTypes, sourceName, filter).forEach(
(ratioType) => visible.add(ratioType)
)
})
return ordered.filter((ratioType) => visible.has(ratioType))
}
export function getBillingCategory(
ratioType: string
): 'price' | 'ratio' | 'tiered' {
if (ratioType === 'model_price') return 'price'
if (ratioType === 'billing_mode' || ratioType === 'billing_expr') {
return 'tiered'
}
return 'ratio'
}
export function isSelectableUpstreamValue(
value: number | string | 'same' | null | undefined
): boolean {
return value !== null && value !== undefined && value !== 'same'
}
export function getUpstreamDisplayName(sourceName: string): string {
const synthesizedPresets = [
{ name: OFFICIAL_CHANNEL_NAME, id: OFFICIAL_CHANNEL_ID },
{ name: MODELS_DEV_PRESET_NAME, id: MODELS_DEV_PRESET_ID },
]
for (const preset of synthesizedPresets) {
if (sourceName === `${preset.name}(${preset.id})`) {
return preset.name
}
}
return sourceName
}
export function isSelectedResolutionValue(
resolutions: ResolutionsMap,
model: string,
ratioType: RatioType,
upstreamValue: number | string | 'same' | null | undefined
): boolean {
if (!isSelectableUpstreamValue(upstreamValue)) return false
const selectedValue = resolutions[model]?.[ratioType]
if (selectedValue === undefined) return false
if (NUMERIC_SYNC_FIELDS.has(ratioType)) {
const selectedNumber = Number(selectedValue)
const upstreamNumber = Number(upstreamValue)
return (
Number.isFinite(selectedNumber) &&
Number.isFinite(upstreamNumber) &&
selectedNumber === upstreamNumber
)
}
return selectedValue === upstreamValue
}
export function deleteResolutionField(
resolutions: ResolutionsMap,
model: string,
ratioType: RatioType
): ResolutionsMap {
return applyResolutionRemovals(resolutions, [{ model, ratioType }])
}
function getDraftModelResolution(
drafts: Map<string, Record<string, number | string>>,
resolutions: ResolutionsMap,
model: string
): Record<string, number | string> {
const existingDraft = drafts.get(model)
if (existingDraft) return existingDraft
const draft = resolutions[model] ? { ...resolutions[model] } : {}
drafts.set(model, draft)
return draft
}
function applyResolutionSelectionToDraft(
drafts: Map<string, Record<string, number | string>>,
resolutions: ResolutionsMap,
differences: Record<string, Partial<Record<RatioType, RatioDifferenceEntry>>>,
selection: ResolutionSelection
) {
const modelDiffs = differences[selection.model]
const preferredType = getPreferredSyncField(
modelDiffs || {},
selection.ratioType,
selection.sourceName
)
const preferredValue =
preferredType === selection.ratioType
? selection.value
: (modelDiffs?.[preferredType]?.upstreams?.[selection.sourceName] ??
selection.value)
const finalType = preferredType
const finalValue = preferredValue as number | string
const category = getBillingCategory(finalType)
const newModelRes = getDraftModelResolution(
drafts,
resolutions,
selection.model
)
Object.keys(newModelRes).forEach((rt) => {
if (
category !== 'tiered' &&
getBillingCategory(rt) !== 'tiered' &&
getBillingCategory(rt) !== category
) {
delete newModelRes[rt]
}
})
newModelRes[finalType] = finalValue
if (category === 'tiered' && modelDiffs) {
const modeVal = modelDiffs.billing_mode?.upstreams?.[selection.sourceName]
const exprVal = modelDiffs.billing_expr?.upstreams?.[selection.sourceName]
if (modeVal !== undefined && modeVal !== null && modeVal !== 'same') {
newModelRes['billing_mode'] = modeVal
} else if (finalType === 'billing_expr') {
newModelRes['billing_mode'] = 'tiered_expr'
}
if (exprVal !== undefined && exprVal !== null && exprVal !== 'same') {
newModelRes['billing_expr'] = exprVal
}
}
}
export function resolveResolutionSelection(
differences: Record<string, Partial<Record<RatioType, RatioDifferenceEntry>>>,
selection: ResolutionSelection
): ResolvedResolutionSelection {
const modelDiffs = differences[selection.model]
const preferredType = getPreferredSyncField(
modelDiffs || {},
selection.ratioType,
selection.sourceName
)
const preferredValue =
preferredType === selection.ratioType
? selection.value
: (modelDiffs?.[preferredType]?.upstreams?.[selection.sourceName] ??
selection.value)
return {
...selection,
ratioType: preferredType,
value: preferredValue as number | string,
}
}
export function getEffectiveResolutionSelections(
differences: Record<string, Partial<Record<RatioType, RatioDifferenceEntry>>>,
selections: ResolutionSelection[]
): ResolvedResolutionSelection[] {
const effectiveByKey = new Map<string, ResolvedResolutionSelection>()
selections.forEach((selection) => {
const resolved = resolveResolutionSelection(differences, selection)
const category = getBillingCategory(resolved.ratioType)
if (category !== 'tiered') {
for (const [key, existing] of effectiveByKey) {
if (
existing.model === resolved.model &&
getBillingCategory(existing.ratioType) !== 'tiered' &&
getBillingCategory(existing.ratioType) !== category
) {
effectiveByKey.delete(key)
}
}
}
effectiveByKey.set(`${resolved.model}\u0000${resolved.ratioType}`, resolved)
})
return [...effectiveByKey.values()]
}
export function applyResolutionSelections(
resolutions: ResolutionsMap,
differences: Record<string, Partial<Record<RatioType, RatioDifferenceEntry>>>,
selections: ResolutionSelection[]
): ResolutionsMap {
if (selections.length === 0) return resolutions
const next = { ...resolutions }
const drafts = new Map<string, Record<string, number | string>>()
selections.forEach((selection) => {
applyResolutionSelectionToDraft(drafts, resolutions, differences, selection)
})
drafts.forEach((draft, model) => {
if (Object.keys(draft).length === 0) {
delete next[model]
} else {
next[model] = draft
}
})
return next
}
export function applyResolutionSelection(
resolutions: ResolutionsMap,
differences: Record<string, Partial<Record<RatioType, RatioDifferenceEntry>>>,
selection: ResolutionSelection
): ResolutionsMap {
return applyResolutionSelections(resolutions, differences, [selection])
}
export function applyResolutionRemovals(
resolutions: ResolutionsMap,
removals: ResolutionRemoval[]
): ResolutionsMap {
if (removals.length === 0) return resolutions
const plan: ResolutionRemovalPlan = new Map()
removals.forEach((removal) => {
const ratioTypes = plan.get(removal.model)
if (ratioTypes) {
ratioTypes.add(removal.ratioType)
} else {
plan.set(removal.model, new Set([removal.ratioType]))
}
})
return applyResolutionRemovalPlan(resolutions, plan)
}
export function applyResolutionRemovalPlan(
resolutions: ResolutionsMap,
plan: ResolutionRemovalPlan
): ResolutionsMap {
if (plan.size === 0) return resolutions
const next = { ...resolutions }
plan.forEach((ratioTypes, model) => {
const current = resolutions[model]
if (!current) return
const draft = { ...current }
ratioTypes.forEach((ratioType) => {
delete draft[ratioType]
if (ratioType === 'billing_expr') delete draft['billing_mode']
if (ratioType === 'billing_mode') delete draft['billing_expr']
})
if (Object.keys(draft).length === 0) {
delete next[model]
} else {
next[model] = draft
}
})
return next
}