feat: extend enterprise gateway policies billing protocols and operations

This commit is contained in:
wlx committed 2026-10-13 19:08:50 +08:00
1 parent 1528b71882
commit af43947b5d
67 files changed
+1822 -69

No files matched your search

@@ -2,6 +2,7 @@
import { reactive, ref } from 'vue'
import { authClient, type AuthUser } from '../services/auth'
import UiModal from './UiModal.vue'
import MfaSettings from './MfaSettings.vue'
const props = defineProps<{ user: AuthUser }>()
const emit = defineEmits<{ close: []; saved: [user: AuthUser]; notify: [message: string] }>()
@@ -47,6 +48,7 @@ async function save() {
<input id="account-confirm-password" v-model="form.confirmPassword" type="password" class="text-input" maxlength="256" autocomplete="new-password" placeholder="留空表示不修改" />
<p class="form-hint">普通用户新密码至少 8 位;超级管理员按实际设置保存。</p>
</form>
<MfaSettings />
<template #footer>
<button class="button secondary" :disabled="saving" @click="emit('close')">取消</button>
<button class="button primary" type="submit" form="account-settings" :disabled="saving">{{ saving ? '保存中…' : '保存设置' }}</button>
@@ -0,0 +1,53 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { catalogClient, type CatalogModel } from '../services/catalog'
import { enterprise } from '../services/enterprise'
type Json = Record<string, unknown>
const models = ref<CatalogModel[]>([]), selected = ref(''), loaded = ref(false), busy = ref(false), notice = ref(''), history = ref<Json[]>([]), records = ref<Json[]>([]), summary = ref<Json>({}), page = ref(1)
const retail = ref<Json>({}), procurement = ref<Json | null>(null), retailFields = reactive<Record<string, string>>({}), costFields = reactive<Record<string, string>>({}), costKnown = ref(false), retailTiers = ref('[]'), costTiers = ref('[]'), protocols = ref<string[]>([])
const fields = [{ id: 'input', label: '普通输入' }, { id: 'output', label: '输出' }, { id: 'cachedInput', label: '缓存命中输入' }, { id: 'cacheWrite5m', label: '缓存写入 · 5 分钟' }, { id: 'cacheWrite1h', label: '缓存写入 · 1 小时' }]
const reconcileId = ref(''), reconcileCost = ref(''), reconcileNote = ref('')
const expectedRetail = ref<Json | null>(null)
const failoverEnabled = computed({ get: () => Boolean(models.value.find(m => m.id === selected.value)?.capabilities.failover), set: value => { const model = models.value.find(m => m.id === selected.value); if (model) model.capabilities.failover = value } })
const money = (v: unknown) => v == null ? '待核' : `¥ ${Number(v).toLocaleString('zh-CN', { maximumFractionDigits: 8 })}`
const state = (s: unknown) => ({ unknown: '成本未知', pending: '待对账', estimated: '按采购价估算', reconciled: '已核对' }[String(s)] || String(s))
async function refresh() { const data = await enterprise<{ records: Json[]; summary: Json }>(`/api/admin/finance/reconciliation?page=${page.value}`); records.value = data.records; summary.value = data.summary }
onMounted(async () => { try { models.value = (await catalogClient.listAdminModels()).models.filter(m => m.mode !== 'async' && ['text', 'code', 'multimodal', 'embedding'].includes(m.type)); await refresh() } catch (e) { notice.value = String(e) } })
async function load() {
loaded.value = false; notice.value = ''; if (!selected.value) return
busy.value = true
try {
const data = await enterprise<{ current: Json; history: Json[] }>(`/api/admin/finance/prices/${selected.value}`)
expectedRetail.value = data.current.pricing ? JSON.parse(String(data.current.pricing)) : null
retail.value = expectedRetail.value || {}
procurement.value = data.current.procurement_pricing ? JSON.parse(String(data.current.procurement_pricing)) : null
history.value = data.history; costKnown.value = !!procurement.value
for (const field of fields) { retailFields[field.id] = String(retail.value[field.id] ?? ''); costFields[field.id] = String(procurement.value?.[field.id] ?? '') }
retailTiers.value = JSON.stringify(retail.value.tiers || [], null, 2); costTiers.value = JSON.stringify(procurement.value?.tiers || [], null, 2)
protocols.value = [...(models.value.find(m => m.id === selected.value)?.capabilities.protocols as string[] || [])]; loaded.value = true
} catch (e) { notice.value = String(e) } finally { busy.value = false }
}
function schedule(base: Json, values: Record<string, string>, tiers: string) { const out: Json = { ...base, unit: 'CNY / 1M tokens', tiers: JSON.parse(tiers) }; for (const f of fields) { if (values[f.id]?.trim()) out[f.id] = values[f.id]; else delete out[f.id] }; delete out.discount; out.discountLabel = '自定义价格'; return out }
async function save() {
busy.value = true
try { await enterprise(`/api/admin/finance/prices/${selected.value}`, { pricing: schedule(retail.value, retailFields, retailTiers.value), procurementPricing: costKnown.value ? schedule(procurement.value || {}, costFields, costTiers.value) : null, expectedPricing: expectedRetail.value, expectedProcurementPricing: procurement.value }); await load(); notice.value = '价格版本已保存,新请求使用新价格。' } catch (e) { notice.value = String(e) } finally { busy.value = false }
}
async function saveProtocols() { busy.value = true; try { await enterprise(`/api/admin/finance/protocols/${selected.value}`, { protocols: protocols.value, failover: failoverEnabled.value }); const model = models.value.find(m => m.id === selected.value); if (model) model.capabilities.protocols = [...protocols.value]; notice.value = '协议配置已保存,请使用测试 Key 验证渠道接口。' } catch (e) { notice.value = String(e) } finally { busy.value = false } }
async function reconcile() { busy.value = true; try { await enterprise(`/api/admin/finance/reconciliation/${reconcileId.value}`, { procurementCost: reconcileCost.value, note: reconcileNote.value }, 'POST'); reconcileId.value = ''; reconcileCost.value = ''; reconcileNote.value = ''; await refresh(); notice.value = '采购成本已核对,用户扣费不变。' } catch (e) { notice.value = String(e) } finally { busy.value = false } }
</script>
<template>
<section class="page-heading compact"><div><span>FINANCE</span><h1>价格版本与成本对账</h1><p>人民币统一结算。采购成本与用户售价独立维护,未知成本不计入已知利润。</p></div></section>
<p role="status">{{ notice }}</p>
<section class="panel finance-card"><h3>Token 价格规则</h3><label class="form-label">模型路由<select v-model="selected" class="text-input" @change="load"><option value="">请选择模型</option><option v-for="m in models" :key="m.id" :value="m.id">{{ m.publicName }} · {{ m.sourceLabel || m.id }}</option></select></label>
<template v-if="loaded"><form @submit.prevent="save"><div class="finance-grid"><div><h4>用户售价 · 元/百万 Token</h4><label v-for="f in fields" :key="f.id" class="form-label">{{ f.label }}<input v-model="retailFields[f.id]" class="text-input" inputmode="decimal" :required="['input', 'output'].includes(f.id)" placeholder="按普通输入价格" /></label><details><summary>上下文阶梯规则</summary><p>按 aboveInputTokens 从小到大排列,超过阈值时覆盖对应价格。</p><textarea v-model="retailTiers" class="text-input" rows="6" placeholder='[{"aboveInputTokens":200000,"input":4,"output":16}]' /></details></div><div><h4>采购成本 · 元/百万 Token</h4><label><input v-model="costKnown" type="checkbox" /> 已核实采购成本</label><template v-if="costKnown"><label v-for="f in fields" :key="f.id" class="form-label">{{ f.label }}<input v-model="costFields[f.id]" class="text-input" inputmode="decimal" :required="['input', 'output'].includes(f.id)" placeholder="按普通输入价格" /></label><details><summary>采购上下文阶梯规则</summary><textarea v-model="costTiers" class="text-input" rows="6" /></details></template><p v-else>采购成本保留未知状态,后续可根据渠道账单核对。</p></div></div><button class="button primary" :disabled="busy">保存价格新版本</button></form>
<details><summary>最近 {{ history.length }} 个版本</summary><div class="history"><div v-for="h in history" :key="String(h.id)"><strong>#{{ h.id }} · {{ h.created_at }}</strong><pre>{{ JSON.stringify(JSON.parse(String(h.pricing || '{}')), null, 2) }}</pre></div></div></details>
<h4>原生协议</h4><p>仅为已确认支持原生接口的渠道启用。未勾选的原生协议会明确拒绝请求。标准 Chat/Embeddings 由模型类型决定。</p><div class="protocols"><label v-for="p in ['messages', 'responses', 'gemini']" :key="p"><input v-model="protocols" type="checkbox" :value="p" /> {{ p }}</label><button class="button secondary" :disabled="busy" @click="saveProtocols">保存协议</button></div>
<label><input v-model="failoverEnabled" type="checkbox" /> 允许切换到已授权的同模型备用渠道(用户售价不变)</label><p>开关与上方协议配置一同保存。仅在明确拒绝请求时切换;超时和已开始输出的请求不重试。</p>
</template>
</section>
<section class="panel finance-card"><h3>本月对账</h3><div class="finance-grid"><p>用户消费 <strong>{{ money(summary.revenue) }}</strong></p><p>已知采购成本 <strong>{{ money(summary.known_cost) }}</strong></p><p>已知利润 <strong>{{ money(summary.known_margin) }}</strong></p><p>待核记录 <strong>{{ summary.pending || 0 }}</strong></p></div>
<form v-if="reconcileId" @submit.prevent="reconcile"><h4>核对 {{ reconcileId }}</h4><label class="form-label">实际采购成本(元)<input v-model="reconcileCost" class="text-input" inputmode="decimal" required /></label><label class="form-label">渠道账单依据<textarea v-model="reconcileNote" class="text-input" minlength="3" maxlength="2000" required /></label><button class="button primary" :disabled="busy">确认成本</button><button type="button" class="button secondary" @click="reconcileId = ''">取消</button></form>
<div class="responsive-table"><table><thead><tr><th>时间/模型</th><th>调用</th><th>用户消费</th><th>采购成本</th><th>核对状态</th><th></th></tr></thead><tbody><tr v-for="r in records" :key="String(r.id)"><td>{{ r.created_at }}<br />{{ r.public_name }}</td><td>{{ r.status }}</td><td>{{ money(r.cost_amount) }}</td><td>{{ money(r.procurement_cost) }}</td><td>{{ state(r.cost_status) }}</td><td><button class="button secondary small" @click="reconcileId = String(r.id); reconcileCost = ''; reconcileNote = ''">核对</button></td></tr></tbody></table></div><div class="protocols"><button class="button secondary" :disabled="page <= 1" @click="page--; refresh().catch(e => notice = String(e))">上一页</button><span>第 {{ page }} 页</span><button class="button secondary" :disabled="records.length < 50" @click="page++; refresh().catch(e => notice = String(e))">下一页</button></div>
</section>
</template>
<style scoped>.finance-card{padding:24px;margin-bottom:22px}.finance-card .form-label{flex-direction:column;gap:8px}.finance-card p{font-size:13px;color:#64736d;line-height:1.7}.finance-grid{display:grid;grid-template-columns:1fr 1fr;gap:24px}.finance-card button,.finance-card details{margin-top:16px}.finance-card summary{cursor:pointer}.history{max-height:340px;overflow:auto}.history pre{white-space:pre-wrap;background:#f3f6f4;padding:12px}.protocols{display:flex;align-items:center;gap:18px;flex-wrap:wrap}@media(max-width:700px){.finance-grid{grid-template-columns:1fr}}</style>
@@ -0,0 +1,21 @@
<script setup lang="ts">
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import { enterprise } from '../services/enterprise'
type Row = Record<string, string | number | boolean | null>
const accounts = ref<Row[]>([]), alerts = ref<Row[]>([]), notice = ref(''), busy = ref(false)
const rule = reactive({ enabled: true, windowMinutes: 5, minimumRequests: 10, errorPercent: 20, cooldownMinutes: 30, notificationEnabled: false, notificationEmail: '' })
async function refresh(initial = false) { try { const data = await enterprise<{ accounts: Row[]; alerts: Row[]; rules: Row[] }>('/api/admin/operations'); accounts.value = data.accounts; alerts.value = data.alerts; if (initial && data.rules[0]) { const r = data.rules[0]; Object.assign(rule, { enabled: r.enabled, windowMinutes: Number(r.window_minutes), minimumRequests: Number(r.minimum_requests), errorPercent: Number(r.error_percent), cooldownMinutes: Number(r.cooldown_minutes), notificationEnabled: !!r.notification_enabled, notificationEmail: String(r.notification_email || '') }) } } catch (e) { notice.value = String(e) } }
let timer: ReturnType<typeof setInterval> | undefined
onMounted(() => { refresh(true); timer = setInterval(() => refresh(), 30000) }); onUnmounted(() => clearInterval(timer))
async function save() { busy.value = true; try { await enterprise('/api/admin/operations/rules/gateway-errors', rule); notice.value = '告警规则已保存' } catch (e) { notice.value = String(e) } finally { busy.value = false } }
async function ack(id: unknown) { try { await enterprise(`/api/admin/operations/alerts/${id}/acknowledge`, {}, 'POST'); await refresh() } catch (e) { notice.value = String(e) } }
const state = (value: unknown) => ({ open: '待处理', acknowledged: '已确认', resolved: '已恢复', disabled: '通知关闭', pending: '待发送', retry: '待重试', sent: '已发送', failed: '发送失败' }[String(value)] || String(value))
</script>
<template>
<section class="page-heading compact"><div><span>OPERATIONS</span><h1>渠道健康与告警</h1><p>每 30 秒刷新。账号异常会暂时隔离;恢复后可重新参与调度。</p></div><button class="button secondary" @click="refresh()">刷新</button></section><p role="status">{{ notice }}</p>
<section class="panel ops-card"><h3>错误率告警</h3><form @submit.prevent="save"><label><input v-model="rule.enabled" type="checkbox" /> 启用站内告警</label><div class="ops-grid"><label class="form-label">统计窗口(分钟)<input v-model.number="rule.windowMinutes" type="number" min="1" max="1440" class="text-input" required /></label><label class="form-label">最小请求数<input v-model.number="rule.minimumRequests" type="number" min="1" class="text-input" required /></label><label class="form-label">错误率阈值(%)<input v-model.number="rule.errorPercent" type="number" min="0" max="100" step="0.01" class="text-input" required /></label><label class="form-label">重复提醒间隔(分钟)<input v-model.number="rule.cooldownMinutes" type="number" min="1" max="1440" class="text-input" required /></label></div><button class="button primary" :disabled="busy">保存规则</button></form></section>
<section class="panel ops-card"><h3>邮件通知</h3><form @submit.prevent="save"><label><input v-model="rule.notificationEnabled" type="checkbox" /> 将新告警发送至指定邮箱</label><label class="form-label">告警接收邮箱<input v-model="rule.notificationEmail" type="email" class="text-input" :required="rule.notificationEnabled" /></label><p>使用平台已配置的邮件服务。默认关闭;发送失败最多尝试 3 次,告警编号可用于识别重复通知。</p><button class="button secondary" :disabled="busy">保存通知设置</button></form></section>
<section class="panel ops-card"><h3>最近告警</h3><div class="responsive-table"><table><thead><tr><th>时间</th><th>失败/总请求</th><th>错误率</th><th>状态/通知</th><th></th></tr></thead><tbody><tr v-for="a in alerts" :key="String(a.id)"><td>{{ a.created_at }}</td><td>{{ a.failed_requests }} / {{ a.total_requests }}</td><td>{{ a.error_percent }}%</td><td>{{ state(a.status) }} / {{ a.notification_status }}</td><td><button v-if="a.status === 'open'" class="button secondary small" @click="ack(a.id)">确认处理</button></td></tr><tr v-if="!alerts.length"><td colspan="5">暂无告警</td></tr></tbody></table></div></section>
<section class="panel ops-card"><h3>渠道账号健康</h3><p>仅显示不可逆的账号指纹,不显示上游密钥。延迟为上游响应头到达时间的平滑值。</p><div class="responsive-table"><table><thead><tr><th>模型/账号</th><th>连续异常</th><th>最近状态码</th><th>延迟</th><th>隔离至</th></tr></thead><tbody><tr v-for="a in accounts" :key="`${a.route_id}-${a.account}`"><td>{{ a.public_name || a.route_id }}<br /><code>{{ a.account }}</code></td><td>{{ a.failures }}</td><td>{{ a.last_status }}</td><td>{{ a.latency_ms }} ms</td><td>{{ a.cooldown_until || '正常' }}</td></tr><tr v-if="!accounts.length"><td colspan="5">调用后显示健康记录</td></tr></tbody></table></div></section>
</template>
<style scoped>.ops-card{padding:24px;margin-bottom:22px}.ops-card .form-label{flex-direction:column;gap:8px}.ops-card p{color:#64736d;font-size:13px}.ops-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}.ops-card button{margin-top:16px}@media(max-width:850px){.ops-grid{grid-template-columns:1fr 1fr}}</style>
@@ -0,0 +1,32 @@
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { catalogClient } from '../services/catalog'
import { enterprise } from '../services/enterprise'
const props = defineProps<{ admin?: boolean }>()
const choices = ref<{ id: string; name: string }[]>([]), selected = ref(''), busy = ref(false), notice = ref(''), loaded = ref(false)
const form = reactive({ requestsPerMinute: 120, maxConcurrency: 16, monthlyBudget: '', dailyBudget: '', totalBudget: '', expiresAt: '', ipAllowlist: '' })
onMounted(async () => { try { choices.value = props.admin ? (await catalogClient.listAdminUsers()).users.map(u => ({ id: u.id, name: `${u.displayName} · ${u.account}` })) : (await catalogClient.listKeys()).keys.map(k => ({ id: k.id, name: k.name })); } catch (e) { notice.value = String(e) } })
function path() { return props.admin ? `/api/admin/users/${selected.value}/gateway-policy` : `/api/keys/${selected.value}/policy` }
async function load() {
loaded.value = false; notice.value = ''; if (!selected.value) return
busy.value = true
try { const data = await enterprise<Record<string, string | number | null>>(path()); Object.assign(form, { requestsPerMinute: data.requests_per_minute ?? 120, maxConcurrency: data.max_concurrency ?? 16, monthlyBudget: data.monthly_budget ?? '', dailyBudget: data.daily_budget ?? '', totalBudget: data.total_budget ?? '', expiresAt: data.expires_at ? new Date(String(data.expires_at)).toLocaleString('sv-SE').replace(' ', 'T') : '', ipAllowlist: JSON.parse(String(data.ip_allowlist || '[]')).join('\n') }); loaded.value = true } catch (e) { notice.value = String(e) } finally { busy.value = false }
}
async function save() {
busy.value = true; notice.value = ''
try { await enterprise(path(), { ...form, expiresAt: form.expiresAt ? new Date(form.expiresAt).toISOString() : null, ipAllowlist: form.ipAllowlist.split(/[\s,]+/).filter(Boolean) }); notice.value = '策略已保存,对新请求生效。' } catch (e) { notice.value = e instanceof Error ? e.message : '保存失败' } finally { busy.value = false }
}
</script>
<template>
<section class="page-heading compact"><div><span>ACCESS POLICY</span><h1>{{ admin ? '企业用户调用策略' : 'API Key 安全与预算' }}</h1><p>{{ admin ? '同一用户的多个 Key 共用请求限额和人民币月预算。' : '为每个 Key 设置有效期、来源 IP 和人民币预算。' }}</p></div></section>
<section class="panel policy-card">
<p v-if="!admin && !choices.length">暂无 API Key,请先在「API Keys」页面创建。</p>
<label class="form-label">{{ admin ? '用户' : 'API Key' }}<select v-model="selected" class="text-input" :disabled="busy" @change="load"><option value="">请选择</option><option v-for="item in choices" :key="item.id" :value="item.id">{{ item.name }}</option></select></label>
<form v-if="loaded" @submit.prevent="save">
<div class="policy-grid" v-if="admin"><label class="form-label">每分钟请求数<input v-model.number="form.requestsPerMinute" type="number" min="1" max="100000" class="text-input" required /></label><label class="form-label">最大总并发<input v-model.number="form.maxConcurrency" type="number" min="1" max="10000" class="text-input" required /></label></div>
<template v-else><label class="form-label">有效期截止(本地时间)<input v-model="form.expiresAt" type="datetime-local" class="text-input" /></label><label class="form-label">IP 白名单<textarea v-model="form.ipAllowlist" class="text-input" rows="4" placeholder="每行一个 IPv4、IPv6 或 CIDR;留空为不限" /></label><div class="policy-grid"><label class="form-label">总预算(元)<input v-model="form.totalBudget" inputmode="decimal" class="text-input" placeholder="不限" /></label><label class="form-label">日预算(元)<input v-model="form.dailyBudget" inputmode="decimal" class="text-input" placeholder="不限" /></label></div></template>
<label class="form-label">月预算(元)<input v-model="form.monthlyBudget" inputmode="decimal" class="text-input" placeholder="不限" /></label><p>预算留空表示不限,0 表示不允许付费调用。日、月周期按北京时间计算,统计包含已结算用量与在途预留。调整预算不会修改钱包余额。</p><button class="button primary" :disabled="busy">{{ busy ? '保存中…' : '保存策略' }}</button>
</form><p role="status">{{ notice }}</p>
</section>
</template>
<style scoped>.policy-card{padding:24px;max-width:900px}.policy-card .form-label{flex-direction:column;gap:8px}.policy-card p{font-size:13px;color:#65736e;line-height:1.7}.policy-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px}.policy-card textarea{resize:vertical}.policy-card button{margin-top:16px}@media(max-width:650px){.policy-grid{grid-template-columns:1fr}}</style>
+28
View File
@@ -0,0 +1,28 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { enterprise } from '../services/enterprise'
const enabled = ref(false), remaining = ref(0), password = ref(''), code = ref(''), secret = ref(''), recovery = ref<string[]>([]), busy = ref(false), notice = ref('')
async function load() { const data = await enterprise<{ enabled: boolean; recoveryRemaining: number }>('/api/auth/mfa'); enabled.value = data.enabled; remaining.value = data.recoveryRemaining }
onMounted(() => load().catch(e => { notice.value = e.message }))
async function action(kind: 'setup' | 'confirm' | 'disable') {
busy.value = true; notice.value = ''
try {
const data = await enterprise<{ secret?: string; recoveryCodes?: string[] }>(`/api/auth/mfa/${kind}`, { password: password.value, code: code.value }, 'POST')
if (kind === 'setup') secret.value = data.secret || ''
else { secret.value = ''; password.value = ''; code.value = ''; recovery.value = data.recoveryCodes || []; await load(); notice.value = kind === 'confirm' ? '双因素认证已启用,请保存一次性恢复码。' : '双因素认证已关闭' }
} catch (e) { notice.value = e instanceof Error ? e.message : '操作失败' } finally { busy.value = false }
}
</script>
<template>
<section class="mfa-settings">
<h3>双因素认证 <small>{{ enabled ? '已启用' : '未启用' }}</small></h3>
<p>使用认证器生成验证码。{{ enabled ? `剩余 ${remaining} 个恢复码。` : '启用后,登录需要密码和动态验证码。' }}</p>
<label class="form-label">当前密码<input v-model="password" type="password" autocomplete="current-password" class="text-input" /></label>
<template v-if="secret"><p>在认证器中添加账号,选择「输入设置密钥」,使用以下密钥(10 分钟内有效):</p><code class="mfa-secret">{{ secret }}</code></template>
<label v-if="enabled || secret" class="form-label">{{ enabled ? '验证码或恢复码' : '认证器验证码' }}<input v-model="code" class="text-input" autocomplete="one-time-code" maxlength="24" /></label>
<button class="button secondary" :disabled="busy || !password" @click="action(enabled ? 'disable' : secret ? 'confirm' : 'setup')">{{ busy ? '处理中…' : enabled ? '关闭双因素认证' : secret ? '验证并启用' : '开始设置' }}</button>
<p role="status">{{ notice }}</p>
<template v-if="recovery.length"><p>恢复码只展示这一次,每个只能使用一次,请保存到安全位置:</p><pre class="mfa-secret">{{ recovery.join('\n') }}</pre><button class="button secondary" @click="recovery = []">我已保存</button></template>
</section>
</template>
<style scoped>.mfa-settings{border-top:1px solid #e5e9e8;margin-top:24px;padding-top:16px}.mfa-settings .form-label{flex-direction:column;gap:8px}.mfa-settings p,.mfa-settings small{font-size:13px;color:#64736d}.mfa-secret{display:block;padding:14px;background:#f3f6f4;overflow-wrap:anywhere;user-select:all}.mfa-settings button{margin-top:12px}</style>
@@ -0,0 +1,12 @@
<script setup lang="ts">
import { ref } from 'vue'
const selected = ref('embeddings')
const examples: Record<string, { path: string; body: string; note: string }> = {
embeddings: { path: '/v1/embeddings', body: '{"model":"从 /v1/models 选择向量模型 ID","input":"需要向量化的文字"}', note: '按输入 Token 计费,支持批量文本,无输出 Token 费用。在线调试也支持向量模型。' },
messages: { path: '/v1/messages', body: '{"model":"已启用 Messages 的模型 ID","messages":[{"role":"user","content":"你好"}],"max_tokens":4096,"stream":true}', note: '支持文本、工具调用与原生 SSE 事件。可使用 Authorization: Bearer 或 x-api-key 传入 MOYI Key。' },
responses: { path: '/v1/responses', body: '{"model":"已启用 Responses 的模型 ID","input":"你好","max_output_tokens":4096,"stream":true}', note: '支持完整上下文的文本与函数调用。当前不保存云端会话;请携带完整上下文,不使用 previous_response_id、conversation 或后台任务。' },
gemini: { path: '/v1beta/models/模型ID:generateContent', body: '{"contents":[{"role":"user","parts":[{"text":"你好"}]}],"generationConfig":{"maxOutputTokens":4096}}', note: '流式调用使用 :streamGenerateContent?alt=sse。可使用 Authorization: Bearer 或 x-goog-api-key,Key 放在请求头中。' },
}
</script>
<template><section class="panel native-guide"><h2>标准与原生协议接入</h2><p>所有金额均为人民币,1M Token = 1,000,000 Token。所有接口共用用户、Key 预算和调用记录。</p><div class="protocol-tabs"><button v-for="(_, name) in examples" :key="name" class="button" :class="selected === name ? 'primary' : 'secondary'" @click="selected = String(name)">{{ name }}</button></div><h3>{{ examples[selected]?.path }}</h3><pre>{{ examples[selected]?.body }}</pre><p>{{ examples[selected]?.note }}</p><p>Messages、Responses、Gemini 需要管理员确认渠道支持后启用。原生入口当前支持文本与本地工具调用;图片、音频、托管工具和外部缓存需要对应的计费适配器。</p><p>可选请求头:<code>Idempotency-Key</code> 防止重复受理;<code>X-Moyi-Session</code> 将同一会话绑定到健康的渠道账号。流式输出开始后不会自动重新生成。</p></section></template>
<style scoped>.native-guide{padding:24px;margin-bottom:22px}.native-guide p{font-size:14px;color:#64736d;line-height:1.8}.protocol-tabs{display:flex;gap:10px;flex-wrap:wrap}.native-guide pre{padding:18px;background:#f3f6f4;white-space:pre-wrap;overflow-wrap:anywhere}.native-guide code{overflow-wrap:anywhere}</style>