dsh-nikoapi 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.en.md +110 -0
- package/README.md +109 -2
- package/client.js +398 -0
- package/cordis.patch.yml +6 -0
- package/icon.svg +7 -0
- package/images/key_permissions.png +0 -0
- package/images/qrcode_main.jpg +0 -0
- package/images/qrcode_notify.jpg +0 -0
- package/index.js +736 -0
- package/lib/billing-expression.js +431 -0
- package/lib/costmeter-prices.js +96 -0
- package/lib/costmeter.js +162 -0
- package/lib/groups.js +68 -0
- package/lib/http.js +147 -0
- package/lib/models.js +192 -0
- package/lib/niko.js +254 -0
- package/lib/price-calculator.js +65 -0
- package/lib/pricing.js +174 -0
- package/lib/state.js +211 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +62 -3
package/lib/niko.js
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* NikoAPI (New API fork) client.
|
|
3
|
+
*
|
|
4
|
+
* Two credential kinds never mix: a dashboard management token (PAT) reads and
|
|
5
|
+
* edits key metadata, while one selected model key reads its own model catalog
|
|
6
|
+
* and usage. Nothing here returns a secret to a caller that renders it; the
|
|
7
|
+
* only method that produces a full key is `revealKey`, and its result goes
|
|
8
|
+
* straight into the credential store.
|
|
9
|
+
*/
|
|
10
|
+
import { HttpError, requestJson } from './http.js'
|
|
11
|
+
import { isLlmModel } from './models.js'
|
|
12
|
+
|
|
13
|
+
/** Marker for a permission the management token did not carry. */
|
|
14
|
+
export class NikoPermissionError extends Error {
|
|
15
|
+
/**
|
|
16
|
+
* @param {string} message safe, user-facing reason
|
|
17
|
+
* @param {string} scope the missing scope, e.g. `api_key:write`
|
|
18
|
+
*/
|
|
19
|
+
constructor(message, scope) {
|
|
20
|
+
super(message)
|
|
21
|
+
this.name = 'NikoPermissionError'
|
|
22
|
+
this.scope = scope
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {object} options
|
|
28
|
+
* @param {string} options.baseUrl site origin, e.g. `https://nikoapi.xyz`
|
|
29
|
+
* @param {typeof fetch} [options.fetch]
|
|
30
|
+
* @param {AbortSignal} [options.signal]
|
|
31
|
+
*/
|
|
32
|
+
export function createNikoClient({ baseUrl, fetch: fetchImpl, signal }) {
|
|
33
|
+
const origin = new URL(baseUrl).origin
|
|
34
|
+
|
|
35
|
+
/** @param {string} path @param {object} [extra] */
|
|
36
|
+
const call = async (path, extra = {}) => {
|
|
37
|
+
const response = await requestJson({ url: origin + path, origin, fetch: fetchImpl, signal, ...extra })
|
|
38
|
+
const body = response.body ?? {}
|
|
39
|
+
if (response.status === 401) {
|
|
40
|
+
throw new HttpError('credential rejected (401)', { status: 401, code: 'UNAUTHORIZED' })
|
|
41
|
+
}
|
|
42
|
+
if (response.status === 403) {
|
|
43
|
+
const scope = scopeFromBody(body)
|
|
44
|
+
throw new NikoPermissionError(`permission denied (403); required scope: ${scope}`, scope)
|
|
45
|
+
}
|
|
46
|
+
if (response.status < 200 || response.status >= 300) {
|
|
47
|
+
throw new HttpError(`upstream status ${response.status}`, { status: response.status, code: 'UPSTREAM' })
|
|
48
|
+
}
|
|
49
|
+
if (body.success === false) throw new HttpError('upstream refused the request', { code: 'UPSTREAM' })
|
|
50
|
+
if (extra.requireIdentity === true && response.authenticated !== true) throw new HttpError('account pricing identity was not confirmed', { code: 'UNAUTHORIZED' })
|
|
51
|
+
return body
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const auth = token => ({ authorization: `Bearer ${token}` })
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
origin,
|
|
58
|
+
|
|
59
|
+
/** Public site facts: version, quota unit, display currency. */
|
|
60
|
+
async status() {
|
|
61
|
+
const body = await call('/api/status')
|
|
62
|
+
const data = body.data ?? {}
|
|
63
|
+
return {
|
|
64
|
+
version: typeof data.version === 'string' ? data.version : '',
|
|
65
|
+
quotaPerUnit: positive(data.quota_per_unit) ?? 500_000,
|
|
66
|
+
displayCurrency: typeof data.quota_display_type === 'string' && data.quota_display_type !== '' ? data.quota_display_type : 'USD',
|
|
67
|
+
usdExchangeRate: positive(data.usd_exchange_rate) ?? 1,
|
|
68
|
+
systemName: typeof data.system_name === 'string' ? data.system_name : 'NikoAPI',
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Key metadata for the account, masked by the server.
|
|
74
|
+
* @param {string} pat management token
|
|
75
|
+
* @param {{ page?: number, size?: number }} [page]
|
|
76
|
+
*/
|
|
77
|
+
async listKeys(pat, page = {}) {
|
|
78
|
+
const pageNumber = Number.isInteger(page.page) && page.page > 0 ? page.page : 1
|
|
79
|
+
const pageSize = Number.isInteger(page.size) && page.size > 0 ? Math.min(page.size, 100) : 100
|
|
80
|
+
const query = `?p=${pageNumber}&size=${pageSize}`
|
|
81
|
+
const body = await call(`/api/token/${query}`, { headers: auth(pat) })
|
|
82
|
+
const data = body.data ?? {}
|
|
83
|
+
const items = Array.isArray(data.items) ? data.items : Array.isArray(data) ? data : []
|
|
84
|
+
return {
|
|
85
|
+
total: Number.isFinite(data.total) ? data.total : items.length,
|
|
86
|
+
items: items.map(normalizeKey).filter(item => item !== null),
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
|
|
90
|
+
/** Paginate all metadata. Refuse repeated/partial pages instead of pretending they are complete. */
|
|
91
|
+
async allKeys(pat) {
|
|
92
|
+
const items = new Map()
|
|
93
|
+
let total = 0
|
|
94
|
+
for (let page = 1; page <= 1000; page += 1) {
|
|
95
|
+
const result = await this.listKeys(pat, { page, size: 100 })
|
|
96
|
+
total = result.total
|
|
97
|
+
const before = items.size
|
|
98
|
+
for (const item of result.items) items.set(item.id, item)
|
|
99
|
+
if (items.size >= total) return { items: [...items.values()], total, complete: true }
|
|
100
|
+
if (items.size === before) throw new HttpError('key listing was incomplete; refresh and retry', { code: 'INCOMPLETE' })
|
|
101
|
+
}
|
|
102
|
+
throw new HttpError('key listing exceeded the page safety limit', { code: 'INCOMPLETE' })
|
|
103
|
+
},
|
|
104
|
+
|
|
105
|
+
/** Optional auto groups plus the per-key limit the site enforces. */
|
|
106
|
+
async autoGroups(pat) {
|
|
107
|
+
const body = await call('/api/token/auto-groups', { headers: auth(pat) })
|
|
108
|
+
const data = body.data ?? {}
|
|
109
|
+
return {
|
|
110
|
+
groups: Array.isArray(data.groups) ? data.groups.filter(group => typeof group === 'string') : [],
|
|
111
|
+
maxCount: Number.isFinite(data.max_count) ? data.max_count : null,
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Read one key's full value. The caller stores it; it is never rendered.
|
|
117
|
+
* @param {string} pat management token
|
|
118
|
+
* @param {number} id key id
|
|
119
|
+
*/
|
|
120
|
+
async revealKey(pat, id) {
|
|
121
|
+
const body = await call(`/api/token/${id}/key`, { method: 'POST', headers: auth(pat), json: {} })
|
|
122
|
+
const key = body.data?.key
|
|
123
|
+
if (typeof key !== 'string' || key.trim() === '') throw new HttpError('upstream returned no key value', { code: 'UPSTREAM' })
|
|
124
|
+
return key.trim()
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Change one key's group on the server.
|
|
129
|
+
* @param {string} pat management token carrying `api_key:write`
|
|
130
|
+
* @param {number} id key id
|
|
131
|
+
* @param {{ group: string, autoGroups?: string[], crossGroupRetry?: boolean }} selection
|
|
132
|
+
*/
|
|
133
|
+
async updateGroup(pat, id, selection) {
|
|
134
|
+
const json = { group: selection.group }
|
|
135
|
+
if (selection.group === 'auto') {
|
|
136
|
+
if (Array.isArray(selection.autoGroups)) json.auto_groups = selection.autoGroups
|
|
137
|
+
if (typeof selection.crossGroupRetry === 'boolean') json.cross_group_retry = selection.crossGroupRetry
|
|
138
|
+
}
|
|
139
|
+
const body = await call(`/api/token/${id}/group`, { method: 'PUT', headers: auth(pat), json })
|
|
140
|
+
return normalizeKey(body.data ?? {})
|
|
141
|
+
},
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Models one selected model key can actually use.
|
|
145
|
+
* @param {string} modelKey full `sk-` style key
|
|
146
|
+
*/
|
|
147
|
+
async listModels(modelKey) {
|
|
148
|
+
const body = await call('/v1/models', { headers: auth(modelKey) })
|
|
149
|
+
const rows = Array.isArray(body.data) ? body.data : []
|
|
150
|
+
return rows
|
|
151
|
+
.map(row => {
|
|
152
|
+
if (typeof row?.id !== 'string' || row.id === '') return null
|
|
153
|
+
const supportedEndpoints = Array.isArray(row.supported_endpoint_types)
|
|
154
|
+
? [...new Set(row.supported_endpoint_types.filter(type => typeof type === 'string'))]
|
|
155
|
+
: null
|
|
156
|
+
return {
|
|
157
|
+
id: row.id,
|
|
158
|
+
name: typeof row.name === 'string' && row.name !== '' ? row.name : row.id,
|
|
159
|
+
supportedEndpoints,
|
|
160
|
+
inputModalities: Array.isArray(row.input_modalities) ? row.input_modalities.filter(type => typeof type === 'string') : null,
|
|
161
|
+
reasoningEfforts: row.reasoning_efforts === false ? false
|
|
162
|
+
: Array.isArray(row.reasoning_efforts) ? row.reasoning_efforts.filter(value => typeof value === 'string')
|
|
163
|
+
: row.reasoning_efforts && typeof row.reasoning_efforts === 'object'
|
|
164
|
+
? Object.fromEntries(Object.entries(row.reasoning_efforts).filter(([, value]) => value === null || typeof value === 'string')) : null,
|
|
165
|
+
contextWindow: positive(row.context_window),
|
|
166
|
+
maxTokens: positive(row.max_tokens),
|
|
167
|
+
}
|
|
168
|
+
})
|
|
169
|
+
.filter(Boolean)
|
|
170
|
+
.filter(isLlmModel)
|
|
171
|
+
},
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The selected key's own quota and limits.
|
|
175
|
+
* @param {string} modelKey full key
|
|
176
|
+
*/
|
|
177
|
+
async usage(modelKey) {
|
|
178
|
+
const body = await call('/api/usage/token/', { headers: auth(modelKey) })
|
|
179
|
+
const data = body.data ?? {}
|
|
180
|
+
const userQuota = data.user_quota ?? null
|
|
181
|
+
return {
|
|
182
|
+
totalGranted: finite(data.total_granted),
|
|
183
|
+
totalUsed: finite(data.total_used),
|
|
184
|
+
totalAvailable: finite(data.total_available),
|
|
185
|
+
unlimitedQuota: data.unlimited_quota === true,
|
|
186
|
+
expiresAt: finite(data.expires_at),
|
|
187
|
+
modelLimitsEnabled: data.model_limits_enabled === true,
|
|
188
|
+
modelLimits: Array.isArray(data.model_limits) ? data.model_limits.filter(v => typeof v === 'string') : [],
|
|
189
|
+
accountQuota: userQuota === null ? null : { available: finite(userQuota.total_available), used: finite(userQuota.total_used) },
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Public price table, optionally authenticated (an identity can change the
|
|
195
|
+
* ratios that come back).
|
|
196
|
+
* @param {string} [credential] management or model token
|
|
197
|
+
*/
|
|
198
|
+
async pricing(credential, { requireIdentity = false } = {}) {
|
|
199
|
+
const body = await call('/api/pricing', credential === undefined ? {} : { headers: auth(credential), requireIdentity })
|
|
200
|
+
return {
|
|
201
|
+
rows: Array.isArray(body.data) ? body.data : [],
|
|
202
|
+
groupRatio: body.group_ratio ?? {},
|
|
203
|
+
usableGroup: body.usable_group ?? {},
|
|
204
|
+
autoGroups: Array.isArray(body.auto_groups) ? body.auto_groups.filter(group => typeof group === 'string') : [],
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Masked key row, reduced to what a settings surface may show. */
|
|
211
|
+
function normalizeKey(raw) {
|
|
212
|
+
if (raw === null || typeof raw !== 'object') return null
|
|
213
|
+
const id = finite(raw.id)
|
|
214
|
+
if (!Number.isSafeInteger(id) || id <= 0) return null
|
|
215
|
+
const status = finite(raw.status)
|
|
216
|
+
return {
|
|
217
|
+
id,
|
|
218
|
+
name: typeof raw.name === 'string' ? raw.name : `#${id}`,
|
|
219
|
+
maskedKey: '••••', // never trust upstream masking to exclude a full secret
|
|
220
|
+
group: typeof raw.group === 'string' ? raw.group : '',
|
|
221
|
+
autoGroups: Array.isArray(raw.auto_groups) ? raw.auto_groups.filter(group => typeof group === 'string') : null,
|
|
222
|
+
crossGroupRetry: raw.cross_group_retry === true,
|
|
223
|
+
status: status === 1 ? 'enabled' : status === 2 ? 'disabled' : status === 3 ? 'expired' : status === 4 ? 'exhausted' : 'unknown',
|
|
224
|
+
unlimitedQuota: raw.unlimited_quota === true,
|
|
225
|
+
remainQuota: finite(raw.remain_quota),
|
|
226
|
+
usedQuota: finite(raw.used_quota),
|
|
227
|
+
modelLimitsEnabled: raw.model_limits_enabled === true,
|
|
228
|
+
expiresAt: finite(raw.expired_time),
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function finite(value) {
|
|
233
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : null
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function positive(value) {
|
|
237
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function messageFromBody(body) {
|
|
241
|
+
const message = body?.message
|
|
242
|
+
if (typeof message === 'string' && message.trim() !== '') return message.trim().slice(0, 300)
|
|
243
|
+
return null
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** The scope a 403 names, when the site reports one. */
|
|
247
|
+
function scopeFromBody(body) {
|
|
248
|
+
// The message carries the actionable scope (`api_key:write`); the code only
|
|
249
|
+
// says a scope was denied, so the message wins when both are present.
|
|
250
|
+
const message = messageFromBody(body) ?? ''
|
|
251
|
+
const match = /api_key:\w+/.exec(message)
|
|
252
|
+
if (match !== null) return match[0]
|
|
253
|
+
return 'api_key'
|
|
254
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** Adapt preloaded Niko rates to cost-meter >=1.9.78's synchronous Host API. */
|
|
2
|
+
import { nikoBillingBreakdown } from './billing-expression.js'
|
|
3
|
+
import { priceSignature } from './costmeter-prices.js'
|
|
4
|
+
|
|
5
|
+
export const usageFields = ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning']
|
|
6
|
+
const amount = value => Number.isFinite(value) && value >= 0 && value <= 1e12
|
|
7
|
+
const own = (object, key) => Object.hasOwn(object ?? {}, key)
|
|
8
|
+
|
|
9
|
+
/** User prices are left in place. Legacy owned prices may be superseded in memory only. */
|
|
10
|
+
export function hasManualPrice(config, provider, model, ownership = {}) {
|
|
11
|
+
const key = `${provider}:${model}`
|
|
12
|
+
const table = config?.prices?.providers?.[provider]?.models
|
|
13
|
+
const override = config?.priceOverrides?.[key]
|
|
14
|
+
const custom = config?.prices?.custom
|
|
15
|
+
if (!own(config?.priceOverrides, key) && !own(custom, key) && !own(table, model)) return false
|
|
16
|
+
// Any explicit remapping/free rule is user-owned even if an old owned table survives.
|
|
17
|
+
if (own(config?.priceOverrides, key) && override !== '__custom__') return true
|
|
18
|
+
if (own(custom, key) && override !== '__custom__') return true
|
|
19
|
+
const entry = override === '__custom__' ? custom?.[key] : table?.[model]
|
|
20
|
+
const expected = ownership.ownedPriceSnapshots?.[key]
|
|
21
|
+
return typeof expected !== 'string' || expected !== priceSignature(entry)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** No fetching, credential reads, settings writes, or asynchronous work occurs here. */
|
|
25
|
+
export function calculatePrice(price, usage, atMs) {
|
|
26
|
+
if (!Number.isFinite(atMs) || !price || price.reference === true || usageFields.some(key => !Number.isSafeInteger(usage?.[key] ?? 0) || (usage?.[key] ?? 0) < 0)) return null
|
|
27
|
+
const tokens = Object.fromEntries(usageFields.map(key => [key, usage?.[key] ?? 0]))
|
|
28
|
+
if (price.kind === 'perMillion') {
|
|
29
|
+
if (price.reference === true || !['USD', 'CNY', 'EUR'].includes(price.currency)) return null
|
|
30
|
+
const rates = { input: price.input, output: price.output, cacheRead: price.cacheHit, cacheWrite: price.cacheWrite ?? price.cacheHit }
|
|
31
|
+
if (Object.values(rates).some(rate => !amount(rate))) return null
|
|
32
|
+
// DSH output already includes reasoning tokens; do not charge reasoning a second time.
|
|
33
|
+
const breakdown = Object.fromEntries(usageFields.map(key => [key, tokens[key] * (rates[key] ?? 0) / 1_000_000]))
|
|
34
|
+
const total = Object.values(breakdown).reduce((sum, value) => sum + value, 0)
|
|
35
|
+
return amount(total) ? { currency: price.currency, total, breakdown, context: { version: 1 } } : null
|
|
36
|
+
}
|
|
37
|
+
if (!['nikoExpression', 'nikoZero', 'perCall'].includes(price.kind) || price.currency !== 'CNY') return null
|
|
38
|
+
if (price.kind === 'perCall' && (price.reference === true || !amount(price.perCall))) return null
|
|
39
|
+
const quote = nikoBillingBreakdown(tokens, {
|
|
40
|
+
billingExpr: price.expression,
|
|
41
|
+
billingQuotaPerUnit: price.quotaPerUnit,
|
|
42
|
+
billingGroupRatio: price.groupRatio,
|
|
43
|
+
...(price.kind === 'nikoZero' ? { zeroByPolicy: true } : {}),
|
|
44
|
+
...(price.kind === 'perCall' ? { requestPriceCny: price.perCall } : {}),
|
|
45
|
+
}, atMs)
|
|
46
|
+
if (!quote || !amount(quote.cost)) return null
|
|
47
|
+
const context = { version: 1 }
|
|
48
|
+
if (amount(price.groupRatio)) context.multiplier = price.groupRatio
|
|
49
|
+
// The official API has no modelRequests breakdown field. Keep legitimate request totals
|
|
50
|
+
// without inventing token amounts; official web request fees remain cost-meter's concern.
|
|
51
|
+
if (quote.billingUnit === 'request') return { currency: quote.currency, total: quote.cost, context }
|
|
52
|
+
const breakdown = Object.fromEntries(usageFields.map(key => [key, 0]))
|
|
53
|
+
for (const row of quote.rows) {
|
|
54
|
+
if (!usageFields.includes(row.bucket) || !amount(row.cost)) return null
|
|
55
|
+
breakdown[row.bucket] += row.cost
|
|
56
|
+
}
|
|
57
|
+
if (usageFields.some(key => !amount(breakdown[key]) || tokens[key] === 0 && breakdown[key] !== 0)) return null
|
|
58
|
+
if (Math.abs(Object.values(breakdown).reduce((sum, value) => sum + value, 0) - quote.cost) > Math.max(1e-12, quote.cost * 1e-10)) return null
|
|
59
|
+
return { currency: quote.currency, total: quote.cost, breakdown, context }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function usablePrice(price, atMs) {
|
|
63
|
+
try { return calculatePrice(price, { input: 1000, output: 200, cacheRead: 10, cacheWrite: 0, reasoning: 20 }, atMs) !== null }
|
|
64
|
+
catch { return false }
|
|
65
|
+
}
|
package/lib/pricing.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { analyzeNikoBillingExpression } from './billing-expression.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Price normalization: New API ratio rows to per-million-token money.
|
|
5
|
+
*
|
|
6
|
+
* Upstream math (verified against the deployed fork's `service/quota.go`):
|
|
7
|
+
* a token-billed call costs `tokens * model_ratio * group_ratio` quota, and
|
|
8
|
+
* `quota_per_unit` quota make one display-currency unit. So one million input
|
|
9
|
+
* tokens cost `1e6 * model_ratio * group_ratio / quota_per_unit`.
|
|
10
|
+
*
|
|
11
|
+
* Fixed token prices remain compatible with the original normalizer. Niko
|
|
12
|
+
* expressions are retained as dynamic snapshots; missing billing context stays unknown.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {object[]} rows `/api/pricing` rows
|
|
17
|
+
* @param {object} context
|
|
18
|
+
* @param {Record<string, number>} context.groupRatio
|
|
19
|
+
* @param {number} context.quotaPerUnit
|
|
20
|
+
* @param {string} context.currency
|
|
21
|
+
* @param {string[]} [context.candidateGroups] groups the selected key may use
|
|
22
|
+
* @param {boolean} [context.reference] whether pricing is only a reference
|
|
23
|
+
* @param {boolean} [context.unknownGroup] whether the key has no known billing group
|
|
24
|
+
* @returns {Map<string, object>} model id → price fact
|
|
25
|
+
*/
|
|
26
|
+
export function normalizePricing(rows, context) {
|
|
27
|
+
const prices = new Map()
|
|
28
|
+
for (const row of Array.isArray(rows) ? rows : []) {
|
|
29
|
+
const id = typeof row?.model_name === 'string' ? row.model_name : ''
|
|
30
|
+
if (id === '') continue
|
|
31
|
+
prices.set(id, priceOf(row, context))
|
|
32
|
+
}
|
|
33
|
+
return prices
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function priceOf(row, context) {
|
|
37
|
+
const currency = context.currency
|
|
38
|
+
const quotaPerUnit = context.quotaPerUnit > 0 ? context.quotaPerUnit : 500_000
|
|
39
|
+
if (Array.isArray(row?.supported_endpoint_types) && row.supported_endpoint_types.includes('image-generation')) {
|
|
40
|
+
return { kind: 'nikoZero', currency: 'CNY', expression: typeof row.billing_expr === 'string' ? row.billing_expr.trim() : '',
|
|
41
|
+
groupRatio: 1, quotaPerUnit, zeroByPolicy: true, adapterSupported: true,
|
|
42
|
+
note: 'image-generation requests are excluded by the local zero-cost policy', enableGroups: enableGroupsOf(row) }
|
|
43
|
+
}
|
|
44
|
+
if (hasExpressionBilling(row)) {
|
|
45
|
+
const ratios = ratioCandidates(row, context)
|
|
46
|
+
const expression = typeof row?.billing_expr === 'string' ? row.billing_expr.trim() : ''
|
|
47
|
+
const analyzed = analyzeNikoBillingExpression(expression)
|
|
48
|
+
const unsupported = !analyzed.supported && !analyzed.zeroByPolicy
|
|
49
|
+
if (context.currency !== 'CNY' || ratios.kind !== 'ratio' || ratios.range === true || expression === '' || unsupported) {
|
|
50
|
+
return { kind: 'unknown', currency, note: context.currency !== 'CNY' ? 'site billing currency is not CNY'
|
|
51
|
+
: ratios.kind !== 'ratio' ? ratios.note
|
|
52
|
+
: ratios.range ? 'group ratio varies per request; request group cannot be inferred safely'
|
|
53
|
+
: unsupported ? analyzed.reason : 'billing expression is missing',
|
|
54
|
+
groups: ratios.groups, enableGroups: enableGroupsOf(row) }
|
|
55
|
+
}
|
|
56
|
+
const shared = { currency: 'CNY', expression, groupRatio: ratios.ratio,
|
|
57
|
+
usdExchangeRate: Number.isFinite(context.usdExchangeRate) && context.usdExchangeRate > 0 ? context.usdExchangeRate : 1,
|
|
58
|
+
quotaPerUnit, groups: ratios.groups, reference: ratios.reference, enableGroups: enableGroupsOf(row), note: ratios.note }
|
|
59
|
+
if (analyzed.zeroByPolicy) return { kind: 'nikoZero', ...shared, zeroByPolicy: true, adapterSupported: true,
|
|
60
|
+
note: analyzed.reason || 'billing expression uses a field excluded by the local policy' }
|
|
61
|
+
return { kind: 'nikoExpression', ...shared }
|
|
62
|
+
}
|
|
63
|
+
const ratios = ratioCandidates(row, context)
|
|
64
|
+
if (ratios.kind !== 'ratio') {
|
|
65
|
+
return { kind: ratios.kind, currency, note: ratios.note, groups: ratios.groups, enableGroups: enableGroupsOf(row) }
|
|
66
|
+
}
|
|
67
|
+
const base = ratios.ratio
|
|
68
|
+
if (!(base > 0)) {
|
|
69
|
+
return { kind: 'unknown', currency, note: 'group ratio unavailable', groups: ratios.groups, enableGroups: enableGroupsOf(row) }
|
|
70
|
+
}
|
|
71
|
+
const quotaType = row.quota_type
|
|
72
|
+
if (quotaType === 1) {
|
|
73
|
+
if (currency !== 'CNY') return { kind: 'unknown', currency, note: 'site billing currency is not CNY', groups: ratios.groups, enableGroups: enableGroupsOf(row) }
|
|
74
|
+
const perCall = number(row.model_price)
|
|
75
|
+
if (perCall === null) return { kind: 'unknown', currency, note: 'per-call price missing', groups: ratios.groups, enableGroups: enableGroupsOf(row) }
|
|
76
|
+
return {
|
|
77
|
+
kind: 'perCall',
|
|
78
|
+
currency,
|
|
79
|
+
perCall: round(perCall * base),
|
|
80
|
+
groups: ratios.groups,
|
|
81
|
+
reference: ratios.reference,
|
|
82
|
+
enableGroups: enableGroupsOf(row),
|
|
83
|
+
note: 'billed per call; not convertible to a per-token rate',
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const modelRatio = number(row.model_ratio)
|
|
87
|
+
if (modelRatio === null) return { kind: 'unknown', currency, note: 'model ratio missing', groups: ratios.groups, enableGroups: enableGroupsOf(row) }
|
|
88
|
+
const perMillion = ratio => round(1_000_000 * ratio * base / quotaPerUnit)
|
|
89
|
+
const input = perMillion(modelRatio)
|
|
90
|
+
const completion = number(row.completion_ratio)
|
|
91
|
+
const cacheRatio = number(row.cache_ratio)
|
|
92
|
+
const createCacheRatio = number(row.create_cache_ratio)
|
|
93
|
+
if (completion === null) {
|
|
94
|
+
return { kind: 'unknown', currency, note: 'completion ratio is missing', groups: ratios.groups, enableGroups: enableGroupsOf(row) }
|
|
95
|
+
}
|
|
96
|
+
const cacheInputFactor = cacheRatio ?? 1
|
|
97
|
+
const output = perMillion(modelRatio * completion)
|
|
98
|
+
const cacheHit = perMillion(modelRatio * cacheInputFactor)
|
|
99
|
+
const cacheWriteRatio = createCacheRatio === null ? cacheInputFactor : createCacheRatio
|
|
100
|
+
const cacheWrite = perMillion(modelRatio * cacheWriteRatio)
|
|
101
|
+
return {
|
|
102
|
+
kind: 'perMillion',
|
|
103
|
+
currency,
|
|
104
|
+
input,
|
|
105
|
+
output,
|
|
106
|
+
cacheHit,
|
|
107
|
+
cacheWrite,
|
|
108
|
+
groups: ratios.groups,
|
|
109
|
+
reference: ratios.reference,
|
|
110
|
+
enableGroups: enableGroupsOf(row),
|
|
111
|
+
note: ratios.note,
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Which group ratio applies to this row for the selected key.
|
|
117
|
+
* A fixed-group key has one answer. An auto key has a range, and the site
|
|
118
|
+
* picks at request time, so the cheapest candidate is reported as a reference
|
|
119
|
+
* price and flagged.
|
|
120
|
+
*/
|
|
121
|
+
function ratioCandidates(row, context) {
|
|
122
|
+
const groupRatio = context.groupRatio ?? {}
|
|
123
|
+
const enableGroups = enableGroupsOf(row)
|
|
124
|
+
const usable = (context.candidateGroups ?? []).filter(group => group !== 'auto')
|
|
125
|
+
if (context.unknownGroup === true && usable.length === 0) return { kind: 'unknown', note: 'key billing group is unknown', groups: [] }
|
|
126
|
+
const candidates = usable.length > 0 ? usable : Object.keys(groupRatio)
|
|
127
|
+
const applicable = candidates.filter(group => enableGroups.length === 0 || enableGroups.includes('all') || enableGroups.includes(group))
|
|
128
|
+
if (usable.length > 0 && applicable.length === 0) return { kind: 'unknown', note: 'model is not enabled for the key group', groups: [] }
|
|
129
|
+
const pool = applicable.length > 0 ? applicable : candidates
|
|
130
|
+
const rawValues = pool.map(group => number(groupRatio[group]))
|
|
131
|
+
if (rawValues.length === 0 || rawValues.some(value => value === null)) return { kind: 'unknown', note: 'group ratio missing for one or more possible key groups', groups: pool }
|
|
132
|
+
const values = rawValues
|
|
133
|
+
const min = Math.min(...values)
|
|
134
|
+
const max = Math.max(...values)
|
|
135
|
+
if (min !== max) {
|
|
136
|
+
return {
|
|
137
|
+
kind: 'ratio',
|
|
138
|
+
ratio: min,
|
|
139
|
+
groups: pool,
|
|
140
|
+
reference: true,
|
|
141
|
+
range: true,
|
|
142
|
+
minRatio: min,
|
|
143
|
+
maxRatio: max,
|
|
144
|
+
note: context.reference === true ? `auto group: ${min}×–${max}× depending on the server's choice; shown at the lowest ratio` : `multiple possible groups: ${min}×–${max}×; shown at the lowest ratio`,
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return { kind: 'ratio', ratio: min, groups: pool, reference: context.reference === true || pool.length > 1, note: context.reference === true ? `auto group: estimated at the lowest of ${pool.length} candidate ratios` : pool.length > 1 ? `multiple groups: ${pool.length} candidates at ${min}×` : undefined }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function enableGroupsOf(row) {
|
|
151
|
+
if (Array.isArray(row?.enable_groups)) return row.enable_groups.filter(group => typeof group === 'string')
|
|
152
|
+
if (Array.isArray(row?.enable_group)) return row.enable_group.filter(group => typeof group === 'string')
|
|
153
|
+
return []
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Billing expressions cannot be evaluated here, and `model_price: 0` is not free. */
|
|
157
|
+
export function hasExpressionBilling(row) {
|
|
158
|
+
const mode = typeof row?.billing_mode === 'string' ? row.billing_mode : ''
|
|
159
|
+
const expr = typeof row?.billing_expr === 'string' ? row.billing_expr.trim() : ''
|
|
160
|
+
return mode === 'tiered_expr' || expr !== ''
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function number(value) {
|
|
164
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value
|
|
165
|
+
if (typeof value === 'string' && value.trim() !== '') {
|
|
166
|
+
const parsed = Number(value)
|
|
167
|
+
if (Number.isFinite(parsed)) return parsed
|
|
168
|
+
}
|
|
169
|
+
return null
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function round(value) {
|
|
173
|
+
return Math.round(value * 1e8) / 1e8
|
|
174
|
+
}
|