feat: stream chat and settle metered CNY usage atomically
This commit is contained in:
1 parent
7360cf3ebe
commit
b46ee72f2d
28 files changed
+1098
-86
No files matched your search
@@ -140,7 +140,7 @@ function accountSaved(user: AuthUser) {
|
||||
<div class="sidebar-footer">
|
||||
<div v-if="portal === 'user'" class="balance-card">
|
||||
<span>可用额度</span>
|
||||
<strong>{{ availableCredit === undefined ? '--' : `¥ ${availableCredit.toFixed(2)}` }}</strong>
|
||||
<strong>{{ availableCredit === undefined ? '--' : `¥ ${availableCredit.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 8 })}` }}</strong>
|
||||
<small>人民币 CNY</small>
|
||||
</div>
|
||||
<div v-else class="security-card"><ShieldCheck :size="17" /><span>管理操作均写入审计日志</span></div>
|
||||
|
||||
@@ -35,7 +35,7 @@ const entries = ref<WalletEntry[]>([])
|
||||
const ledgerLoading = ref(false)
|
||||
const filteredUsers = computed(() => users.value.filter(user => `${user.account} ${user.displayName}`.toLowerCase().includes(query.value.toLowerCase())))
|
||||
const totalBalance = computed(() => Object.values(balances.value).reduce((sum, balance) => sum + Number(balance), 0))
|
||||
const money = (value: number | undefined) => `¥ ${Number(value || 0).toFixed(2)}`
|
||||
const money = (value: number | undefined) => `¥ ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 8 })}`
|
||||
const roleName = (value: string) => ({ user: '普通用户', admin: '管理员', super_admin: '超级管理员' })[value] || value
|
||||
async function refresh() {
|
||||
loading.value = true
|
||||
@@ -126,7 +126,7 @@ async function copyText(value: string) {
|
||||
</form>
|
||||
<template #footer><button class="button secondary" :disabled="saving" @click="editor = ''">关闭</button><button v-if="!inviteCode || editor !== 'invite'" class="button primary" type="submit" form="account-editor" :disabled="saving">{{ saving ? '提交中…' : editor === 'credit' ? '确认调整' : '确认' }}</button></template>
|
||||
</UiModal>
|
||||
<SlidePanel v-if="ledgerUser" :title="`${ledgerUser.displayName} · 额度流水`" @close="ledgerUser = undefined"><p>币种:人民币 CNY</p><p v-if="ledgerLoading">加载中…</p><div v-for="entry in entries" :key="entry.id" class="wallet-entry"><strong>{{ Number(entry.amount) >= 0 ? '+' : '−' }} {{ money(Math.abs(Number(entry.amount))) }}</strong><small> · {{ ({ increase: '增加', decrease: '减少', set: '设置余额' })[entry.operation] }}</small><p>{{ entry.reason }}</p><small>{{ entry.actor }} · {{ new Date(entry.createdAt).toLocaleString('zh-CN') }}</small><p>{{ money(entry.balanceBefore) }} → {{ money(entry.balanceAfter) }}</p></div><p v-if="!entries.length && !ledgerLoading">暂无流水</p></SlidePanel>
|
||||
<SlidePanel v-if="ledgerUser" :title="`${ledgerUser.displayName} · 额度流水`" @close="ledgerUser = undefined"><p>币种:人民币 CNY</p><p v-if="ledgerLoading">加载中…</p><div v-for="entry in entries" :key="entry.id" class="wallet-entry"><strong>{{ Number(entry.amount) >= 0 ? '+' : '−' }} {{ money(Math.abs(Number(entry.amount))) }}</strong><small> · {{ ({ increase: '增加', decrease: '减少', set: '设置余额', usage: '模型扣费' })[entry.operation] }}</small><p>{{ entry.reason }}</p><small>{{ entry.actor }} · {{ new Date(entry.createdAt).toLocaleString('zh-CN') }}</small><p>{{ money(entry.balanceBefore) }} → {{ money(entry.balanceAfter) }}</p></div><p v-if="!entries.length && !ledgerLoading">暂无流水</p></SlidePanel>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -27,7 +27,7 @@ async function remove() {
|
||||
}
|
||||
const channel = reactive({ code: '', name: '', protocol: 'openai-compatible' as CatalogProvider['protocol'], sourceType: 'relay' as CatalogProvider['sourceType'], baseUrl: '', credentialType: 'api-key' as NonNullable<CatalogProvider['credentialType']>, credentialSecret: '', description: '', status: 'active' as CatalogProvider['status'] })
|
||||
const model = reactive({ publicName: '', modelKey: '', type: 'text' as LogicalModel['type'], mode: 'sync' as LogicalModel['mode'], description: '', inputTypes: 'text', outputTypes: 'text', status: 'active' as LogicalModel['status'] })
|
||||
const group = reactive({ logicalModelId: '', providerId: '', sourceLabel: '', upstreamModel: '', input: '', output: '', unit: 'CNY / 1M tokens', priority: '100', maxConcurrency: '1', status: 'active' as CatalogModel['status'] })
|
||||
const group = reactive({ logicalModelId: '', providerId: '', sourceLabel: '', upstreamModel: '', input: '', output: '', cachedInput: '', unit: 'CNY / 1M tokens', priority: '100', maxConcurrency: '1', status: 'active' as CatalogModel['status'] })
|
||||
const shownModels = computed(() => models.value.filter(item => `${item.publicName} ${item.modelKey || ''}`.toLowerCase().includes(query.value.toLowerCase())))
|
||||
const shownChannels = computed(() => channels.value.filter(item => `${item.name} ${item.code}`.toLowerCase().includes(query.value.toLowerCase())))
|
||||
const channelName = (id: string) => channels.value.find(item => item.id === id)?.name || id
|
||||
@@ -59,7 +59,7 @@ function editModel(item?: LogicalModel) {
|
||||
}
|
||||
function editGroup(parent: LogicalModel, item?: CatalogModel) {
|
||||
editingId.value = item?.id
|
||||
Object.assign(group, { logicalModelId: parent.id, providerId: item?.providerId || '', sourceLabel: item?.sourceLabel || '', upstreamModel: item?.upstreamModel || '', input: item?.pricing?.input?.toString() || '', output: item?.pricing?.output?.toString() || '', unit: item?.pricing?.unit || 'CNY / 1M tokens', priority: String(item?.priority ?? 100), maxConcurrency: String(item?.maxConcurrency ?? 1), status: item?.status || 'active' })
|
||||
Object.assign(group, { logicalModelId: parent.id, providerId: item?.providerId || '', sourceLabel: item?.sourceLabel || '', upstreamModel: item?.upstreamModel || '', input: item?.pricing?.input?.toString() || '', output: item?.pricing?.output?.toString() || '', cachedInput: item?.pricing?.cachedInput?.toString() || '', unit: item?.pricing?.unit || 'CNY / 1M tokens', priority: String(item?.priority ?? 100), maxConcurrency: String(item?.maxConcurrency ?? 1), status: item?.status || 'active' })
|
||||
editor.value = 'group'
|
||||
}
|
||||
async function save() {
|
||||
@@ -76,7 +76,7 @@ async function save() {
|
||||
await catalogClient.saveDefinition(editingId.value, { ...model, inputTypes: model.inputTypes.split(',').map(s => s.trim()).filter(Boolean), outputTypes: model.outputTypes.split(',').map(s => s.trim()).filter(Boolean) })
|
||||
} else {
|
||||
if (!group.providerId || !group.sourceLabel.trim() || !group.upstreamModel.trim()) throw new Error('请选择渠道并填写分组名称、上游模型标识')
|
||||
await catalogClient.saveGroup(editingId.value, { logicalModelId: group.logicalModelId, providerId: group.providerId, sourceLabel: group.sourceLabel, upstreamModel: group.upstreamModel, status: group.status, priority: Number(group.priority), maxConcurrency: Number(group.maxConcurrency), pricing: { input: group.input === '' ? undefined : Number(group.input), output: group.output === '' ? undefined : Number(group.output), unit: group.unit } })
|
||||
await catalogClient.saveGroup(editingId.value, { logicalModelId: group.logicalModelId, providerId: group.providerId, sourceLabel: group.sourceLabel, upstreamModel: group.upstreamModel, status: group.status, priority: Number(group.priority), maxConcurrency: Number(group.maxConcurrency), pricing: { input: group.input === '' ? undefined : Number(group.input), output: group.output === '' ? undefined : Number(group.output), cachedInput: group.cachedInput === '' ? undefined : Number(group.cachedInput), unit: group.unit } })
|
||||
}
|
||||
editor.value = ''
|
||||
await refresh()
|
||||
@@ -141,7 +141,9 @@ async function toggle(kind: 'channel' | 'model' | 'group', item: CatalogProvider
|
||||
<label class="form-label" for="group-channel">渠道</label><select id="group-channel" v-model="group.providerId" class="text-input" required><option value="" disabled>请选择渠道</option><option v-for="item in channels" :key="item.id" :value="item.id">{{ item.name }}{{ item.status === 'disabled' ? '(已停用)' : '' }}</option></select>
|
||||
<label class="form-label" for="group-upstream">上游模型标识</label><input id="group-upstream" v-model="group.upstreamModel" class="text-input" required maxlength="160" />
|
||||
<div class="modal-form-grid"><label><span class="form-label">输入价格</span><input v-model="group.input" class="text-input" type="number" min="0" step="any" /></label><label><span class="form-label">输出价格</span><input v-model="group.output" class="text-input" type="number" min="0" step="any" /></label></div>
|
||||
<label class="form-label">缓存命中输入价格(留空按普通输入价格)<input v-model="group.cachedInput" class="text-input" type="number" min="0" step="any" /></label>
|
||||
<label class="form-label" for="group-unit">价格单位</label><input id="group-unit" v-model="group.unit" class="text-input" required />
|
||||
<small>文本聊天自动扣费仅支持 CNY / 1M tokens(元/百万 Token)。输入、输出均需填写;填 0 表示免费,留空则禁止调用。请填写平台对用户的售价。</small>
|
||||
<div class="modal-form-grid"><label><span class="form-label">优先级</span><input v-model="group.priority" class="text-input" type="number" min="0" step="1" required /></label><label><span class="form-label">并发上限</span><input v-model="group.maxConcurrency" class="text-input" type="number" min="1" step="1" required /></label></div>
|
||||
</template>
|
||||
</form>
|
||||
|
||||
@@ -20,7 +20,7 @@ type Column = keyof typeof columnLabels
|
||||
const columns = ref<Column[]>(['key', 'model', 'group', 'endpoint', 'mode', 'tokens', 'cost', 'latency', 'time', 'status'])
|
||||
const show = (name: Column) => columns.value.includes(name)
|
||||
const number = (n: unknown) => n == null ? '—' : Number(n).toLocaleString('zh-CN')
|
||||
const money = (n: unknown) => n == null ? '—' : `¥ ${Number(n).toFixed(6)}`
|
||||
const money = (n: unknown) => n == null ? '—' : `¥ ${Number(n).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 8 })}`
|
||||
const duration = (n: unknown) => n == null ? '—' : `${(Number(n) / 1000).toFixed(2)}s`
|
||||
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
|
||||
const statusName = (v: string) => ({ succeeded: '成功', failed: '失败', queued: '排队中', running: '执行中', cancelled: '已取消' })[v] || v
|
||||
|
||||
@@ -28,7 +28,7 @@ export interface CatalogModel {
|
||||
inputTypes: string[]
|
||||
outputTypes: string[]
|
||||
capabilities: Record<string, unknown>
|
||||
pricing?: { input?: number; output?: number; unit?: string }
|
||||
pricing?: { input?: number; output?: number; cachedInput?: number; unit?: string }
|
||||
priority?: number
|
||||
maxConcurrency?: number
|
||||
status: 'active' | 'disabled'
|
||||
@@ -51,7 +51,7 @@ export interface WalletEntry {
|
||||
amount: number
|
||||
balanceAfter: number
|
||||
balanceBefore: number
|
||||
operation: 'increase' | 'decrease' | 'set'
|
||||
operation: 'increase' | 'decrease' | 'set' | 'usage'
|
||||
currency: 'CNY'
|
||||
reason: string
|
||||
createdAt: string
|
||||
@@ -92,6 +92,9 @@ export interface PlatformOverview {
|
||||
callsThisMonth: number
|
||||
averageLatencyMs?: number
|
||||
availableCredit?: number
|
||||
balance?: number
|
||||
reservedCredit?: number
|
||||
costThisMonth?: number
|
||||
availabilityPercent?: number
|
||||
asyncTasks: number
|
||||
asyncSuccessRate?: number
|
||||
@@ -287,14 +290,29 @@ class HttpCatalogClient {
|
||||
return response.blob()
|
||||
}
|
||||
|
||||
async chatCompletion(apiKey: string, input: { model: string; prompt: string }) {
|
||||
async chatCompletion(apiKey: string, input: { model: string; prompt: string; maxTokens?: number }) {
|
||||
return this.request<ChatCompletionResult>('/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${apiKey}`, 'X-Moyi-Source': 'playground' },
|
||||
body: JSON.stringify({ model: input.model, messages: [{ role: 'user', content: input.prompt }] }),
|
||||
headers: { Authorization: `Bearer ${apiKey}`, 'X-Moyi-Source': 'playground', 'Idempotency-Key': crypto.randomUUID() },
|
||||
body: JSON.stringify({ model: input.model, messages: [{ role: 'user', content: input.prompt }], max_tokens: input.maxTokens || 4096 }),
|
||||
})
|
||||
}
|
||||
|
||||
async streamChat(apiKey: string, input: { model: string; prompt: string; maxTokens: number }, onDelta: (content: string, reasoning: string) => void, signal: AbortSignal) {
|
||||
const response = await fetch(`${this.baseUrl}/v1/chat/completions`, {
|
||||
method: 'POST', credentials: 'include', signal,
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}`, 'X-Moyi-Source': 'playground', 'Idempotency-Key': crypto.randomUUID() },
|
||||
body: JSON.stringify({ model: input.model, messages: [{ role: 'user', content: input.prompt }], stream: true, max_tokens: input.maxTokens }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({}))
|
||||
throw new Error(error.error?.message || `调用失败 (${response.status})`)
|
||||
}
|
||||
if (!response.body || !response.headers.get('content-type')?.includes('text/event-stream')) throw new Error('服务未返回流式响应')
|
||||
const { readChatStream } = await import('./chat-stream')
|
||||
await readChatStream(response.body, onDelta)
|
||||
}
|
||||
|
||||
async createMediaTask(apiKey: string, input: { model: string; prompt: string; mediaType: '3d' | 'video' }) {
|
||||
const payload = await this.request<{ task: AsyncTaskResult }>(input.mediaType === 'video' ? '/v1/video/tasks' : '/v1/3d/tasks', {
|
||||
method: 'POST',
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/** Parse incrementally: a UTF-8 character or SSE frame may span several network chunks. */
|
||||
export async function readChatStream(body: ReadableStream<Uint8Array>, onDelta: (content: string, reasoning: string) => void) {
|
||||
const reader = body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = '', data: string[] = [], done = false
|
||||
const line = (value: string) => {
|
||||
if (value.endsWith('\r')) value = value.slice(0, -1)
|
||||
if (value === '') {
|
||||
if (!data.length) return
|
||||
const frame = data.join('\n'); data = []
|
||||
if (frame === '[DONE]') { done = true; return }
|
||||
const event = JSON.parse(frame)
|
||||
if (event.error) throw new Error(event.error.message || '流式调用失败')
|
||||
const delta = event.choices?.[0]?.delta
|
||||
if (delta) onDelta(typeof delta.content === 'string' ? delta.content : '', typeof delta.reasoning_content === 'string' ? delta.reasoning_content : '')
|
||||
} else if (value.startsWith('data:')) data.push(value.slice(5).replace(/^ /, ''))
|
||||
}
|
||||
try {
|
||||
while (!done) {
|
||||
const part = await reader.read()
|
||||
buffer += decoder.decode(part.value, { stream: !part.done })
|
||||
let pos: number
|
||||
while ((pos = buffer.indexOf('\n')) >= 0) {
|
||||
line(buffer.slice(0, pos)); buffer = buffer.slice(pos + 1)
|
||||
if (done) break
|
||||
}
|
||||
if (part.done) break
|
||||
if (buffer.length > 262144 || data.join('\n').length > 262144) throw new Error('流式响应超过限制')
|
||||
}
|
||||
if (!done) throw new Error('连接提前结束,请到使用记录中确认调用与扣费状态')
|
||||
} finally {
|
||||
await reader.cancel().catch(() => {})
|
||||
reader.releaseLock()
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ export interface ModelItem {
|
||||
icon: Component
|
||||
modelKey?: string
|
||||
sourceLabel?: string
|
||||
pricing?: { input?: number; output?: number; unit?: string }
|
||||
pricing?: { input?: number; output?: number; cachedInput?: number; unit?: string }
|
||||
priority?: number
|
||||
maxConcurrency?: number
|
||||
}
|
||||
|
||||
@@ -69,7 +69,11 @@ function selectPlaygroundModel(id: string) {
|
||||
}
|
||||
const prompt = ref('')
|
||||
const running = ref(false)
|
||||
const maxOutputTokens = ref(4096)
|
||||
const reasoningOutput = ref('')
|
||||
let streamAbort: AbortController | undefined
|
||||
const response = ref('')
|
||||
const responseError = ref('')
|
||||
const keys = ref<ApiKeyItem[]>([])
|
||||
const tasks = ref<TaskItem[]>([])
|
||||
const historyRevision = ref(0)
|
||||
@@ -139,6 +143,7 @@ onMounted(async () => {
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
streamAbort?.abort()
|
||||
taskPollers.forEach((timer) => window.clearTimeout(timer))
|
||||
taskPollers.clear()
|
||||
copyTimers.forEach((timer) => window.clearTimeout(timer))
|
||||
@@ -221,6 +226,7 @@ async function runModel() {
|
||||
if (!activeModel.value.id) return emit('notify', '当前没有可调用的模型,请先检查模型目录')
|
||||
if (!prompt.value.trim()) return emit('notify', '请先输入调用内容')
|
||||
if (running.value) return
|
||||
if (callMode.value !== '异步' && (!Number.isInteger(maxOutputTokens.value) || maxOutputTokens.value < 1 || maxOutputTokens.value > 32768)) return emit('notify', '最大输出 Token 须为 1–32768 的整数')
|
||||
if (!catalogConnected.value) return emit('notify', 'Control Plane 未连接,无法提交真实调用')
|
||||
if (!remoteApiKey.value) {
|
||||
emit('notify', '请先创建一个临时 API Key,再进行真实接口调用')
|
||||
@@ -230,6 +236,9 @@ async function runModel() {
|
||||
}
|
||||
running.value = true
|
||||
response.value = ''
|
||||
responseError.value = ''
|
||||
reasoningOutput.value = ''
|
||||
const selectedMode = callMode.value
|
||||
try {
|
||||
if (callMode.value === '异步') {
|
||||
const task = await catalogClient.createMediaTask(remoteApiKey.value, { model: activeModel.value.id, prompt: prompt.value, mediaType: activeModel.value.type === '视频' ? 'video' : '3d' })
|
||||
@@ -238,17 +247,22 @@ async function runModel() {
|
||||
activeTaskId.value = task.id
|
||||
response.value = `任务 ${task.id} 已进入队列,可前往任务中心查看进度。`
|
||||
scheduleTaskPoll(task.id, remoteApiKey.value)
|
||||
} else if (selectedMode === '流式') {
|
||||
streamAbort = new AbortController()
|
||||
await catalogClient.streamChat(remoteApiKey.value, { 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.chatCompletion(remoteApiKey.value, { model: activeModel.value.id, prompt: prompt.value })
|
||||
const result = await catalogClient.chatCompletion(remoteApiKey.value, { model: activeModel.value.id, prompt: prompt.value, maxTokens: maxOutputTokens.value })
|
||||
response.value = result.choices[0]?.message.content || '模型未返回内容'
|
||||
}
|
||||
emit('notify', callMode.value === '异步' ? '异步任务提交成功' : '模型调用完成')
|
||||
await refreshOverview()
|
||||
} catch (error) {
|
||||
emit('notify', error instanceof Error ? error.message : '模型调用失败')
|
||||
responseError.value = error instanceof Error && error.name === 'AbortError' ? '已停止接收,请在使用记录中确认最终状态和费用' : error instanceof Error ? error.message : '模型调用失败'
|
||||
emit('notify', responseError.value)
|
||||
} finally {
|
||||
running.value = false
|
||||
streamAbort = undefined
|
||||
historyRevision.value++
|
||||
await refreshOverview()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,7 +496,7 @@ async function createProject() {
|
||||
<section class="metric-grid">
|
||||
<article class="metric-card"><span class="icon-tile violet"><Activity :size="18" /></span><div><small>今日调用</small><strong>{{ overviewLoaded ? overview.callsToday.toLocaleString() : '--' }}</strong><em>来自网关调用记录</em></div></article>
|
||||
<article class="metric-card"><span class="icon-tile cyan"><Gauge :size="18" /></span><div><small>平均响应</small><strong>{{ overview.averageLatencyMs === undefined ? '--' : `${overview.averageLatencyMs}ms` }}</strong><em>{{ overview.averageLatencyMs === undefined ? '暂无延迟样本' : '按真实调用计算' }}</em></div></article>
|
||||
<article class="metric-card"><span class="icon-tile orange"><CircleDollarSign :size="18" /></span><div><small>可用额度</small><strong>{{ overview.availableCredit === undefined ? '--' : `¥ ${overview.availableCredit.toFixed(2)}` }}</strong><em>{{ overview.availableCredit === undefined ? '额度账本尚未接入' : '读取额度账本' }}</em></div></article>
|
||||
<article class="metric-card"><span class="icon-tile orange"><CircleDollarSign :size="18" /></span><div><small>可用额度</small><strong>{{ overview.availableCredit === undefined ? '--' : `¥ ${overview.availableCredit.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 8 })}` }}</strong><em>{{ overview.availableCredit === undefined ? '额度账本尚未接入' : '读取额度账本' }}</em></div></article>
|
||||
<article class="metric-card"><span class="icon-tile green"><CheckCircle2 :size="18" /></span><div><small>平台可用性</small><strong>{{ overview.availabilityPercent === undefined ? '--' : `${overview.availabilityPercent.toFixed(2)}%` }}</strong><em>{{ overview.availabilityPercent === undefined ? '监控数据尚未接入' : '来自可用性监控' }}</em></div></article>
|
||||
</section>
|
||||
|
||||
@@ -516,14 +530,18 @@ async function createProject() {
|
||||
<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>
|
||||
</div>
|
||||
<label class="form-label">调用模式</label>
|
||||
<div class="segment"><button v-for="mode in ['同步','流式','异步']" :key="mode" :disabled="running || mode !== activeModel.mode || mode === '流式'" :class="{ active: callMode === mode }" @click="callMode = mode as CallMode">{{ mode }}</button></div>
|
||||
<div class="segment"><button v-for="mode in ['同步','流式','异步']" :key="mode" :disabled="running || (activeModel.mode === '异步' ? mode !== '异步' : mode === '异步')" :class="{ active: callMode === mode }" @click="callMode = mode as CallMode">{{ mode }}</button></div>
|
||||
<label v-if="callMode !== '异步'" class="form-label token-limit">最大输出 Token<input v-model.number="maxOutputTokens" class="text-input" type="number" min="1" max="32768" step="1" :disabled="running" /></label>
|
||||
<small v-if="callMode !== '异步'">按分组人民币售价和实际 Token 用量扣费;调用前预留额度,结束后释放差额。</small>
|
||||
<label class="form-label prompt-label"><span>输入内容</span><small>{{ prompt.length }}/4000</small></label>
|
||||
<textarea v-model="prompt" maxlength="4000" :placeholder="callMode === '异步' ? activeModel.type === '视频' ? '例如:电影感产品展示视频,柔和运镜与自然光影' : '例如:一个低面数的木质机械鸟,游戏资产风格' : '描述你希望模型完成的任务'"></textarea>
|
||||
<div class="request-footer"><span><ShieldCheck :size="14" />{{ catalogConnected ? '通过 MOYI Key 调用真实网关' : '连接服务后才能调用' }}</span><button class="button primary" :disabled="running || !catalogConnected || !activeModel.id" @click="runModel"><Play v-if="!running" :size="16" /><span v-else class="spinner"></span>{{ running ? '提交中…' : callMode === '异步' ? activeModel.type === '视频' ? '生成视频' : '生成 3D' : '开始调用' }}</button></div>
|
||||
</article>
|
||||
<article class="panel response-panel">
|
||||
<header class="panel-header"><div><span>RESPONSE</span><h3>{{ callMode === '异步' ? '任务状态' : '模型输出' }}</h3></div><button class="icon-button" :class="{ copied: copySucceeded('response') }" :disabled="!response" :title="copySucceeded('response') ? '已复制' : '复制响应'" @click="copy(response, '响应内容', 'response')"><Check v-if="copySucceeded('response')" :size="16" /><Copy v-else :size="16" /></button></header>
|
||||
<div v-if="running" class="response-state"><span class="loading-orbit"><i></i></span><strong>{{ callMode === '异步' ? activeModel.type === '视频' ? '正在创建视频任务' : '正在创建 3D 任务' : '模型正在生成响应' }}</strong><p>请求通过模亦灵枢统一网关发送</p></div>
|
||||
<button v-if="running && callMode === '流式'" class="button secondary" @click="streamAbort?.abort()">停止接收</button>
|
||||
<details v-if="reasoningOutput"><summary>思考过程</summary><pre class="response-content">{{ reasoningOutput }}</pre></details>
|
||||
<div v-if="running && !response" class="response-state"><span class="loading-orbit"><i></i></span><strong>{{ callMode === '异步' ? activeModel.type === '视频' ? '正在创建视频任务' : '正在创建 3D 任务' : '模型正在生成响应' }}</strong><p>请求通过模亦灵枢统一网关发送</p></div>
|
||||
<div v-else-if="callMode === '异步' && activeTask" class="live-task-result">
|
||||
<div class="task-preview" :class="{ empty: !activeTask.previewUrl && !activeTask.videoUrl }"><video v-if="activeTask.videoUrl" :src="activeTask.videoUrl" controls></video><img v-else-if="activeTask.previewUrl" :src="activeTask.previewUrl" alt="异步任务预览" /><span v-else><Box :size="34" /><small>{{ activeTask.status === '已完成' ? '结果已生成' : '生成预览中' }}</small></span><em>{{ activeTask.provider === 'tripo' ? 'TRIPO' : activeTask.provider === 'seedance' ? 'SEEDANCE' : 'MOYI GATEWAY' }}</em></div>
|
||||
<div class="live-task-head"><span class="status-chip" :class="activeTask.status"><i></i>{{ activeTask.status }}</span><code>{{ activeTask.id }}</code></div>
|
||||
@@ -532,7 +550,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" class="response-result"><div><span class="status-chip success"><i></i>200 OK</span><small>MOYI unified response</small></div><p>{{ response }}</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</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>
|
||||
@@ -552,9 +570,11 @@ async function createProject() {
|
||||
|
||||
<template v-else-if="view === 'usage'">
|
||||
<section class="page-heading"><div><span>USAGE & CREDITS</span><h1>用量与额度</h1><p>查看调用消耗、额度余额和最近流水。</p></div><button class="button disabled" disabled><WalletCards :size="16" />充值暂未开放</button></section>
|
||||
<section class="credit-hero"><div><span>当前可用额度</span><strong>{{ overview.availableCredit === undefined ? '--' : `¥ ${overview.availableCredit.toFixed(2)}` }}</strong><p>{{ overview.availableCredit === undefined ? '额度账本尚未接入,当前不会展示预估金额。' : '额度由平台账本实时计算。' }}</p></div><div class="credit-circle"><span>{{ overview.availableCredit === undefined ? '--' : '已同步' }}</span><small>{{ overview.availableCredit === undefined ? '等待账本' : '账本状态' }}</small></div></section>
|
||||
<section class="metric-grid three"><article class="metric-card"><span class="icon-tile violet"><Activity :size="18" /></span><div><small>本月调用</small><strong>{{ overviewLoaded ? overview.callsThisMonth.toLocaleString() : '--' }}</strong><em>网关真实记录</em></div></article><article class="metric-card"><span class="icon-tile cyan"><BarChart3 :size="18" /></span><div><small>本月消耗</small><strong>--</strong><em>计费规则尚未接入</em></div></article><article class="metric-card"><span class="icon-tile orange"><Box :size="18" /></span><div><small>异步任务</small><strong>{{ overviewLoaded ? overview.asyncTasks : '--' }}</strong><em>{{ overview.asyncSuccessRate === undefined ? '暂无完成样本' : `成功率 ${overview.asyncSuccessRate.toFixed(1)}%` }}</em></div></article></section>
|
||||
<section class="two-column wide-left"><article class="panel chart-panel"><header class="panel-header"><div><span>USAGE TREND</span><h3>过去 7 天调用</h3></div><span class="select-button static">按调用次数</span></header><div v-if="usageSeries.length" class="bar-chart large"><div v-for="item in usageSeries" :key="item.date"><i :style="{ height: `${item.height}%` }" :title="`${item.date} · ${item.count} 次`"></i><span>{{ item.label }}</span></div></div><div v-else class="empty-state compact"><BarChart3 :size="22" /><strong>暂无调用趋势</strong><span>完成真实调用后会在这里形成统计</span></div></article><article class="panel ledger"><header class="panel-header"><div><span>CREDIT LEDGER</span><h3>最近额度流水</h3></div><Download :size="17" /></header><div v-if="overview.ledger.length"><p v-for="item in overview.ledger" :key="item.id"><span class="activity-dot violet"><CircleDollarSign :size="14" /></span><span><strong>{{ item.title }}</strong><small>{{ item.createdAt }}</small></span><b :class="item.amount >= 0 ? 'positive' : ''">{{ item.amount >= 0 ? '+' : '' }} ¥{{ item.amount.toFixed(2) }}</b></p></div><div v-else class="empty-state compact"><CircleDollarSign :size="22" /><strong>暂无额度流水</strong><span>管理员发放或计费完成后会显示记录</span></div></article></section>
|
||||
<section class="credit-hero"><div><span>当前可用额度</span><strong>{{ overview.availableCredit === undefined ? '--' : `¥ ${overview.availableCredit.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 8 })}` }}</strong><p>{{ overview.availableCredit === undefined ? '额度账本尚未接入,当前不会展示预估金额。' : '额度由平台账本实时计算。' }}</p></div><div class="credit-circle"><span>{{ overview.availableCredit === undefined ? '--' : '已同步' }}</span><small>{{ overview.availableCredit === undefined ? '等待账本' : '账本状态' }}</small></div></section>
|
||||
<p v-if="overview.reservedCredit" class="billing-note">进行中的调用已预留 ¥{{ overview.reservedCredit.toLocaleString('zh-CN', { maximumFractionDigits: 8 }) }};结束后按实际 Token 用量结算,剩余预留自动释放。</p>
|
||||
<p v-if="(overview.balance ?? 0) < 0" class="billing-note" role="alert">账户存在待补余额,请补足后继续调用。可在下方流水查看实际扣费。</p>
|
||||
<section class="metric-grid three"><article class="metric-card"><span class="icon-tile violet"><Activity :size="18" /></span><div><small>本月调用</small><strong>{{ overviewLoaded ? overview.callsThisMonth.toLocaleString() : '--' }}</strong><em>网关真实记录</em></div></article><article class="metric-card"><span class="icon-tile cyan"><BarChart3 :size="18" /></span><div><small>本月消耗</small><strong>{{ overview.costThisMonth === undefined ? '--' : `¥ ${overview.costThisMonth.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 8 })}` }}</strong><em>已入账的模型调用费用</em></div></article><article class="metric-card"><span class="icon-tile orange"><Box :size="18" /></span><div><small>异步任务</small><strong>{{ overviewLoaded ? overview.asyncTasks : '--' }}</strong><em>{{ overview.asyncSuccessRate === undefined ? '暂无完成样本' : `成功率 ${overview.asyncSuccessRate.toFixed(1)}%` }}</em></div></article></section>
|
||||
<section class="two-column wide-left"><article class="panel chart-panel"><header class="panel-header"><div><span>USAGE TREND</span><h3>过去 7 天调用</h3></div><span class="select-button static">按调用次数</span></header><div v-if="usageSeries.length" class="bar-chart large"><div v-for="item in usageSeries" :key="item.date"><i :style="{ height: `${item.height}%` }" :title="`${item.date} · ${item.count} 次`"></i><span>{{ item.label }}</span></div></div><div v-else class="empty-state compact"><BarChart3 :size="22" /><strong>暂无调用趋势</strong><span>完成真实调用后会在这里形成统计</span></div></article><article class="panel ledger"><header class="panel-header"><div><span>CREDIT LEDGER</span><h3>最近额度流水</h3></div><Download :size="17" /></header><div v-if="overview.ledger.length"><p v-for="item in overview.ledger" :key="item.id"><span class="activity-dot violet"><CircleDollarSign :size="14" /></span><span><strong>{{ item.title }}</strong><small>{{ item.createdAt }}</small></span><b :class="item.amount >= 0 ? 'positive' : ''">{{ item.amount >= 0 ? '+' : '' }} ¥{{ item.amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 8 }) }}</b></p></div><div v-else class="empty-state compact"><CircleDollarSign :size="22" /><strong>暂无额度流水</strong><span>管理员发放或计费完成后会显示记录</span></div></article></section>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
@@ -584,6 +604,10 @@ MOYI_MODEL=<model-id></code></pre></div></section><section><b>02</b><div><
|
||||
|
||||
<style scoped>
|
||||
.request-panel, .response-panel { min-width: 0; }
|
||||
.token-limit { display: grid; gap: 8px; }
|
||||
.response-result > p, .response-content { white-space: pre-wrap; overflow-wrap: anywhere; max-width: 100%; }
|
||||
.response-result .status-chip.failed { color: #b42318; background: #fee4e2; }
|
||||
.response-result p[role="alert"] { color: #b42318; }
|
||||
.playground-selectors { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin-bottom: 16px; }
|
||||
.playground-selectors label { display: grid; gap: 8px; font-size: 13px; min-width: 0; }
|
||||
.playground-selectors select { width: 100%; min-width: 0; }
|
||||
|
||||
Reference in new issue
Block a user