@fish-under-sea/magpie-dragonapi 0.0.0-stage → 0.1.1
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.md +140 -2
- package/index.mjs +452 -0
- package/lib/catalog-source.mjs +87 -0
- package/lib/catalog.mjs +200 -0
- package/lib/pricing.mjs +256 -0
- package/lib/service.mjs +498 -0
- package/lib/site.mjs +301 -0
- package/lib/status-source.mjs +44 -0
- package/lib/store.mjs +86 -0
- package/lib/usage.mjs +202 -0
- package/package.json +70 -4
- package/page/boot.js +112 -0
- package/page/icon.svg +12 -0
- package/page/index.html +32 -0
- package/serve.mjs +110 -0
- package/ui/app.js +1722 -0
- package/ui/index.html +259 -0
- package/ui/style.css +968 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// 目录源:/api/pricing 的缓存与刷新策略,只此一处。
|
|
2
|
+
//
|
|
3
|
+
// 为什么单独抽出来:这份数据有三处消费者——宿主要模型表、页面要模型广场、
|
|
4
|
+
// 独立启动模式也要。之前每处各拉各的、各缓存各的,结果是「页面点刷新刷不到
|
|
5
|
+
// 宿主那份」,而且三份缓存会给出三个不同的答案。现在只有一个所有者,
|
|
6
|
+
// 谁要都从同一个 get() 取。
|
|
7
|
+
//
|
|
8
|
+
// 三条策略:
|
|
9
|
+
// 1. TTL 内直接给缓存,不打站点;
|
|
10
|
+
// 2. 带 ETag / Last-Modified 做条件请求,命中 304 就只更新时间(站点实测认这个);
|
|
11
|
+
// 3. 拉失败沿用上一次成功的快照,一次都没成功过才把错误报出去。
|
|
12
|
+
|
|
13
|
+
import { readPricing } from './site.mjs'
|
|
14
|
+
|
|
15
|
+
/** 目录多久算过期。站点目录动得不勤,五分钟足够。 */
|
|
16
|
+
export const DEFAULT_TTL = 5 * 60e3
|
|
17
|
+
|
|
18
|
+
/** 健康记录留几条。页面用它显示「上一次拉目录是什么时候、成没成」。 */
|
|
19
|
+
const HEALTH_KEEP = 12
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* createCatalogSource 造一个目录源。
|
|
23
|
+
*
|
|
24
|
+
* @param {object} o
|
|
25
|
+
* @param {string} o.site 站点根地址
|
|
26
|
+
* @param {number} [o.ttl] 缓存有效期(毫秒)
|
|
27
|
+
* @param {function} [o.fetchPricing] 拉取实现,测试可替换
|
|
28
|
+
* @param {object} [o.stub] 固定目录,测试用;给了就不再打站点
|
|
29
|
+
*/
|
|
30
|
+
export function createCatalogSource({ site, ttl = DEFAULT_TTL, fetchPricing = readPricing, stub = null } = {}) {
|
|
31
|
+
/** env 是站点 /api/pricing 的原文;source 说明它从哪来。 */
|
|
32
|
+
let state = { at: 0, env: null, etag: '', lastModified: '', source: 'empty', error: '' }
|
|
33
|
+
const health = []
|
|
34
|
+
|
|
35
|
+
function note(rec) {
|
|
36
|
+
health.unshift({ at: Date.now(), ...rec })
|
|
37
|
+
while (health.length > HEALTH_KEEP) health.pop()
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* get 取目录。force 为真时跳过 TTL(用户点刷新),但仍走条件请求——
|
|
42
|
+
* 站点没变就该省掉那 89 KB。
|
|
43
|
+
*/
|
|
44
|
+
async function get({ force = false } = {}) {
|
|
45
|
+
const now = Date.now()
|
|
46
|
+
if (stub) {
|
|
47
|
+
state = { at: now, env: stub, etag: '', lastModified: '', source: 'live', error: '' }
|
|
48
|
+
return state
|
|
49
|
+
}
|
|
50
|
+
if (!force && state.env && now - state.at < ttl) return state
|
|
51
|
+
|
|
52
|
+
const startedAt = Date.now()
|
|
53
|
+
try {
|
|
54
|
+
const r = await fetchPricing(site, force ? {} : { etag: state.etag, lastModified: state.lastModified })
|
|
55
|
+
if (r.notModified) {
|
|
56
|
+
// 304:内容没变,只把「上次核对时间」推后。
|
|
57
|
+
state = { ...state, at: now, source: 'live', error: '' }
|
|
58
|
+
} else {
|
|
59
|
+
state = { at: now, env: r.env, etag: r.etag || '', lastModified: r.lastModified || '', source: 'live', error: '' }
|
|
60
|
+
}
|
|
61
|
+
} catch (error) {
|
|
62
|
+
state = {
|
|
63
|
+
...state,
|
|
64
|
+
at: now,
|
|
65
|
+
// 有旧数据就是 stale(还能用),没有才是 empty(真的什么都没有)。
|
|
66
|
+
source: state.env ? 'stale' : 'empty',
|
|
67
|
+
error: String(error?.message || error),
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
note({
|
|
71
|
+
ok: state.source === 'live',
|
|
72
|
+
source: state.source,
|
|
73
|
+
count: Array.isArray(state.env?.data) ? state.env.data.length : 0,
|
|
74
|
+
ms: Date.now() - startedAt,
|
|
75
|
+
error: state.error,
|
|
76
|
+
})
|
|
77
|
+
return state
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** snapshot 是「现在手上有什么」,不触发拉取。 */
|
|
81
|
+
const snapshot = () => state
|
|
82
|
+
|
|
83
|
+
/** recent 是最近的拉取记录,最新的在前。 */
|
|
84
|
+
const recent = () => health.slice()
|
|
85
|
+
|
|
86
|
+
return { get, snapshot, recent }
|
|
87
|
+
}
|
package/lib/catalog.mjs
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
// 目录:把站点 /api/pricing 折成 magpie 的模型表。
|
|
2
|
+
//
|
|
3
|
+
// 这里有一处与 NearToken 的根本不同,必须先说清:
|
|
4
|
+
//
|
|
5
|
+
// NearToken 站点让插件在请求头里塞 `x-neartoken-group` 来选分组,所以它
|
|
6
|
+
// 可以「一个模型一行,按那一行走那一组」。DragonAPI 没有这个补丁——
|
|
7
|
+
// `TokenAuth` 里 `userGroup = tokenGroup`,分组是**钥匙的属性**,请求头里
|
|
8
|
+
// 没有任何入口能改它(`Distribute` 只从 `/pg/chat/completions` 的请求体读
|
|
9
|
+
// group,而那条路由要浏览器会话)。
|
|
10
|
+
//
|
|
11
|
+
// 所以这里的分组策略是:**一个分组一把钥匙 = magpie 的一个账号**。
|
|
12
|
+
// 模型 id 用 `分组/模型` 的形式,每个账号的 `models` 清单只列它那一组的模型,
|
|
13
|
+
// 让宿主自己把请求送到对的账号(上游 magpie 的 `AccountServes` 保证这点)。
|
|
14
|
+
// 这也意味着**目录里的分组是给账号用的,不是给请求头用的**。
|
|
15
|
+
|
|
16
|
+
import { priceOf } from './pricing.mjs'
|
|
17
|
+
|
|
18
|
+
/** 端点类型 → 该用哪个 SDK 方言发出去。 */
|
|
19
|
+
export function npmOf(row) {
|
|
20
|
+
const ends = Array.isArray(row?.supported_endpoint_types) ? row.supported_endpoint_types.map(String) : []
|
|
21
|
+
// 只要模型支持 openai 兼容,就走 openai-compatible:本站绝大多数模型都挂着它,
|
|
22
|
+
// 而且 anthropic / gemini 原生通道在 magpie 里要额外的账号形态,第一版不做。
|
|
23
|
+
if (ends.includes('openai') || ends.includes('openai-response')) return '@ai-sdk/openai-compatible'
|
|
24
|
+
if (ends.includes('image-generation')) return '@ai-sdk/openai-compatible'
|
|
25
|
+
if (ends.includes('anthropic')) return '@ai-sdk/anthropic'
|
|
26
|
+
if (ends.includes('gemini')) return '@ai-sdk/google'
|
|
27
|
+
return '@ai-sdk/openai-compatible'
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 模型的类别,决定 magpie 把它放进哪个分区。 */
|
|
31
|
+
export function kindOf(row) {
|
|
32
|
+
const ends = Array.isArray(row?.supported_endpoint_types) ? row.supported_endpoint_types.map(String) : []
|
|
33
|
+
if (ends.includes('image-generation')) return 'image'
|
|
34
|
+
if (ends.includes('视频任务')) return 'video'
|
|
35
|
+
if (ends.some((e) => /^(audio|tts|asr|transcription|speech)$/i.test(e))) return 'audio'
|
|
36
|
+
if (ends.some((e) => /^(embedding|jina-rerank|rerank)$/i.test(e))) return 'embedding'
|
|
37
|
+
const groups = Array.isArray(row?.enable_groups) ? row.enable_groups.join(' ').toLowerCase() : ''
|
|
38
|
+
if (/embedding|向量|rerank/.test(groups)) return 'embedding'
|
|
39
|
+
return 'chat'
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** kindOutput 是 magpie 的 capabilities.output:分区靠它认。 */
|
|
43
|
+
export function kindOutput(kind) {
|
|
44
|
+
switch (kind) {
|
|
45
|
+
case 'image': return { image: true, text: true }
|
|
46
|
+
case 'video': return { video: true, text: true }
|
|
47
|
+
case 'audio': return { audio: true, text: true }
|
|
48
|
+
case 'embedding': return { embedding: true, text: true }
|
|
49
|
+
default: return { text: true }
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* seriesRank 决定供应商列表里的排序:对话在前,功能模型在后。
|
|
55
|
+
* 站点自己给的 group_order 是「推荐顺序」,直接用它更贴合站点。
|
|
56
|
+
*/
|
|
57
|
+
function rankOf(kind, group, groupOrder) {
|
|
58
|
+
const base = kind === 'chat' ? 0 : 1 + ['image', 'video', 'audio', 'embedding'].indexOf(kind)
|
|
59
|
+
const gi = Array.isArray(groupOrder) ? groupOrder.indexOf(group) : -1
|
|
60
|
+
return [base, gi < 0 ? 999 : gi]
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* buildCatalog 把站点目录折成
|
|
65
|
+
* { models: {id: Model}, rows: [行], groups: [组], vendors: [vendor], version }
|
|
66
|
+
*
|
|
67
|
+
* `rows` 是「分组 × 模型」的扁平表,给页面用;`models` 是给宿主的模型表。
|
|
68
|
+
* `enabledGroups` 是用户勾选的分组(空数组表示全部分组)。
|
|
69
|
+
*/
|
|
70
|
+
export function buildCatalog(env, { cur, enabledGroups = [], site } = {}) {
|
|
71
|
+
const data = Array.isArray(env?.data) ? env.data : []
|
|
72
|
+
const ratios = env?.group_ratio && typeof env.group_ratio === 'object' ? env.group_ratio : {}
|
|
73
|
+
const order = Array.isArray(env?.group_order) ? env.group_order : []
|
|
74
|
+
const notes = env?.usable_group && typeof env.usable_group === 'object' ? env.usable_group : {}
|
|
75
|
+
const vendors = Array.isArray(env?.vendors) ? env.vendors : []
|
|
76
|
+
const vendorName = new Map(vendors.map((v) => [String(v?.id), String(v?.name || '')]))
|
|
77
|
+
|
|
78
|
+
// auto_groups 是「令牌可配置的自动分组候选」,跟价格无关——它只是站点
|
|
79
|
+
// 允许你在令牌上挂哪几个分组做自动路由。之前把它当成「价格随通道浮动」,
|
|
80
|
+
// 结果 13/14 个分组都被标成「以实际命中通道为准」,把真实单价全藏了。
|
|
81
|
+
// 现在只把真正的 `auto` 分组视为无固定倍率(它确实不在 group_ratio 里)。
|
|
82
|
+
const autoGroups = Array.isArray(env?.auto_groups) ? env.auto_groups.map(String) : []
|
|
83
|
+
|
|
84
|
+
// 勾选为空 = 全部分组。
|
|
85
|
+
const picked = new Set((Array.isArray(enabledGroups) ? enabledGroups : []).map(String).filter(Boolean))
|
|
86
|
+
|
|
87
|
+
const groups = new Map()
|
|
88
|
+
const rows = []
|
|
89
|
+
const models = {}
|
|
90
|
+
|
|
91
|
+
for (const row of data) {
|
|
92
|
+
const name = String(row?.model_name || '').trim()
|
|
93
|
+
if (!name) continue
|
|
94
|
+
const kind = kindOf(row)
|
|
95
|
+
const ends = Array.isArray(row?.supported_endpoint_types) ? row.supported_endpoint_types.map(String) : []
|
|
96
|
+
const all = Array.isArray(row?.enable_groups) && row.enable_groups.length ? row.enable_groups.map(String) : []
|
|
97
|
+
if (!all.length) continue
|
|
98
|
+
|
|
99
|
+
for (const g of all) {
|
|
100
|
+
const group = String(g || '').trim()
|
|
101
|
+
if (!group) continue
|
|
102
|
+
const ratio = Number(ratios[group]) || 0
|
|
103
|
+
// `auto` 分组不在 group_ratio 里:它的实际倍率取决于命中的通道,
|
|
104
|
+
// 站点自己也算不出一个确定值,所以这类分组不给单价。
|
|
105
|
+
const isAuto = group === 'auto' || !(group in ratios)
|
|
106
|
+
// 分组统计按「全量」算,页面要显示每组多少模型;是否进账号另判。
|
|
107
|
+
const had = groups.get(group) || { id: group, ratio, note: String(notes[group] || ''), models: 0, auto: isAuto }
|
|
108
|
+
had.models += 1
|
|
109
|
+
groups.set(group, had)
|
|
110
|
+
|
|
111
|
+
if (picked.size && !picked.has(group)) continue
|
|
112
|
+
|
|
113
|
+
// 没有固定倍率的分组(只有 `auto`)算不出确定单价,交给 priceOf 的
|
|
114
|
+
// unknown 分支,让 note 说清「为什么算不出来」,而不是硬塞一个数。
|
|
115
|
+
const price = isAuto && !ratio
|
|
116
|
+
? { kind: 'unknown', input: '价格未知', output: '', cache: '', note: '该分组按命中的通道计费,站点没有给固定倍率' }
|
|
117
|
+
: priceOf(row, ratio, cur)
|
|
118
|
+
const id = `${group}/${name}`
|
|
119
|
+
// 同一个「分组/模型」只会出现一次;站点不会给重复行。
|
|
120
|
+
const [r0, r1] = rankOf(kind, group, order)
|
|
121
|
+
// rows 与 models 共用同一套排序键:页面看到的第一行,就是宿主列表里
|
|
122
|
+
// 的第一行。两处各排各的会让「界面上排在最前的模型」和「magpie 里排
|
|
123
|
+
// 在最前的模型」不是同一个,用户会以为它们不是同一份数据。
|
|
124
|
+
rows.push({
|
|
125
|
+
id,
|
|
126
|
+
name,
|
|
127
|
+
group,
|
|
128
|
+
groupRatio: ratio,
|
|
129
|
+
groupAuto: isAuto,
|
|
130
|
+
vendor: vendorName.get(String(row?.vendor_id)) || '',
|
|
131
|
+
kind,
|
|
132
|
+
endpoints: ends,
|
|
133
|
+
context: Number(row?.context_window) > 0 ? Number(row.context_window) : 0,
|
|
134
|
+
pricing: price,
|
|
135
|
+
description: String(row?.description || ''),
|
|
136
|
+
tags: String(row?.tags || ''),
|
|
137
|
+
_rank: [r0, r1, name, group],
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
models[id] = {
|
|
141
|
+
id,
|
|
142
|
+
name: `${name} · ${group}${ratio > 0 ? ` ×${round(ratio)}` : ''}`,
|
|
143
|
+
api: { id: name, url: String(site || '').replace(/\/+$/, '') + '/v1', npm: npmOf(row) },
|
|
144
|
+
limit: {
|
|
145
|
+
context: Number(row?.context_window) > 0 ? Number(row.context_window) : 0,
|
|
146
|
+
output: 0,
|
|
147
|
+
},
|
|
148
|
+
...(kind === 'chat' ? {} : { kind }),
|
|
149
|
+
capabilities: {
|
|
150
|
+
toolcall: kind === 'chat',
|
|
151
|
+
output: kindOutput(kind),
|
|
152
|
+
attachment: false,
|
|
153
|
+
input: { text: true, image: false, audio: false, video: false, pdf: false },
|
|
154
|
+
...(kind === 'chat' ? { reasoning: true } : {}),
|
|
155
|
+
},
|
|
156
|
+
...(kind === 'chat' ? { variants: { low: {}, medium: {}, high: {} } } : {}),
|
|
157
|
+
// 排序用的私有字段,不进宿主(宿主会忽略不认识的键)
|
|
158
|
+
_rank: [r0, r1, name],
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// 按 rank 排序后把 _rank 去掉:宿主按对象的插入顺序展示模型列表。
|
|
164
|
+
const ordered = Object.keys(models).sort((a, b) => {
|
|
165
|
+
const x = models[a]._rank
|
|
166
|
+
const y = models[b]._rank
|
|
167
|
+
return x[0] - y[0] || x[1] - y[1] || String(x[2]).localeCompare(String(y[2]))
|
|
168
|
+
})
|
|
169
|
+
const out = {}
|
|
170
|
+
for (const id of ordered) {
|
|
171
|
+
const m = models[id]
|
|
172
|
+
delete m._rank
|
|
173
|
+
out[id] = m
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// 页面行用同一套键排序,然后去掉私有字段。
|
|
177
|
+
rows.sort((a, b) => {
|
|
178
|
+
const x = a._rank
|
|
179
|
+
const y = b._rank
|
|
180
|
+
return x[0] - y[0] || x[1] - y[1] || String(x[2]).localeCompare(String(y[2])) || String(x[3]).localeCompare(String(y[3]))
|
|
181
|
+
})
|
|
182
|
+
for (const r of rows) delete r._rank
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
models: out,
|
|
186
|
+
rows,
|
|
187
|
+
groups: [...groups.values()].sort((a, b) => (order.indexOf(a.id) - order.indexOf(b.id)) || a.id.localeCompare(b.id, 'zh')),
|
|
188
|
+
vendors: vendors.map((v) => ({ id: Number(v?.id) || 0, name: String(v?.name || '') })),
|
|
189
|
+
version: String(env?.pricing_version || ''),
|
|
190
|
+
autoGroups,
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** 一个分组下的模型 id 清单,给账号的 models 字段用。 */
|
|
195
|
+
export function modelsOfGroup(rows, group) {
|
|
196
|
+
const g = String(group || '')
|
|
197
|
+
return rows.filter((r) => r.group === g).map((r) => r.id)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const round = (v) => String(Math.round(Number(v) * 10000) / 10000)
|
package/lib/pricing.mjs
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
// 价格:把 DragonAPI 的两种计费规则折成「看得懂的钱」。
|
|
2
|
+
//
|
|
3
|
+
// 站点有两种完全不同的计价方式,混在一起处理一定出错:
|
|
4
|
+
//
|
|
5
|
+
// 1. 倍率计费(quota_type=0 且没有 billing_mode):模型倍率 × 分组倍率,
|
|
6
|
+
// 1 倍率 = 2 美元 / 百万 token(站点前端的 $P:{M:1} 除数表与 ×2 约定)。
|
|
7
|
+
// 2. 表达式计费(billing_mode=tiered_expr):站点给一段 DSL,里面既有
|
|
8
|
+
// chat 侧的 token 系数(p / c / cr / cc / cc1h),也有视频侧的用量变量
|
|
9
|
+
// (u("seconds") / u("resolution") / u("spec") / u("reference_video_seconds"))。
|
|
10
|
+
//
|
|
11
|
+
// 这个文件只做「能算准的就算,算不准就说不准」,绝不给一个看起来像真的
|
|
12
|
+
// 假价格。站点前端自己也是这么做的:它把表达式解析成「变量 × 单价」表,
|
|
13
|
+
// 解析失败就不显示价格。
|
|
14
|
+
|
|
15
|
+
/** 视频类模型的分辨率档位顺序,用来给「按分辨率」的表达式挑一个代表值。 */
|
|
16
|
+
const RES_ORDER = ['480p', '720p', '768p', '1080p', '2k', '4k']
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* parseTiers 把表达式里的 `tier("名字", 金额表达式)` 全部取出来。
|
|
20
|
+
*
|
|
21
|
+
* 只做括号配对,不做完整求值——完整求值需要一个 DSL 解释器,而站点随时
|
|
22
|
+
* 会往里加函数(param / weekday / hour / fixed 已经出现了)。取不到就返回空。
|
|
23
|
+
*/
|
|
24
|
+
export function parseTiers(expr) {
|
|
25
|
+
if (typeof expr !== 'string' || !expr) return []
|
|
26
|
+
const out = []
|
|
27
|
+
const re = /tier\(\s*"([^"]*)"\s*,/g
|
|
28
|
+
let m
|
|
29
|
+
while ((m = re.exec(expr))) {
|
|
30
|
+
const name = m[1]
|
|
31
|
+
// 从逗号后开始配对括号,直到这一层 tier( 闭合
|
|
32
|
+
const start = re.lastIndex
|
|
33
|
+
let depth = 0
|
|
34
|
+
let end = -1
|
|
35
|
+
for (let i = start; i < expr.length; i++) {
|
|
36
|
+
const c = expr[i]
|
|
37
|
+
if (c === '(') depth++
|
|
38
|
+
else if (c === ')') {
|
|
39
|
+
if (depth === 0) { end = i; break }
|
|
40
|
+
depth--
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (end < 0) continue
|
|
44
|
+
out.push({ name, body: expr.slice(start, end).trim() })
|
|
45
|
+
}
|
|
46
|
+
return out
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* chatCoeffs 从一段 tier 金额里取 chat 侧的 token 系数。
|
|
51
|
+
*
|
|
52
|
+
* 表达式形如 `p*2 + cr*0.2 + cc*2.5 + c*10`,单位是「美元 / 百万 token」
|
|
53
|
+
* (站点前端把它按 M 换算后再乘分组倍率)。
|
|
54
|
+
*
|
|
55
|
+
* 变量名两侧都必须有边界。只加左侧断言是不够的:在 `p*2 + cr*0.2 + c*10`
|
|
56
|
+
* 里,`c` 会先匹配到 `cr` 的那个 c(左侧是空格,左侧断言通过),而后面不是
|
|
57
|
+
* `*`,于是输出系数被读成 1——真实站点上 gpt-6-sol 就这么显示成「输出比
|
|
58
|
+
* 输入便宜」,一眼就能看出不对。所以右侧也要断言。
|
|
59
|
+
*/
|
|
60
|
+
export function chatCoeffs(body) {
|
|
61
|
+
const pick = (name) => {
|
|
62
|
+
const re = new RegExp(`(?<![a-zA-Z0-9_])${name}(?![a-zA-Z0-9_])\\s*(?:\\*\\s*([0-9.]+))?`)
|
|
63
|
+
const m = body.match(re)
|
|
64
|
+
if (!m) return undefined
|
|
65
|
+
return m[1] === undefined ? 1 : Number(m[1])
|
|
66
|
+
}
|
|
67
|
+
const out = {
|
|
68
|
+
input: pick('p'),
|
|
69
|
+
output: pick('c'),
|
|
70
|
+
cacheRead: pick('cr'),
|
|
71
|
+
cacheWrite: pick('cc'),
|
|
72
|
+
cacheWrite1h: pick('cc1h'),
|
|
73
|
+
}
|
|
74
|
+
const any = Object.values(out).some((v) => v !== undefined)
|
|
75
|
+
return any ? out : null
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* usagePrices 从表达式里取「用量变量 × 单价」表,视频模型主要靠它。
|
|
80
|
+
*
|
|
81
|
+
* 形如 `u("seconds") * 0.45 + u("reference_video_seconds") * 0.45`。
|
|
82
|
+
* 这是站点前端 `XY` 那套做法的简化版:它把每个 u(...) 项拆成
|
|
83
|
+
* 「变量 → 每单位单价」,我们照着拆,单位靠 billing_usage_schema 补。
|
|
84
|
+
*/
|
|
85
|
+
export function usagePrices(expr) {
|
|
86
|
+
if (typeof expr !== 'string' || !expr) return {}
|
|
87
|
+
const out = {}
|
|
88
|
+
const re = /u\(\s*"([^"]+)"\s*\)\s*\*\s*([0-9.]+)/g
|
|
89
|
+
let m
|
|
90
|
+
while ((m = re.exec(expr))) {
|
|
91
|
+
const field = m[1]
|
|
92
|
+
const price = Number(m[2])
|
|
93
|
+
if (!Number.isFinite(price)) continue
|
|
94
|
+
// 同一个变量可能出现多次(不同分辨率分支),取最小值作为「起步价」,
|
|
95
|
+
// 最大值作为「最高价」。只报一个数会误导。
|
|
96
|
+
const had = out[field]
|
|
97
|
+
if (!had) out[field] = { min: price, max: price }
|
|
98
|
+
else out[field] = { min: Math.min(had.min, price), max: Math.max(had.max, price) }
|
|
99
|
+
}
|
|
100
|
+
return out
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* priceOf 算一个模型的价格描述。
|
|
105
|
+
*
|
|
106
|
+
* 返回 { kind, input, output, cache, note },其中 input/output/cache 已经是
|
|
107
|
+
* 格式化好的字符串(如 `$2.00/M`),kind 说明这份价格是怎么来的:
|
|
108
|
+
*
|
|
109
|
+
* ratio 倍率计费,算得准
|
|
110
|
+
* tiered 表达式计费且取到了系数,算得准(取第一档,其余在 note 里)
|
|
111
|
+
* percall 按次 / 按秒,价格是区间
|
|
112
|
+
* unknown 算不准,只有 note 说明原因
|
|
113
|
+
*
|
|
114
|
+
* @param {object} row /api/pricing 里的一条模型
|
|
115
|
+
* @param {number} ratio 该分组的分组倍率
|
|
116
|
+
* @param {object} cur currencyOf 的结果
|
|
117
|
+
*/
|
|
118
|
+
export function priceOf(row, ratio, cur) {
|
|
119
|
+
const groupRatio = Number(ratio) > 0 ? Number(ratio) : 1
|
|
120
|
+
const symbol = cur?.symbol || '$'
|
|
121
|
+
const perM = (v) => {
|
|
122
|
+
// 站点前端:单价 = 系数 × 分组倍率 ÷ 1e6,再乘「充值价系数」。
|
|
123
|
+
// 我们不做充值价折算(拿不到 priceRate 时不能猜),只给系数 × 分组倍率。
|
|
124
|
+
const n = Number(v)
|
|
125
|
+
if (!Number.isFinite(n)) return null
|
|
126
|
+
const value = n * groupRatio
|
|
127
|
+
return symbol + (value >= 0.01 ? value.toFixed(2) : value.toFixed(4)) + '/M'
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const mode = String(row?.billing_mode || '')
|
|
131
|
+
const expr = String(row?.billing_expr || '')
|
|
132
|
+
const quotaType = Number(row?.quota_type) || 0
|
|
133
|
+
|
|
134
|
+
// ---- 按次 / 按秒(quota_type=1)----
|
|
135
|
+
if (quotaType === 1) {
|
|
136
|
+
const per = Number(row?.model_price) || 0
|
|
137
|
+
if (mode === 'tiered_expr' && expr) {
|
|
138
|
+
const usage = usagePrices(expr)
|
|
139
|
+
const fields = Object.keys(usage)
|
|
140
|
+
// 视频:按秒计价,价格随分辨率变。给区间而不是单值。
|
|
141
|
+
const seconds = usage.seconds
|
|
142
|
+
if (seconds) {
|
|
143
|
+
const lo = (seconds.min * groupRatio).toFixed(4)
|
|
144
|
+
const hi = (seconds.max * groupRatio).toFixed(4)
|
|
145
|
+
const res = resolutionRange(row)
|
|
146
|
+
return {
|
|
147
|
+
kind: 'percall',
|
|
148
|
+
input: lo === hi ? `${symbol}${lo}/秒` : `${symbol}${lo}–${hi}/秒`,
|
|
149
|
+
output: '',
|
|
150
|
+
cache: '',
|
|
151
|
+
note: res ? `按秒计价,随分辨率变化(${res})` : '按秒计价',
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (fields.length) {
|
|
155
|
+
return {
|
|
156
|
+
kind: 'percall',
|
|
157
|
+
input: fields.map((f) => `${f} ${symbol}${usage[f].min}–${usage[f].max}`).join(' · '),
|
|
158
|
+
output: '',
|
|
159
|
+
cache: '',
|
|
160
|
+
note: '按用量变量计价,实际以控制台为准',
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
// 纯按次:tier("按次", 0.65) 或直接给 model_price
|
|
165
|
+
if (per > 0) {
|
|
166
|
+
return {
|
|
167
|
+
kind: 'percall',
|
|
168
|
+
input: `${symbol}${(per * groupRatio).toFixed(2)}/次`,
|
|
169
|
+
output: '',
|
|
170
|
+
cache: '',
|
|
171
|
+
note: '按次计价',
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return { kind: 'unknown', input: '价格未知', output: '', cache: '', note: '按次模型,但站点没有给单价' }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ---- 表达式计费(chat 侧)----
|
|
178
|
+
if (mode === 'tiered_expr' && expr) {
|
|
179
|
+
const tiers = parseTiers(expr)
|
|
180
|
+
if (tiers.length) {
|
|
181
|
+
const first = tiers[0]
|
|
182
|
+
const co = chatCoeffs(first.body)
|
|
183
|
+
if (co) {
|
|
184
|
+
const input = co.input === undefined ? null : perM(co.input)
|
|
185
|
+
const output = co.output === undefined ? null : perM(co.output)
|
|
186
|
+
const cache = co.cacheRead === undefined ? null : perM(co.cacheRead)
|
|
187
|
+
if (input || output) {
|
|
188
|
+
return {
|
|
189
|
+
kind: 'tiered',
|
|
190
|
+
input: input || '—',
|
|
191
|
+
output: output || '—',
|
|
192
|
+
cache: cache || '—',
|
|
193
|
+
note: tiers.length > 1
|
|
194
|
+
? `${tiers.length} 档(${tiers.map((t) => t.name).join(' / ')}),上表是「${first.name}」档`
|
|
195
|
+
: `表达式计费(${first.name})`,
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return { kind: 'unknown', input: '价格未知', output: '', cache: '', note: '表达式无法解析成单价' }
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ---- 倍率计费 ----
|
|
204
|
+
const modelRatio = Number(row?.model_ratio) || 0
|
|
205
|
+
if (modelRatio > 0) {
|
|
206
|
+
const completion = Number(row?.completion_ratio) || 0
|
|
207
|
+
const cacheRatio = Number(row?.cache_ratio) || 0
|
|
208
|
+
// 站点约定:1 倍率 = 2 美元 / 百万 token(前端把系数按 M 换算)。
|
|
209
|
+
const input = modelRatio * 2
|
|
210
|
+
const output = completion > 0 ? input * completion : input
|
|
211
|
+
return {
|
|
212
|
+
kind: 'ratio',
|
|
213
|
+
input: perM(input),
|
|
214
|
+
output: perM(output),
|
|
215
|
+
cache: cacheRatio > 0 ? perM(input * cacheRatio) : '—',
|
|
216
|
+
note: `倍率 ${round(modelRatio)}${completion > 0 ? ` · 补全 ${round(completion)}` : ''}`,
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
return { kind: 'unknown', input: '价格未知', output: '', cache: '', note: '站点没有给这个模型的计价规则' }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** 分辨率范围,从 billing_usage_schema 里读,读不到就看表达式里出现过的分辨率。 */
|
|
224
|
+
function resolutionRange(row) {
|
|
225
|
+
const schema = row?.billing_usage_schema
|
|
226
|
+
const list = schema?.resolution?.enum
|
|
227
|
+
if (Array.isArray(list) && list.length) {
|
|
228
|
+
const sorted = list.slice().sort((a, b) => RES_ORDER.indexOf(String(a)) - RES_ORDER.indexOf(String(b)))
|
|
229
|
+
return sorted.join(' / ')
|
|
230
|
+
}
|
|
231
|
+
const expr = String(row?.billing_expr || '')
|
|
232
|
+
const found = RES_ORDER.filter((r) => expr.includes(`"${r}"`))
|
|
233
|
+
return found.length ? found.join(' / ') : ''
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const round = (v) => String(Math.round(Number(v) * 10000) / 10000)
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* billingOf 给「模型详情」用的完整计费信息,比 priceOf 多给原始数字。
|
|
240
|
+
* UI 只在用户点开单个模型时用它。
|
|
241
|
+
*/
|
|
242
|
+
export function billingOf(row, ratio) {
|
|
243
|
+
const mode = String(row?.billing_mode || '')
|
|
244
|
+
const expr = String(row?.billing_expr || '')
|
|
245
|
+
const tiers = parseTiers(expr)
|
|
246
|
+
return {
|
|
247
|
+
mode: mode || (Number(row?.quota_type) === 1 ? 'per_call' : 'ratio'),
|
|
248
|
+
expr,
|
|
249
|
+
groupRatio: Number(ratio) > 0 ? Number(ratio) : 1,
|
|
250
|
+
tiers: tiers.map((t) => ({ name: t.name, body: t.body, coeffs: chatCoeffs(t.body) })),
|
|
251
|
+
usages: usagePrices(expr),
|
|
252
|
+
schema: row?.billing_usage_schema && typeof row.billing_usage_schema === 'object' ? row.billing_usage_schema : null,
|
|
253
|
+
examples: Array.isArray(row?.billing_usage_examples) ? row.billing_usage_examples : [],
|
|
254
|
+
variants: Array.isArray(row?.billing_plugin_variants) ? row.billing_plugin_variants : [],
|
|
255
|
+
}
|
|
256
|
+
}
|