fix: classify upstream failures and prevent empty billed responses

This commit is contained in:
wlx committed 2026-09-28 04:55:00 +08:00
1 parent b455d8d79f
commit 9acc69d4c7
28 files changed
+1449 -131

No files matched your search

+25 -14
View File
@@ -39,6 +39,9 @@ import SlidePanel from '../components/SlidePanel.vue'
import UiModal from '../components/UiModal.vue'
import CatalogAdmin from '../components/CatalogAdmin.vue'
import AccountAdmin from '../components/AccountAdmin.vue'
import { providerCapabilityLabel, summarizeModelCatalog } from '../services/model-catalog'
import { usePagination } from '../composables/usePagination'
import ListPagination from '../components/ListPagination.vue'
const props = defineProps<{ view: string; currentUser?: AuthUser }>()
const emit = defineEmits<{ navigate: [view: string]; notify: [message: string] }>()
@@ -47,6 +50,7 @@ const users = ref<AdminUser[]>([])
const providers = ref<ProviderItem[]>([])
const models = ref<ModelItem[]>([])
const publicModelCount = ref(0)
const publishedModelCount = ref(0)
const publicRouteCount = ref(0)
const unpricedRouteCount = ref(0)
const adminSummary = ref<AdminUsageSummary | null>(null)
@@ -84,12 +88,11 @@ async function refreshOverviewData(notifyOnSuccess = false) {
])
providers.value = mapProviders(providerResult.providers, modelResult.models)
models.value = mapModels(modelResult.models, providerResult.providers)
const activeProviders = new Set(providerResult.providers.filter((item) => item.status === 'active').map((item) => item.id))
const activeDefinitions = new Set(modelResult.logicalModels.filter((item) => item.status === 'active').map((item) => item.id))
const publishedRoutes = modelResult.models.filter((item) => item.status === 'active' && activeProviders.has(item.providerId) && activeDefinitions.has(item.logicalModelId) && item.pricingConfigured && item.billingReady !== false && item.executionReady !== false)
publicRouteCount.value = publishedRoutes.length
publicModelCount.value = new Set(publishedRoutes.map((item) => item.logicalModelId)).size
unpricedRouteCount.value = modelResult.models.filter((item) => item.status === 'active' && activeProviders.has(item.providerId) && activeDefinitions.has(item.logicalModelId) && !item.pricingConfigured).length
const catalogSummary = summarizeModelCatalog(modelResult.logicalModels, modelResult.models, providerResult.providers)
publishedModelCount.value = catalogSummary.publishedModels
publicRouteCount.value = catalogSummary.readyRoutes
publicModelCount.value = catalogSummary.readyModels
unpricedRouteCount.value = catalogSummary.unpricedRoutes
adminSummary.value = summaryResult
verificationChannels.value = verificationResult
users.value = userResult.users.map(mapUser)
@@ -194,10 +197,12 @@ function formatUsagePayload(value: unknown) {
const queueGroups = computed(() => (adminSummary.value?.capacityGroups || []).map((group) => ({
...group,
type: '模型分组',
wait: group.queued ? '排队中' : '—',
status: group.queued ? '保护中' : '正常',
type: `${group.providerName || '未知渠道'} · ${group.sourceLabel || '模型分组'}`,
status: group.running === null ? '未读取' : group.routeEnabled === false ? '已停用,仍有任务' : group.queued ? '排队中' : group.running ? '执行中' : '空闲',
warning: group.running === null || group.routeEnabled === false || !!group.queued,
})))
const { page: capacityPage, pageSize: capacityPageSize, pagedItems: capacityPageGroups } = usePagination(queueGroups)
const configuredCapacity = computed(() => adminSummary.value?.capacityGroups.filter(group => group.routeEnabled !== false).reduce((total, group) => total + group.limit, 0))
const pricing = computed(() => models.value.filter((model) => model.pricingConfigured).map((model) => ({
model: model.name,
unit: model.pricing?.unit || 'CNY / 1M tokens',
@@ -227,7 +232,7 @@ function mapProviders(items: CatalogProvider[], modelItems: CatalogModel[]): Pro
return items.map((provider) => ({
id: provider.id,
name: provider.name,
capability: modelItems.filter((model) => model.providerId === provider.id).map((model) => model.type).join(' / ') || '待配置能力',
capability: providerCapabilityLabel(modelItems.filter((model) => model.providerId === provider.id).map((model) => model.type)),
models: modelItems.filter((model) => model.providerId === provider.id).length,
latency: '未采样',
successRate: '—',
@@ -277,7 +282,7 @@ function mapModels(items: CatalogModel[], providersList: CatalogProvider[]): Mod
<div class="page-stack admin-pages">
<template v-if="view === 'admin-overview'">
<section class="page-heading compact"><div><span>ADMIN OVERVIEW</span><h1>管理总览</h1><p>掌握平台供给、用户、容量和风险状态。</p></div><div class="heading-actions"><span class="health-badge"><i></i>目录数据已读取</span><button class="button secondary" :disabled="overviewRefreshing" @click="refreshOverviewData(true)"><Activity :size="16" />{{ overviewRefreshing ? '刷新中…' : '刷新数据' }}</button></div></section>
<section class="metric-grid"><article class="metric-card"><span class="icon-tile violet"><Users :size="18" /></span><div><small>用户总数</small><strong>{{ users.length }}</strong><em>来自认证服务</em></div></article><article class="metric-card"><span class="icon-tile cyan"><Cloud :size="18" /></span><div><small>用户端可用模型</small><strong>{{ publicModelCount }}</strong><em>{{ publicRouteCount }} 个已定价分组 · 管理目录 {{ models.length }} 条 · 待定价 {{ unpricedRouteCount }} 个</em></div></article><article class="metric-card"><span class="icon-tile orange"><Gauge :size="18" /></span><div><small>等待 / 执行任务</small><strong>{{ adminSummary?.waiting ?? '—' }}</strong><em>来自最近调用记录</em></div></article><article class="metric-card"><span class="icon-tile green"><CircleDollarSign :size="18" /></span><div><small>今日额度消耗</small><strong>{{ adminSummary ? `¥${Number(adminSummary.costToday || 0).toFixed(4)}` : '—' }}</strong><em>成功调用实际扣费</em></div></article></section>
<section class="metric-grid"><article class="metric-card"><span class="icon-tile violet"><Users :size="18" /></span><div><small>用户总数</small><strong>{{ users.length }}</strong><em>来自认证服务</em></div></article><article class="metric-card"><span class="icon-tile cyan"><Cloud :size="18" /></span><div><small>已完成接入配置的模型</small><strong>{{ publicModelCount }}</strong><em>模型广场显示 {{ publishedModelCount }} 个 · {{ publicRouteCount }} 个就绪分组 · 待定价 {{ unpricedRouteCount }} 个</em></div></article><article class="metric-card"><span class="icon-tile orange"><Gauge :size="18" /></span><div><small>等待 / 执行任务</small><strong>{{ adminSummary?.waiting ?? '—' }} / {{ adminSummary?.running ?? '—' }}</strong><em>Redis 租约与异步任务实时状态</em></div></article><article class="metric-card"><span class="icon-tile green"><CircleDollarSign :size="18" /></span><div><small>今日额度消耗</small><strong>{{ adminSummary ? `¥${Number(adminSummary.costToday || 0).toFixed(4)}` : '—' }}</strong><em>成功调用实际扣费</em></div></article></section>
<section class="two-column equal"><article class="panel chart-panel"><header class="panel-header"><div><span>PLATFORM TRAFFIC</span><h3>平台请求趋势</h3></div><span class="select-button static">最近 7 天</span></header><div v-if="adminSummary" class="traffic-list"><div v-for="point in adminSummary.series" :key="point.date"><span>{{ point.date }}</span><strong>{{ point.count }} 次</strong></div></div><div v-else class="empty-state compact"><BarChart3 :size="22" /><strong>正在加载平台流量</strong><span>刷新后显示最近 7 天调用量</span></div></article><article class="panel health-panel"><header class="panel-header"><div><span>GATEWAY STATUS</span><h3>模型供给状态</h3></div><button class="text-link" @click="emit('navigate', 'admin-routing')">管理渠道<ArrowRight :size="14" /></button></header><div v-if="providers.length" class="health-list"><div v-for="provider in providers.slice(0, 3)" :key="provider.id"><span class="provider-mark">{{ provider.name.slice(0, 1) }}</span><p><strong>{{ provider.name }}</strong><small>{{ provider.capability }} · {{ provider.latency }}</small></p><b>{{ provider.successRate }}</b><span class="status-chip" :class="provider.status === '已启用' ? 'success' : 'warning'"><i></i>{{ provider.status }}</span></div></div><div v-else class="empty-state compact"><Cloud :size="22" /><strong>暂无供应商</strong><span>由管理员登记上游渠道后显示</span></div></article></section>
<section class="two-column narrow-left"><article class="panel quick-credit"><header class="panel-header"><div><span>CREDIT OPERATIONS</span><h3>额度分配</h3></div><ShieldCheck :size="18" /></header><p>人民币额度余额与发放流水</p><button class="button primary full" @click="emit('navigate', 'admin-users')"><Users :size="16" />查看用户</button></article><article class="panel activity-panel"><header class="panel-header"><div><span>RECENT EVENTS</span><h3>最近运营事件</h3></div><button class="text-link" @click="emit('navigate', 'admin-audit')">审计日志<ArrowRight :size="14" /></button></header><div v-if="auditEvents.length" class="activity-list"><div v-for="event in auditEvents.slice(0, 3)" :key="`${event.time}-${event.action}`"><span class="activity-dot cyan"><ShieldCheck :size="14" /></span><p><strong>{{ event.action }}</strong><small>{{ event.actor }} · {{ event.target }}</small></p><time>{{ event.time }}</time></div></div><div v-else class="empty-state compact"><ShieldCheck :size="22" /><strong>暂无运营事件</strong><span>真实管理操作发生后会显示审计记录</span></div></article></section>
</template>
@@ -286,9 +291,15 @@ function mapModels(items: CatalogModel[], providersList: CatalogProvider[]): Mod
<CatalogAdmin v-else-if="view === 'admin-models' || view === 'admin-routing'" :section="view === 'admin-routing' ? 'channels' : 'models'" @notify="emit('notify', $event)" />
<template v-else-if="view === 'admin-capacity'">
<section class="page-heading"><div><span>CAPACITY CONTROL</span><h1>并发与队列</h1><p>显示最近调用记录中的运行、排队数量,以及每个模型分组的配置上限。</p></div><div class="heading-actions"><span class="admin-badge"><ShieldCheck :size="15" />队列保护已启用</span><button class="button secondary" @click="refreshOverviewData(true)"><RefreshCcw :size="15" />刷新监控</button></div></section>
<section class="capacity-grid"><article class="capacity-main"><div class="capacity-ring"><strong>{{ adminSummary?.capacityGroups.reduce((total, group) => total + group.running, 0) ?? '—' }}</strong><span>运行中</span></div><div><small>CONFIGURED CAPACITY</small><h2>{{ adminSummary?.capacityGroups.reduce((total, group) => total + group.limit, 0) ?? '—' }} 个分组上限</h2><p>同步请求超过上限时会在平台内排队,超出等待窗口后返回 429。</p></div></article><article class="metric-card"><span class="icon-tile orange"><Clock3 :size="18" /></span><div><small>等待任务</small><strong>{{ adminSummary?.waiting ?? '—' }}</strong><em>queued / running</em></div></article><article class="metric-card"><span class="icon-tile cyan"><Timer :size="18" /></span><div><small>排队窗口</small><strong>30s</strong><em>环境默认值</em></div></article><article class="metric-card"><span class="icon-tile green"><CheckCircle2 :size="18" /></span><div><small>调度状态</small><strong>已启用</strong><em>数据库队列与 Redis 占用</em></div></article></section>
<section class="panel table-card"><header class="panel-header"><div><span>CAPACITY GROUPS</span><h3>并发与排队状态</h3></div><span class="select-button static">最近 10 分钟</span></header><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="group in queueGroups" :key="group.id"><td><strong>{{ group.name }}</strong><small>{{ group.type }}</small></td><td>{{ group.running }}</td><td>{{ group.limit || '默认' }}</td><td>{{ group.queued }}</td><td>{{ group.wait }}</td><td><span class="status-chip" :class="group.status === '正常' ? 'success' : 'warning'"><i></i>{{ group.status }}</span></td></tr><tr v-if="!queueGroups.length"><td colspan="6"><div class="empty-state compact"><Gauge :size="22" /><strong>暂无活跃模型分组</strong><span>启用并定价的模型调用后会显示容量状态</span></div></td></tr></tbody></table></div></section>
<section class="page-heading"><div><span>CAPACITY CONTROL</span><h1>并发与队列</h1><p>显示实时 Redis 租约、异步任务队列和每个模型分组的配置上限。</p></div><div class="heading-actions"><span class="admin-badge"><ShieldCheck :size="15" />{{ adminSummary?.capacityConfig ? '运行配置已读取' : '运行配置未读取' }}</span><button class="button secondary" @click="refreshOverviewData(true)"><RefreshCcw :size="15" />刷新监控</button></div></section>
<section class="capacity-grid">
<article class="capacity-main"><div class="capacity-ring"><strong>{{ adminSummary?.running ?? '—' }}</strong><span>实时运行中</span></div><div><small>CONFIGURED CAPACITY</small><h2>{{ configuredCapacity ?? '—' }} 个配置槽位</h2><p>启用分组的上限合计;上游共享限额仍会影响实际吞吐。</p></div></article>
<article class="metric-card"><span class="icon-tile orange"><Clock3 :size="18" /></span><div><small>等待任务</small><strong>{{ adminSummary?.waiting ?? '—' }}</strong><em>不含正在执行的请求</em></div></article>
<article class="metric-card"><span class="icon-tile cyan"><Timer :size="18" /></span><div><small>同步排队窗口</small><strong>{{ adminSummary?.capacityConfig ? `${adminSummary.capacityConfig.queueWaitMs / 1000}s` : '—' }}</strong><em>读取当前服务器配置</em></div></article>
<article class="metric-card"><span class="icon-tile green"><CheckCircle2 :size="18" /></span><div><small>同步占用快照</small><strong>{{ adminSummary?.capacityConfig?.synchronousSnapshotAvailable ? '已读取' : '未读取' }}</strong><em>来自 Redis 有效租约</em></div></article>
</section>
<p v-if="adminSummary?.capacityConfig" class="billing-note">单 Key 并发上限 {{ adminSummary.capacityConfig.defaultKeyConcurrency }};未单独设置的模型分组默认上限 {{ adminSummary.capacityConfig.defaultModelConcurrency }}。每组异步等待与执行总量上限 {{ adminSummary.capacityConfig.asyncQueueLimit }},任务扫描间隔 {{ adminSummary.capacityConfig.asyncWorkerIntervalMs / 1000 }} 秒。同步与异步分别计数。</p>
<section class="panel table-card"><header class="panel-header"><div><span>CAPACITY GROUPS</span><h3>并发与排队状态</h3></div><span class="select-button static">{{ queueGroups.length }} 个分组 · 实时快照</span></header><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="group in capacityPageGroups" :key="group.id"><td><div class="stacked-cell"><strong>{{ group.name }}</strong><small>{{ group.type }}</small></div></td><td>{{ group.running ?? '—' }}</td><td>{{ group.limit }}</td><td>{{ group.queued ?? '—' }}</td><td>{{ group.mode === 'async' ? '异步任务队列' : 'Redis 有效租约' }}</td><td><span class="status-chip" :class="group.warning ? 'warning' : 'success'"><i></i>{{ group.status }}</span></td></tr><tr v-if="!queueGroups.length"><td colspan="6"><div class="empty-state compact"><Gauge :size="22" /><strong>{{ adminSummary ? '暂无活跃模型分组' : '容量数据尚未读取' }}</strong><span>启用模型分组后会显示其配置与占用情况</span></div></td></tr></tbody></table></div><ListPagination v-model:page="capacityPage" v-model:page-size="capacityPageSize" :total="queueGroups.length" label="容量分组分页" /></section>
</template>
<template v-else-if="view === 'admin-billing'">
+33 -4
View File
@@ -76,7 +76,7 @@ const playgroundModels = computed(() => [...new Map(catalogModels.value.map(grou
const playgroundGroups = computed(() => catalogModels.value.filter(group => (group.logicalModelId || group.id) === (activeModel.value.logicalModelId || activeModel.value.id)))
function selectPlaygroundGroup(id: string) {
const group = catalogModels.value.find(item => item.id === id)
if (group) { activeModel.value = group; callMode.value = group.mode; response.value = ''; activeTaskId.value = '' }
if (group) { activeModel.value = group; callMode.value = group.mode; response.value = ''; reasoningOutput.value = ''; finishReason.value = ''; activeTaskId.value = '' }
}
function selectPlaygroundModel(id: string) {
const group = catalogModels.value.find(item => (item.logicalModelId || item.id) === id)
@@ -86,6 +86,7 @@ const prompt = ref('')
const running = ref(false)
const maxOutputTokens = ref(4096)
const reasoningOutput = ref('')
const finishReason = ref('')
let streamAbort: AbortController | undefined
const response = ref('')
const responseError = ref('')
@@ -103,6 +104,8 @@ function restoreHistory(record: UserUsageRecord) {
const text = typeof input?.prompt === 'string' ? input.prompt : messages.filter(message => message?.role === 'user' && typeof message.content === 'string').map(message => message.content).join('\n')
prompt.value = text.slice(0, 4000)
response.value = ''
reasoningOutput.value = ''
finishReason.value = ''
emit('notify', !group ? '历史文本已载入,原分组已不可用,请重新选择模型和分组' : text.length > 4000 ? '已载入前 4000 字,请检查输入后再调用' : text ? '历史输入已载入,确认配置后可再次调用' : '该记录没有可恢复的纯文本输入,请手动填写')
}
const selectedTask = ref<TaskItem | null>(null)
@@ -290,6 +293,8 @@ function tryModel(model: GalleryModel) {
callMode.value = group.mode
selectedModel.value = null
response.value = ''
reasoningOutput.value = ''
finishReason.value = ''
emit('navigate', 'playground')
}
@@ -309,6 +314,7 @@ async function runModel() {
response.value = ''
responseError.value = ''
reasoningOutput.value = ''
finishReason.value = ''
const selectedMode = callMode.value
try {
if (callMode.value === '异步') {
@@ -323,7 +329,15 @@ async function runModel() {
await catalogClient.playgroundStreamChat(apiKey, { model: activeModel.value.id, prompt: prompt.value, maxTokens: maxOutputTokens.value }, (text, reasoning) => { response.value += text; reasoningOutput.value += reasoning }, streamAbort.signal)
} else {
const result = await catalogClient.playgroundChatCompletion(apiKey, { model: activeModel.value.id, prompt: prompt.value, maxTokens: maxOutputTokens.value })
response.value = result.choices[0]?.message.content || '模型未返回内容'
const choice = result.choices[0]
const message = choice?.message
const reasoning = typeof message?.reasoning_content === 'string' ? message.reasoning_content : typeof message?.reasoning === 'string' ? message.reasoning : ''
reasoningOutput.value = reasoning
finishReason.value = typeof choice?.finish_reason === 'string' ? choice.finish_reason : ''
const content = normalizeAssistantContent(message?.content)
// Keep reasoning separate from the final answer. A small output budget
// can legitimately end after reasoning; leave that choice to the user.
response.value = content || (reasoning ? '模型仅返回了思考过程,未返回最终答案;可调整最大输出 Token 后重试。' : '模型未返回内容')
}
emit('notify', callMode.value === '异步' ? '异步任务提交成功' : '模型调用完成')
} catch (error) {
@@ -337,6 +351,16 @@ async function runModel() {
}
}
function normalizeAssistantContent(value: unknown): string {
if (typeof value === 'string') return value
if (!Array.isArray(value)) return ''
return value.map((part) => {
if (typeof part === 'string') return part
if (part && typeof part === 'object' && typeof (part as { text?: unknown }).text === 'string') return (part as { text: string }).text
return ''
}).join('')
}
function mapAsyncTask(task: AsyncTaskResult, model: ModelItem, taskPrompt?: string): TaskItem {
const modelUrl = task.output?.modelUrl || task.result?.modelUrl || (task.provider ? task.result?.url : undefined)
const videoUrl = task.output?.videoUrl || task.result?.videoUrl
@@ -394,6 +418,11 @@ async function pollTask(taskId: string, apiKey: string) {
scheduleTaskPoll(taskId, apiKey, 2500)
} else {
taskPollers.delete(taskId)
// The async endpoint settles or releases the wallet only when the
// provider task reaches a terminal state. Refresh the overview here so
// the balance card and usage counters reflect that settlement immediately
// instead of waiting for a full page reload.
await refreshOverview()
emit('notify', latest.status === 'succeeded' ? '3D 模型生成完成,可以预览和下载' : '3D 任务未能完成')
}
} catch (error) {
@@ -616,7 +645,7 @@ async function createProject() {
</section>
<section class="playground-grid">
<article class="panel request-panel">
<header class="panel-header"><div><span>REQUEST</span><h3>请求配置</h3></div><button class="icon-button" @click="prompt = ''; response = ''; activeTaskId = ''"><RefreshCcw :size="16" /></button></header>
<header class="panel-header"><div><span>REQUEST</span><h3>请求配置</h3></div><button class="icon-button" @click="prompt = ''; response = ''; reasoningOutput = ''; finishReason = ''; activeTaskId = ''"><RefreshCcw :size="16" /></button></header>
<div class="playground-selectors">
<label>模型<select class="text-input" aria-label="调试模型" :value="activeModel.logicalModelId || activeModel.id" :disabled="running || !playgroundModels.length" @change="selectPlaygroundModel(($event.target as HTMLSelectElement).value)"><option v-for="model in playgroundModels" :key="model.logicalModelId || model.id" :value="model.logicalModelId || model.id">{{ model.name }}</option></select></label>
<label>分组<select class="text-input" aria-label="调试分组" :value="activeModel.id" :disabled="running || !playgroundGroups.length" @change="selectPlaygroundGroup(($event.target as HTMLSelectElement).value)"><option v-for="group in playgroundGroups" :key="group.id" :value="group.id">{{ group.sourceLabel || '默认分组' }} · {{ group.provider }}</option></select></label>
@@ -642,7 +671,7 @@ async function createProject() {
<dl v-if="activeTask.creditsConsumed !== undefined" class="task-cost"><dt>上游任务消耗</dt><dd>{{ activeTask.creditsConsumed }} credits</dd></dl>
<div class="live-task-actions"><button class="button secondary" @click="emit('navigate', 'tasks')"><FileClock :size="16" />任务中心</button><button v-if="activeTask.modelUrl" class="button primary" @click="openTaskAsset(activeTask.modelUrl)"><Download :size="16" />下载 GLB</button><button v-if="activeTask.videoUrl" class="button primary" @click="openTaskAsset(activeTask.videoUrl)"><ExternalLink :size="16" />查看视频</button><button v-if="activeTask.previewUrl" class="icon-button" title="打开预览" @click="openTaskAsset(activeTask.previewUrl)"><ExternalLink :size="16" /></button></div>
</div>
<div v-else-if="response || responseError" class="response-result"><div><span class="status-chip" :class="responseError ? 'failed' : running ? 'muted' : 'success'"><i></i>{{ responseError ? '调用未正常完成' : running ? '正在输出' : '调用完成' }}</span><small>MOYI unified response</small></div><p>{{ response }}</p><p v-if="responseError" role="alert">{{ responseError }}</p></div>
<div v-else-if="response || responseError" class="response-result"><div><span class="status-chip" :class="responseError ? 'failed' : running ? 'muted' : 'success'"><i></i>{{ responseError ? '调用未正常完成' : running ? '正在输出' : '调用完成' }}</span><small>MOYI unified response<span v-if="finishReason"> · finish_reason: {{ finishReason }}</span></small></div><p>{{ response }}</p><p v-if="responseError" role="alert">{{ responseError }}</p></div>
<div v-else class="response-state empty"><span class="response-icon"><Sparkles :size="28" /></span><strong>等待模型响应</strong><p>配置请求并点击“开始调用”</p></div>
</article>
</section>