mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-02 01:10:23 +08:00
refactor: 前端全面替换 any 为 unknown 并统一错误处理,后端用量记录补写请求头/体
- 前端 API 层、stores、conversation 解析器、组件全面替换 any 为 unknown/具体类型 - 错误处理统一使用 parseApiError/getErrorStatus 替代 err.response?.data?.detail 模式 - 后端 handler/TaskService/UsageLifecycle/StreamTracker 链路传递 request_headers/request_body - streaming/pending 状态更新时可补写客户端和提供商的请求头及请求体 - 新增 TaskService 和 UsageService 相关测试
This commit is contained in:
@@ -392,7 +392,7 @@ async function loadAccessRestrictionOptions() {
|
||||
])
|
||||
providers.value = providersData
|
||||
globalModels.value = modelsData.models || []
|
||||
allApiFormats.value = formatsData.formats?.map((f: any) => f.value) || []
|
||||
allApiFormats.value = formatsData.formats?.map((f: { value: string }) => f.value) || []
|
||||
} catch (err) {
|
||||
log.error('加载访问限制选项失败:', err)
|
||||
}
|
||||
|
||||
@@ -60,10 +60,12 @@
|
||||
class="oauth-btn"
|
||||
@click="handleOAuthLogin(oauthProviders[0].provider_type)"
|
||||
>
|
||||
<!-- eslint-disable vue/no-v-html -->
|
||||
<span
|
||||
class="oauth-icon"
|
||||
v-html="getOAuthIcon(oauthProviders[0].provider_type)"
|
||||
/>
|
||||
<!-- eslint-enable vue/no-v-html -->
|
||||
<span>使用 {{ oauthProviders[0].display_name }} 登录</span>
|
||||
</button>
|
||||
</div>
|
||||
@@ -83,10 +85,12 @@
|
||||
:title="p.display_name"
|
||||
@click="handleOAuthLogin(p.provider_type)"
|
||||
>
|
||||
<!-- eslint-disable vue/no-v-html -->
|
||||
<span
|
||||
class="oauth-icon-lg"
|
||||
v-html="getOAuthIcon(p.provider_type)"
|
||||
/>
|
||||
<!-- eslint-enable vue/no-v-html -->
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -222,6 +222,7 @@
|
||||
import { ref, computed, watch, onUnmounted, nextTick } from 'vue'
|
||||
import { authApi } from '@/api/auth'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { Dialog } from '@/components/ui'
|
||||
import Button from '@/components/ui/button.vue'
|
||||
import Input from '@/components/ui/input.vue'
|
||||
@@ -576,12 +577,8 @@ const handleSendCode = async () => {
|
||||
} else {
|
||||
showError(response.message || '请稍后重试', '发送失败')
|
||||
}
|
||||
} catch (error: any) {
|
||||
const errorMsg = error.response?.data?.detail
|
||||
|| error.response?.data?.error?.message
|
||||
|| error.message
|
||||
|| '网络错误,请重试'
|
||||
showError(errorMsg, '发送失败')
|
||||
} catch (error: unknown) {
|
||||
showError(parseApiError(error, '网络错误,请重试'), '发送失败')
|
||||
} finally {
|
||||
isSendingCode.value = false
|
||||
}
|
||||
@@ -609,13 +606,9 @@ const handleCodeComplete = async (code: string) => {
|
||||
// Clear the code input
|
||||
clearCodeInputs()
|
||||
}
|
||||
} catch (error: any) {
|
||||
} catch (error: unknown) {
|
||||
verificationError.value = true
|
||||
const errorMsg = error.response?.data?.detail
|
||||
|| error.response?.data?.error?.message
|
||||
|| error.message
|
||||
|| '验证码错误,请重试'
|
||||
showError(errorMsg, '验证失败')
|
||||
showError(parseApiError(error, '验证码错误,请重试'), '验证失败')
|
||||
// Clear the code input
|
||||
clearCodeInputs()
|
||||
} finally {
|
||||
@@ -662,12 +655,8 @@ const handleSubmit = async () => {
|
||||
|
||||
emit('success')
|
||||
isOpen.value = false
|
||||
} catch (error: any) {
|
||||
const errorMsg = error.response?.data?.detail
|
||||
|| error.response?.data?.error?.message
|
||||
|| error.message
|
||||
|| '注册失败,请重试'
|
||||
showError(errorMsg, '注册失败')
|
||||
} catch (error: unknown) {
|
||||
showError(parseApiError(error, '注册失败,请重试'), '注册失败')
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
|
||||
@@ -66,21 +66,21 @@
|
||||
class="bg-muted/30"
|
||||
>
|
||||
<div
|
||||
v-for="model in group.models"
|
||||
:key="model.modelId"
|
||||
v-for="item in group.models"
|
||||
:key="item.modelId"
|
||||
class="flex flex-col gap-0.5 pl-7 pr-2.5 py-1.5 cursor-pointer text-xs border-t"
|
||||
:class="selectedModel?.modelId === model.modelId && selectedModel?.providerId === model.providerId
|
||||
:class="selectedModel?.modelId === item.modelId && selectedModel?.providerId === item.providerId
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'hover:bg-muted'"
|
||||
@click="selectModel(model)"
|
||||
@click="selectModel(item)"
|
||||
>
|
||||
<span class="truncate font-medium">{{ model.modelName }}</span>
|
||||
<span class="truncate font-medium">{{ item.modelName }}</span>
|
||||
<span
|
||||
class="truncate text-[10px]"
|
||||
:class="selectedModel?.modelId === model.modelId && selectedModel?.providerId === model.providerId
|
||||
:class="selectedModel?.modelId === item.modelId && selectedModel?.providerId === item.providerId
|
||||
? 'text-primary-foreground/70'
|
||||
: 'text-muted-foreground'"
|
||||
>{{ model.modelId }}</span>
|
||||
>{{ item.modelId }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -363,6 +363,7 @@ import { useToast } from '@/composables/useToast'
|
||||
import { useFormDialog } from '@/composables/useFormDialog'
|
||||
import { parseNumberInput, sortResolutionEntries } from '@/utils/form'
|
||||
import { log } from '@/utils/logger'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import TieredPricingEditor from './TieredPricingEditor.vue'
|
||||
import {
|
||||
getModelsDevList,
|
||||
@@ -436,7 +437,7 @@ const groupedModels = computed(() => {
|
||||
models: []
|
||||
})
|
||||
}
|
||||
groups.get(model.providerId)!.models.push(model)
|
||||
groups.get(model.providerId)?.models.push(model)
|
||||
}
|
||||
|
||||
// 转换为数组并排序
|
||||
@@ -506,7 +507,7 @@ interface FormData {
|
||||
display_name: string
|
||||
default_price_per_request?: number
|
||||
supported_capabilities?: string[]
|
||||
config?: Record<string, any>
|
||||
config?: Record<string, unknown>
|
||||
is_active?: boolean
|
||||
}
|
||||
|
||||
@@ -524,7 +525,7 @@ const form = ref<FormData>(defaultForm())
|
||||
const KEEP_FALSE_CONFIG_KEYS = new Set(['streaming'])
|
||||
|
||||
// 设置 config 字段
|
||||
function setConfigField(key: string, value: any) {
|
||||
function setConfigField(key: string, value: unknown) {
|
||||
if (!form.value.config) {
|
||||
form.value.config = {}
|
||||
}
|
||||
@@ -535,41 +536,41 @@ function setConfigField(key: string, value: any) {
|
||||
}
|
||||
}
|
||||
|
||||
function getNested(obj: any, path: string): any {
|
||||
function getNested(obj: unknown, path: string): unknown {
|
||||
if (!obj || typeof obj !== 'object') return undefined
|
||||
const parts = path.split('.').filter(Boolean)
|
||||
let cur: any = obj
|
||||
let cur = obj as Record<string, unknown>
|
||||
for (const p of parts) {
|
||||
if (!cur || typeof cur !== 'object') return undefined
|
||||
cur = cur[p]
|
||||
cur = cur[p] as Record<string, unknown>
|
||||
}
|
||||
return cur
|
||||
}
|
||||
|
||||
function setNested(obj: any, path: string, value: any) {
|
||||
function setNested(obj: unknown, path: string, value: unknown) {
|
||||
if (!obj || typeof obj !== 'object') return
|
||||
const parts = path.split('.').filter(Boolean)
|
||||
if (parts.length === 0) return
|
||||
let cur: any = obj
|
||||
let cur = obj as Record<string, unknown>
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
const p = parts[i]
|
||||
if (!cur[p] || typeof cur[p] !== 'object') {
|
||||
cur[p] = {}
|
||||
}
|
||||
cur = cur[p]
|
||||
cur = cur[p] as Record<string, unknown>
|
||||
}
|
||||
cur[parts[parts.length - 1]] = value
|
||||
}
|
||||
|
||||
function deleteNested(obj: any, path: string) {
|
||||
function deleteNested(obj: unknown, path: string) {
|
||||
if (!obj || typeof obj !== 'object') return
|
||||
const parts = path.split('.').filter(Boolean)
|
||||
if (parts.length === 0) return
|
||||
let cur: any = obj
|
||||
let cur = obj as Record<string, unknown>
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
const p = parts[i]
|
||||
if (!cur[p] || typeof cur[p] !== 'object') return
|
||||
cur = cur[p]
|
||||
cur = cur[p] as Record<string, unknown>
|
||||
}
|
||||
delete cur[parts[parts.length - 1]]
|
||||
}
|
||||
@@ -577,9 +578,9 @@ function deleteNested(obj: any, path: string) {
|
||||
function pruneEmptyBillingConfig() {
|
||||
const cfg = form.value.config
|
||||
if (!cfg || typeof cfg !== 'object') return
|
||||
const billing = cfg.billing
|
||||
const billing = cfg.billing as Record<string, unknown> | undefined
|
||||
if (!billing || typeof billing !== 'object') return
|
||||
const video = billing.video
|
||||
const video = billing.video as Record<string, unknown> | undefined
|
||||
if (video && typeof video === 'object' && Object.keys(video).length === 0) {
|
||||
delete billing.video
|
||||
}
|
||||
@@ -611,7 +612,7 @@ function loadVideoPricingFromConfig() {
|
||||
const raw = getNested(cfg, 'billing.video.price_per_second_by_resolution')
|
||||
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
||||
// 按分辨率从低到高排序
|
||||
const sortedEntries = sortResolutionEntries(Object.entries(raw))
|
||||
const sortedEntries = sortResolutionEntries(Object.entries(raw as Record<string, unknown>))
|
||||
videoResolutionPrices.value = sortedEntries.map(([k, v]) => ({
|
||||
resolution: String(k),
|
||||
price_per_second: typeof v === 'number' ? v : undefined,
|
||||
@@ -722,7 +723,7 @@ function selectModel(model: ModelsDevModelItem) {
|
||||
form.value.display_name = model.modelName
|
||||
|
||||
// 构建 config
|
||||
const config: Record<string, any> = {
|
||||
const config: Record<string, unknown> = {
|
||||
streaming: true,
|
||||
}
|
||||
if (model.supportsVision) config.vision = true
|
||||
@@ -848,8 +849,8 @@ async function handleSubmit() {
|
||||
success('模型更新成功')
|
||||
} else {
|
||||
const createData: GlobalModelCreate = {
|
||||
name: form.value.name!,
|
||||
display_name: form.value.display_name!,
|
||||
name: form.value.name ?? '',
|
||||
display_name: form.value.display_name ?? '',
|
||||
config: cleanConfig,
|
||||
default_price_per_request: form.value.default_price_per_request ?? undefined,
|
||||
default_tiered_pricing: finalTieredPricing,
|
||||
@@ -861,8 +862,8 @@ async function handleSubmit() {
|
||||
}
|
||||
emit('update:open', false)
|
||||
emit('success')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || err.message, isEditMode.value ? '更新失败' : '创建失败')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, isEditMode.value ? '更新失败' : '创建失败'), isEditMode.value ? '更新失败' : '创建失败')
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
|
||||
@@ -469,6 +469,7 @@ import TableCell from '@/components/ui/table-cell.vue'
|
||||
import RoutingTab from './RoutingTab.vue'
|
||||
import ModelMappingsTab from './ModelMappingsTab.vue'
|
||||
import { sortResolutionEntries } from '@/utils/form'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { getGlobalModelRoutingPreview } from '@/api/global-models'
|
||||
|
||||
// 使用外部类型定义
|
||||
@@ -479,15 +480,16 @@ import type { RoutingProviderInfo } from '@/api/global-models'
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
hasBlockingDialogOpen: false,
|
||||
capabilities: () => [],
|
||||
})
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
'editModel': [model: GlobalModelResponse]
|
||||
'toggleModelStatus': [model: GlobalModelResponse]
|
||||
'addProvider': []
|
||||
'editProvider': [provider: any]
|
||||
'deleteProvider': [provider: any]
|
||||
'toggleProviderStatus': [provider: any]
|
||||
'editProvider': [provider: Record<string, unknown>]
|
||||
'deleteProvider': [provider: Record<string, unknown>]
|
||||
'toggleProviderStatus': [provider: Record<string, unknown>]
|
||||
'refreshModel': []
|
||||
'linkProvider': [providerId: string]
|
||||
'linkProviders': [providerIds: string[]]
|
||||
@@ -520,8 +522,8 @@ async function loadRoutingData() {
|
||||
|
||||
try {
|
||||
routingData.value = await getGlobalModelRoutingPreview(props.model.id)
|
||||
} catch (err: any) {
|
||||
routingError.value = err.response?.data?.detail || '加载失败'
|
||||
} catch (err: unknown) {
|
||||
routingError.value = parseApiError(err, '加载失败')
|
||||
} finally {
|
||||
routingLoading.value = false
|
||||
}
|
||||
|
||||
@@ -606,6 +606,7 @@ import {
|
||||
import { API_FORMAT_ORDER } from '@/api/endpoints/types'
|
||||
import { formatApiFormat } from '@/api/endpoints/types/api-format'
|
||||
import { recoverKeyHealth } from '@/api/endpoints/health'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { useCountdownTimer, getProbeCountdown } from '@/composables/useCountdownTimer'
|
||||
import { MAX_MODEL_NAME_LENGTH, createLRURegexCache, getCompiledModelMappingRegex } from '@/features/models/utils/model-mapping-regex'
|
||||
@@ -696,7 +697,8 @@ const apiFormatGroups = computed<ApiFormatGroup[]>(() => {
|
||||
formatMap.set(format, { providers: [], allKeys: [] })
|
||||
}
|
||||
|
||||
const data = formatMap.get(format)!
|
||||
const data = formatMap.get(format)
|
||||
if (!data) continue
|
||||
|
||||
// 添加 provider entry
|
||||
data.providers.push({
|
||||
@@ -739,7 +741,7 @@ const apiFormatGroups = computed<ApiFormatGroup[]>(() => {
|
||||
if (!keyGroupMap.has(priority)) {
|
||||
keyGroupMap.set(priority, [])
|
||||
}
|
||||
keyGroupMap.get(priority)!.push(keyEntry)
|
||||
keyGroupMap.get(priority)?.push(keyEntry)
|
||||
}
|
||||
|
||||
// 转换为分组数组并排序
|
||||
@@ -847,8 +849,8 @@ async function loadRoutingData() {
|
||||
|
||||
internalRoutingData.value = data
|
||||
compiledGlobalModelMappingRegexes.value = compiled
|
||||
} catch (err: any) {
|
||||
internalError.value = err.response?.data?.detail || '加载失败'
|
||||
} catch (err: unknown) {
|
||||
internalError.value = parseApiError(err, '加载失败')
|
||||
} finally {
|
||||
internalLoading.value = false
|
||||
}
|
||||
@@ -977,7 +979,7 @@ function getKeyPriorityGroups(keys: RoutingKeyInfo[]): KeyPriorityGroup[] {
|
||||
keys: []
|
||||
})
|
||||
}
|
||||
groups.get(priority)!.keys.push(key)
|
||||
groups.get(priority)?.keys.push(key)
|
||||
}
|
||||
|
||||
return Array.from(groups.values()).sort((a, b) => {
|
||||
@@ -1121,8 +1123,8 @@ async function handleRecoverKey(keyId: string, apiFormat: string) {
|
||||
// 通知父组件刷新数据
|
||||
emit('refresh')
|
||||
showSuccess(result.message || 'Key 已恢复')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || 'Key 恢复失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, 'Key 恢复失败'), '错误')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -48,10 +48,12 @@ export function createLRURegexCache(maxSize: number): LRURegexCache {
|
||||
return {
|
||||
get: (key: string) => {
|
||||
if (!cache.has(key)) return undefined
|
||||
const value = cache.get(key)!
|
||||
cache.delete(key)
|
||||
cache.set(key, value)
|
||||
return value
|
||||
const value = cache.get(key)
|
||||
if (value !== undefined) {
|
||||
cache.delete(key)
|
||||
cache.set(key, value)
|
||||
}
|
||||
return value ?? null
|
||||
},
|
||||
set: (key: string, value: RegExp | null) => {
|
||||
if (cache.has(key)) {
|
||||
|
||||
@@ -190,14 +190,14 @@ function propertyToField(
|
||||
export function buildRequestFromSchema(
|
||||
schema: CredentialsSchema,
|
||||
architectureId: string,
|
||||
formData: Record<string, any>,
|
||||
formData: Record<string, unknown>,
|
||||
providerWebsite?: string,
|
||||
): SaveConfigRequest {
|
||||
const baseUrl = formData.base_url || providerWebsite || schema['x-default-base-url'] || ''
|
||||
const baseUrl = (formData.base_url as string) || providerWebsite || schema['x-default-base-url'] || ''
|
||||
const authType = schema['x-auth-type'] || 'api_key'
|
||||
|
||||
// 构建 credentials:除 base_url 和代理字段外的所有 schema 属性
|
||||
const credentials: Record<string, any> = {}
|
||||
const credentials: Record<string, unknown> = {}
|
||||
for (const key of Object.keys(schema.properties)) {
|
||||
if (key === 'base_url') continue
|
||||
const v = formData[key]
|
||||
@@ -227,18 +227,21 @@ export function buildRequestFromSchema(
|
||||
*/
|
||||
export function parseConfigFromSchema(
|
||||
schema: CredentialsSchema,
|
||||
config: any,
|
||||
): Record<string, any> {
|
||||
const proxyData = parseProxyConfig(config?.connector?.config)
|
||||
const result: Record<string, any> = {
|
||||
base_url: config?.base_url || '',
|
||||
config: Record<string, unknown> | null | undefined,
|
||||
): Record<string, unknown> {
|
||||
const connector = config?.connector as Record<string, unknown> | undefined
|
||||
const connectorConfig = connector?.config as Record<string, unknown> | undefined
|
||||
const proxyData = parseProxyConfig(connectorConfig)
|
||||
const result: Record<string, unknown> = {
|
||||
base_url: (config?.base_url as string) || '',
|
||||
...proxyData,
|
||||
}
|
||||
|
||||
// 从 credentials 中提取各 schema 属性
|
||||
const credentials = connector?.credentials as Record<string, unknown> | undefined
|
||||
for (const key of Object.keys(schema.properties)) {
|
||||
if (key === 'base_url') continue
|
||||
result[key] = config?.connector?.credentials?.[key] || ''
|
||||
result[key] = credentials?.[key] || ''
|
||||
}
|
||||
|
||||
return result
|
||||
@@ -246,13 +249,18 @@ export function parseConfigFromSchema(
|
||||
|
||||
// ==================== 验证 ====================
|
||||
|
||||
/** 安全获取字符串值并 trim(表单字段值可能为 string 或其他类型) */
|
||||
function trimValue(v: unknown): string {
|
||||
return typeof v === 'string' ? v.trim() : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 schema 验证表单数据
|
||||
* @returns 错误消息,无错误返回 null
|
||||
*/
|
||||
export function validateFromSchema(
|
||||
schema: CredentialsSchema,
|
||||
formData: Record<string, any>,
|
||||
formData: Record<string, unknown>,
|
||||
): string | null {
|
||||
const validations = schema['x-validation']
|
||||
if (!validations) return null
|
||||
@@ -262,7 +270,7 @@ export function validateFromSchema(
|
||||
case 'required': {
|
||||
if (!rule.fields) break
|
||||
for (const field of rule.fields) {
|
||||
if (!formData[field]?.trim?.()) {
|
||||
if (!trimValue(formData[field])) {
|
||||
return rule.message
|
||||
}
|
||||
}
|
||||
@@ -270,7 +278,7 @@ export function validateFromSchema(
|
||||
}
|
||||
case 'any_required': {
|
||||
if (!rule.fields) break
|
||||
const hasAny = rule.fields.some((f) => !!formData[f]?.trim?.())
|
||||
const hasAny = rule.fields.some((f) => !!trimValue(formData[f]))
|
||||
if (!hasAny) {
|
||||
return rule.message
|
||||
}
|
||||
@@ -282,12 +290,12 @@ export function validateFromSchema(
|
||||
const thenFields = rule.then
|
||||
if (!ifField || !thenFields) break
|
||||
|
||||
const ifHasValue = !!formData[ifField]?.trim?.()
|
||||
const unlessHasValue = unlessField ? !!formData[unlessField]?.trim?.() : false
|
||||
const ifHasValue = !!trimValue(formData[ifField])
|
||||
const unlessHasValue = unlessField ? !!trimValue(formData[unlessField]) : false
|
||||
|
||||
if (ifHasValue && !unlessHasValue) {
|
||||
for (const field of thenFields) {
|
||||
if (!formData[field]?.trim?.()) {
|
||||
if (!trimValue(formData[field])) {
|
||||
return rule.message
|
||||
}
|
||||
}
|
||||
@@ -331,7 +339,7 @@ export function formatQuotaFromSchema(
|
||||
*/
|
||||
export function formatBalanceExtraFromSchema(
|
||||
schema: CredentialsSchema,
|
||||
extra: Record<string, any>,
|
||||
extra: Record<string, unknown>,
|
||||
): BalanceExtraItem[] {
|
||||
const formats = schema['x-balance-extra-format']
|
||||
if (!formats) return []
|
||||
@@ -367,31 +375,35 @@ export function formatBalanceExtraFromSchema(
|
||||
}
|
||||
|
||||
function formatWindowLimitItem(
|
||||
extra: Record<string, any>,
|
||||
extra: Record<string, unknown>,
|
||||
fmt: BalanceExtraFormat,
|
||||
): BalanceExtraItem | null {
|
||||
if (!fmt.source) return null
|
||||
const limit = extra[fmt.source]
|
||||
if (!limit || limit.remaining === undefined || limit.limit === undefined || limit.limit === 0) {
|
||||
const rawLimit = extra[fmt.source]
|
||||
if (!rawLimit || typeof rawLimit !== 'object') return null
|
||||
const limit = rawLimit as Record<string, unknown>
|
||||
if (limit.remaining === undefined || limit.limit === undefined || limit.limit === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const percent = Math.round((limit.remaining / limit.limit) * 100)
|
||||
const limitVal = Number(limit.limit)
|
||||
const remainingVal = Number(limit.remaining)
|
||||
const percent = Math.round((remainingVal / limitVal) * 100)
|
||||
const divisor = fmt.unit_divisor || 1
|
||||
const remaining = (limit.remaining / divisor).toFixed(2)
|
||||
const total = (limit.limit / divisor).toFixed(2)
|
||||
const remaining = (remainingVal / divisor).toFixed(2)
|
||||
const total = (limitVal / divisor).toFixed(2)
|
||||
|
||||
return {
|
||||
label: fmt.label,
|
||||
value: `${percent}%`,
|
||||
percent,
|
||||
resetsAt: limit.resets_at,
|
||||
resetsAt: typeof limit.resets_at === 'number' ? limit.resets_at : undefined,
|
||||
tooltip: `$${remaining} / $${total}`,
|
||||
}
|
||||
}
|
||||
|
||||
function formatDailyQuotaItem(
|
||||
extra: Record<string, any>,
|
||||
extra: Record<string, unknown>,
|
||||
fmt: BalanceExtraFormat,
|
||||
): BalanceExtraItem | null {
|
||||
const limitKey = fmt.source_limit || 'daily_quota_limit'
|
||||
@@ -410,7 +422,7 @@ function formatDailyQuotaItem(
|
||||
const startDateKey = fmt.source_start_date
|
||||
if (startDateKey && extra[startDateKey]) {
|
||||
try {
|
||||
const startDate = new Date(extra[startDateKey])
|
||||
const startDate = new Date(String(extra[startDateKey]))
|
||||
const now = new Date()
|
||||
const todayReset = new Date(now)
|
||||
todayReset.setHours(startDate.getHours(), startDate.getMinutes(), startDate.getSeconds(), 0)
|
||||
@@ -432,14 +444,14 @@ function formatDailyQuotaItem(
|
||||
}
|
||||
|
||||
function formatMonthlyExpiryItem(
|
||||
extra: Record<string, any>,
|
||||
extra: Record<string, unknown>,
|
||||
fmt: BalanceExtraFormat,
|
||||
): BalanceExtraItem | null {
|
||||
const endDateKey = fmt.source_end_date || 'effective_end_date'
|
||||
if (!extra[endDateKey]) return null
|
||||
|
||||
try {
|
||||
const endDate = new Date(extra[endDateKey])
|
||||
const endDate = new Date(String(extra[endDateKey]))
|
||||
const now = new Date()
|
||||
const daysLeft = Math.ceil((endDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
|
||||
const resetsAt = Math.floor(endDate.getTime() / 1000)
|
||||
@@ -457,27 +469,27 @@ function formatMonthlyExpiryItem(
|
||||
}
|
||||
|
||||
function formatWeeklySpentItem(
|
||||
extra: Record<string, any>,
|
||||
extra: Record<string, unknown>,
|
||||
fmt: BalanceExtraFormat,
|
||||
): BalanceExtraItem | null {
|
||||
const limitKey = fmt.source_limit || 'weekly_limit'
|
||||
const spentKey = fmt.source_spent || 'weekly_spent'
|
||||
const resetsAtKey = fmt.source_resets_at || 'weekly_resets_at'
|
||||
|
||||
const limit = extra[limitKey]
|
||||
const spent = extra[spentKey]
|
||||
const limitNum = Number(extra[limitKey])
|
||||
const spentNum = Number(extra[spentKey])
|
||||
|
||||
if (limit === undefined || limit <= 0 || spent === undefined) return null
|
||||
if (extra[limitKey] === undefined || limitNum <= 0 || extra[spentKey] === undefined) return null
|
||||
|
||||
const remaining = Math.max(0, limit - spent)
|
||||
const percent = Math.round((remaining / limit) * 100)
|
||||
const remaining = Math.max(0, limitNum - spentNum)
|
||||
const percent = Math.round((remaining / limitNum) * 100)
|
||||
|
||||
return {
|
||||
label: fmt.label,
|
||||
value: `${percent}%`,
|
||||
percent,
|
||||
resetsAt: extra[resetsAtKey],
|
||||
tooltip: `$${remaining.toFixed(2)} / $${(limit as number).toFixed(2)}`,
|
||||
resetsAt: typeof extra[resetsAtKey] === 'number' ? extra[resetsAtKey] : undefined,
|
||||
tooltip: `$${remaining.toFixed(2)} / $${limitNum.toFixed(2)}`,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -489,8 +501,8 @@ function formatWeeklySpentItem(
|
||||
export function handleSchemaFieldChange(
|
||||
schema: CredentialsSchema,
|
||||
fieldKey: string,
|
||||
value: any,
|
||||
formData: Record<string, any>,
|
||||
value: unknown,
|
||||
formData: Record<string, unknown>,
|
||||
): void {
|
||||
const hooks = schema['x-field-hooks']
|
||||
if (!hooks) return
|
||||
@@ -499,9 +511,9 @@ export function handleSchemaFieldChange(
|
||||
if (!hook) return
|
||||
|
||||
// 目标字段为空时才填充
|
||||
if (formData[hook.target]?.trim?.()) return
|
||||
if (trimValue(formData[hook.target])) return
|
||||
|
||||
const result = executeFieldHook(hook.action, value)
|
||||
const result = executeFieldHook(hook.action, typeof value === 'string' ? value : String(value ?? ''))
|
||||
if (result) {
|
||||
formData[hook.target] = result
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ export const PROXY_FIELD_GROUP: AuthTemplateFieldGroup = {
|
||||
* @param formData 表单数据
|
||||
* @returns 代理配置对象,展开到 connector.config 中
|
||||
*/
|
||||
export function buildProxyConfig(formData: Record<string, any>): { proxy_node_id?: string } {
|
||||
export function buildProxyConfig(formData: Record<string, unknown>): { proxy_node_id?: string } {
|
||||
if (!formData.proxy_enabled || !formData.proxy_node_id) {
|
||||
return {}
|
||||
}
|
||||
@@ -114,7 +114,7 @@ export function buildProxyConfig(formData: Record<string, any>): { proxy_node_id
|
||||
* @param config connector.config 对象
|
||||
* @returns 表单数据
|
||||
*/
|
||||
export function parseProxyConfig(config: any): Record<string, any> {
|
||||
export function parseProxyConfig(config: Record<string, unknown> | null | undefined): Record<string, unknown> {
|
||||
// 代理节点模式
|
||||
if (config?.proxy_node_id) {
|
||||
return {
|
||||
|
||||
@@ -113,10 +113,11 @@ import {
|
||||
import Button from '@/components/ui/button.vue'
|
||||
import { testModel } from '@/api/endpoints/providers'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
metadata: any
|
||||
metadata: Record<string, unknown> | null
|
||||
keyName: string
|
||||
providerId?: string
|
||||
keyId?: string
|
||||
@@ -138,17 +139,19 @@ const { error: showError, success: showSuccess } = useToast()
|
||||
const testingModel = ref<string | null>(null)
|
||||
|
||||
const items = computed<QuotaItem[]>(() => {
|
||||
const quotaByModel = props.metadata?.antigravity?.quota_by_model
|
||||
const antigravity = props.metadata?.antigravity
|
||||
if (!antigravity || typeof antigravity !== 'object') return []
|
||||
const quotaByModel = (antigravity as Record<string, unknown>).quota_by_model
|
||||
if (!quotaByModel || typeof quotaByModel !== 'object') return []
|
||||
|
||||
const result: QuotaItem[] = []
|
||||
for (const [model, rawInfo] of Object.entries(quotaByModel)) {
|
||||
for (const [model, rawInfo] of Object.entries(quotaByModel as Record<string, unknown>)) {
|
||||
if (!model) continue
|
||||
const info: any = rawInfo || {}
|
||||
const info = (rawInfo || {}) as Record<string, unknown>
|
||||
|
||||
let usedPercent = Number(info.used_percent)
|
||||
let usedPercent = Number(info['used_percent'])
|
||||
if (!Number.isFinite(usedPercent)) {
|
||||
const remainingFraction = Number(info.remaining_fraction)
|
||||
const remainingFraction = Number(info['remaining_fraction'])
|
||||
if (Number.isFinite(remainingFraction)) {
|
||||
usedPercent = (1 - remainingFraction) * 100
|
||||
} else {
|
||||
@@ -162,8 +165,9 @@ const items = computed<QuotaItem[]>(() => {
|
||||
const remainingPercent = Math.max(100 - usedPercent, 0)
|
||||
|
||||
let resetSeconds: number | null = null
|
||||
if (typeof info.reset_time === 'string' && info.reset_time.trim()) {
|
||||
const ts = Date.parse(info.reset_time.trim())
|
||||
const resetTime = info['reset_time']
|
||||
if (typeof resetTime === 'string' && resetTime.trim()) {
|
||||
const ts = Date.parse(resetTime.trim())
|
||||
if (!Number.isNaN(ts)) {
|
||||
const diff = Math.floor((ts - Date.now()) / 1000)
|
||||
resetSeconds = diff > 0 ? diff : 0
|
||||
@@ -203,9 +207,8 @@ async function handleTestModel(modelName: string) {
|
||||
} else {
|
||||
showError(`模型测试失败: ${result.error || '未知错误'}`)
|
||||
}
|
||||
} catch (err: any) {
|
||||
const errorMsg = err?.response?.data?.detail || err?.message || '测试请求失败'
|
||||
showError(`模型测试失败: ${errorMsg}`)
|
||||
} catch (err: unknown) {
|
||||
showError(`模型测试失败: ${parseApiError(err, '测试请求失败')}`)
|
||||
} finally {
|
||||
testingModel.value = null
|
||||
}
|
||||
|
||||
@@ -524,7 +524,7 @@ async function handleSave() {
|
||||
try {
|
||||
await deleteModel(props.providerId, existingModel.id)
|
||||
totalSuccess++
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
allErrors.push(parseApiError(err, '移除失败'))
|
||||
}
|
||||
}
|
||||
@@ -541,7 +541,7 @@ async function handleSave() {
|
||||
try {
|
||||
await deleteModel(props.providerId, existingModel.id)
|
||||
totalSuccess++
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
allErrors.push(parseApiError(err, '移除失败'))
|
||||
}
|
||||
}
|
||||
@@ -556,7 +556,7 @@ async function handleSave() {
|
||||
if (result.errors.length > 0) {
|
||||
allErrors.push(...result.errors.map(e => e.error))
|
||||
}
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
allErrors.push(parseApiError(err, '批量添加全局模型失败'))
|
||||
}
|
||||
}
|
||||
@@ -570,7 +570,7 @@ async function handleSave() {
|
||||
if (result.errors.length > 0) {
|
||||
allErrors.push(...result.errors.map(e => e.error))
|
||||
}
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
allErrors.push(parseApiError(err, '导入上游模型失败'))
|
||||
}
|
||||
}
|
||||
@@ -585,7 +585,7 @@ async function handleSave() {
|
||||
|
||||
emit('changed')
|
||||
emit('update:open', false)
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '保存失败'), '错误')
|
||||
// 即使出错,如果已执行过操作,也通知父组件刷新数据
|
||||
if (hasAnyOperation) {
|
||||
@@ -650,7 +650,7 @@ async function loadGlobalModels() {
|
||||
loadingGlobalModels.value = true
|
||||
const response = await getGlobalModels({ limit: 1000 })
|
||||
allGlobalModels.value = response.models
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '加载全局模型失败'), '错误')
|
||||
} finally {
|
||||
loadingGlobalModels.value = false
|
||||
@@ -661,7 +661,7 @@ async function loadGlobalModels() {
|
||||
async function loadExistingModels() {
|
||||
try {
|
||||
existingModels.value = await getProviderModels(props.providerId)
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '加载已关联模型失败'), '错误')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -783,6 +783,7 @@ import {
|
||||
} from '@/components/ui'
|
||||
import { Settings, Trash2, Check, X, Power, ChevronRight, Plus, Shuffle, RotateCcw, Radio, CheckCircle, Save, Filter, HelpCircle } from 'lucide-vue-next'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { log } from '@/utils/logger'
|
||||
import AlertDialog from '@/components/common/AlertDialog.vue'
|
||||
import {
|
||||
@@ -1000,8 +1001,7 @@ function prepareValueForJsonParse(raw: string): string {
|
||||
}
|
||||
|
||||
// 递归还原: 将 sentinel 字符串还原为 {{$original}}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function restoreOriginalPlaceholder(value: any): any {
|
||||
function restoreOriginalPlaceholder(value: unknown): unknown {
|
||||
if (typeof value === 'string') {
|
||||
if (value === ORIGINAL_SENTINEL) return ORIGINAL_PLACEHOLDER
|
||||
if (value.includes(ORIGINAL_SENTINEL)) {
|
||||
@@ -1011,8 +1011,8 @@ function restoreOriginalPlaceholder(value: any): any {
|
||||
}
|
||||
if (Array.isArray(value)) return value.map(restoreOriginalPlaceholder)
|
||||
if (value !== null && typeof value === 'object') {
|
||||
const result: Record<string, any> = {}
|
||||
for (const [k, v] of Object.entries(value)) result[k] = restoreOriginalPlaceholder(v)
|
||||
const result: Record<string, unknown> = {}
|
||||
for (const [k, v] of Object.entries(value as Record<string, unknown>)) result[k] = restoreOriginalPlaceholder(v)
|
||||
return result
|
||||
}
|
||||
return value
|
||||
@@ -1045,7 +1045,7 @@ function parseBodyRulePathParts(path: string): string[] | null {
|
||||
return parts
|
||||
}
|
||||
|
||||
function initBodyRuleSetValueForEditor(value: any): { value: string } {
|
||||
function initBodyRuleSetValueForEditor(value: unknown): { value: string } {
|
||||
if (value === undefined) return { value: '' }
|
||||
|
||||
// 所有值都用 JSON 格式回显
|
||||
@@ -1110,7 +1110,7 @@ function isCodexUrl(baseUrl: string): boolean {
|
||||
// 读取端点的上游流式策略(endpoint.config.upstream_stream_policy)
|
||||
function getEndpointUpstreamStreamPolicy(endpoint: ProviderEndpoint): string {
|
||||
const cfg = endpoint.config || {}
|
||||
const raw = (cfg.upstream_stream_policy ?? cfg.upstreamStreamPolicy ?? cfg.upstream_stream) as any
|
||||
const raw = (cfg.upstream_stream_policy ?? cfg.upstreamStreamPolicy ?? cfg.upstream_stream) as unknown
|
||||
if (raw === null || raw === undefined) return 'auto'
|
||||
if (typeof raw === 'boolean') return raw ? 'force_stream' : 'force_non_stream'
|
||||
const s = String(raw).trim().toLowerCase()
|
||||
@@ -1509,7 +1509,7 @@ function validateBodySetValue(rule: EditableBodyRule): string | null {
|
||||
if (!raw) return '值不能为空'
|
||||
try {
|
||||
JSON.parse(prepareValueForJsonParse(raw))
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
return `JSON 格式错误:${msg}`
|
||||
}
|
||||
@@ -1559,7 +1559,7 @@ function getRegexPatternValidationTip(rule: EditableBodyRule): string {
|
||||
new RegExp(rule.pattern.trim())
|
||||
// 正则有效但 flags 无效
|
||||
return '无效的 flags(仅允许 i/m/s)'
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
return err instanceof Error ? err.message : String(err)
|
||||
}
|
||||
}
|
||||
@@ -1576,7 +1576,7 @@ function getBodySetValueValidationTip(rule: EditableBodyRule): string {
|
||||
try {
|
||||
JSON.parse(prepareValueForJsonParse(rule.value.trim()))
|
||||
return ''
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
return err instanceof Error ? err.message : String(err)
|
||||
}
|
||||
}
|
||||
@@ -1729,7 +1729,7 @@ function rulesToBodyRules(rules: EditableBodyRule[]): BodyRule[] | null {
|
||||
return { path: rule.conditionPath.trim(), op }
|
||||
}
|
||||
const raw = rule.conditionValue.trim()
|
||||
let val: any = raw
|
||||
let val: unknown = raw
|
||||
try { val = JSON.parse(raw) } catch { /* 保留原字符串 */ }
|
||||
return { path: rule.conditionPath.trim(), op, value: val }
|
||||
}
|
||||
@@ -1737,7 +1737,7 @@ function rulesToBodyRules(rules: EditableBodyRule[]): BodyRule[] | null {
|
||||
for (const rule of rules) {
|
||||
const condition = buildCondition(rule)
|
||||
if (rule.action === 'set' && rule.path.trim()) {
|
||||
let value: any = rule.value
|
||||
let value: unknown = rule.value
|
||||
try { value = restoreOriginalPlaceholder(JSON.parse(prepareValueForJsonParse(rule.value.trim()))) } catch { value = rule.value }
|
||||
result.push({ action: 'set', path: rule.path.trim(), value, ...(condition ? { condition } : {}) })
|
||||
} else if (rule.action === 'drop' && rule.path.trim()) {
|
||||
@@ -1745,7 +1745,7 @@ function rulesToBodyRules(rules: EditableBodyRule[]): BodyRule[] | null {
|
||||
} else if (rule.action === 'rename' && rule.from.trim() && rule.to.trim()) {
|
||||
result.push({ action: 'rename', from: rule.from.trim(), to: rule.to.trim(), ...(condition ? { condition } : {}) })
|
||||
} else if ((rule.action === 'insert' || rule.action === 'append') && rule.path.trim()) {
|
||||
let value: any = rule.value
|
||||
let value: unknown = rule.value
|
||||
try { value = restoreOriginalPlaceholder(JSON.parse(prepareValueForJsonParse(rule.value.trim()))) } catch { value = rule.value }
|
||||
const indexStr = rule.index.trim()
|
||||
if (indexStr === '') {
|
||||
@@ -1804,7 +1804,7 @@ function getBodyValidationErrorForEndpoint(endpointId: string): string | null {
|
||||
if (!rule.pattern.trim()) return `${prefix}正则表达式不能为空`
|
||||
try {
|
||||
new RegExp(rule.pattern.trim())
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
return `${prefix}正则表达式无效:${err instanceof Error ? err.message : String(err)}`
|
||||
}
|
||||
const flags = rule.flags.trim()
|
||||
@@ -1984,7 +1984,7 @@ async function saveEndpoint(endpoint: ProviderEndpoint) {
|
||||
savingEndpointId.value = endpoint.id
|
||||
try {
|
||||
// 仅提交变更字段,避免 fixed provider 因 base_url/custom_path 被锁定而更新失败
|
||||
const payload: Record<string, any> = {}
|
||||
const payload: Record<string, unknown> = {}
|
||||
|
||||
if (!isFixedProvider.value) {
|
||||
if (state.url !== endpoint.base_url) payload.base_url = state.url
|
||||
@@ -2001,8 +2001,8 @@ async function saveEndpoint(endpoint: ProviderEndpoint) {
|
||||
await updateEndpoint(endpoint.id, payload)
|
||||
success('端点已更新')
|
||||
emit('endpointUpdated')
|
||||
} catch (error: any) {
|
||||
showError(error.response?.data?.detail || '更新失败', '错误')
|
||||
} catch (error: unknown) {
|
||||
showError(parseApiError(error, '更新失败'), '错误')
|
||||
} finally {
|
||||
savingEndpointId.value = null
|
||||
}
|
||||
@@ -2020,8 +2020,8 @@ async function handleToggleFormatConversion(endpoint: ProviderEndpoint) {
|
||||
})
|
||||
success(newEnabled ? '已启用格式转换' : '已关闭格式转换')
|
||||
emit('endpointUpdated')
|
||||
} catch (error: any) {
|
||||
showError(error.response?.data?.detail || '操作失败', '错误')
|
||||
} catch (error: unknown) {
|
||||
showError(parseApiError(error, '操作失败'), '错误')
|
||||
} finally {
|
||||
togglingFormatEndpointId.value = null
|
||||
}
|
||||
@@ -2070,7 +2070,7 @@ async function handleCycleUpstreamStream(endpoint: ProviderEndpoint) {
|
||||
|
||||
savingEndpointId.value = endpoint.id
|
||||
try {
|
||||
const merged: Record<string, any> = { ...(endpoint.config || {}) }
|
||||
const merged: Record<string, unknown> = { ...(endpoint.config || {}) }
|
||||
// 清理旧的 key
|
||||
delete merged.upstream_stream_policy
|
||||
delete merged.upstreamStreamPolicy
|
||||
@@ -2091,8 +2091,8 @@ async function handleCycleUpstreamStream(endpoint: ProviderEndpoint) {
|
||||
|
||||
success(`已切换为${nextLabel}`)
|
||||
emit('endpointUpdated')
|
||||
} catch (error: any) {
|
||||
showError(error.response?.data?.detail || '操作失败', '错误')
|
||||
} catch (error: unknown) {
|
||||
showError(parseApiError(error, '操作失败'), '错误')
|
||||
} finally {
|
||||
savingEndpointId.value = null
|
||||
}
|
||||
@@ -2122,8 +2122,8 @@ async function handleAddEndpoint() {
|
||||
// 重置表单,保留 URL
|
||||
newEndpoint.value = { api_format: '', base_url: baseUrl, custom_path: '' }
|
||||
emit('endpointCreated')
|
||||
} catch (error: any) {
|
||||
showError(error.response?.data?.detail || '添加失败', '错误')
|
||||
} catch (error: unknown) {
|
||||
showError(parseApiError(error, '添加失败'), '错误')
|
||||
} finally {
|
||||
addingEndpoint.value = false
|
||||
}
|
||||
@@ -2137,8 +2137,8 @@ async function handleToggleEndpoint(endpoint: ProviderEndpoint) {
|
||||
await updateEndpoint(endpoint.id, { is_active: newStatus })
|
||||
success(newStatus ? '端点已启用' : '端点已停用')
|
||||
emit('endpointUpdated')
|
||||
} catch (error: any) {
|
||||
showError(error.response?.data?.detail || '操作失败', '错误')
|
||||
} catch (error: unknown) {
|
||||
showError(parseApiError(error, '操作失败'), '错误')
|
||||
} finally {
|
||||
togglingEndpointId.value = null
|
||||
}
|
||||
@@ -2162,8 +2162,8 @@ async function confirmDeleteEndpoint() {
|
||||
await deleteEndpoint(endpoint.id)
|
||||
success(`已删除 ${formatApiFormat(endpoint.api_format)} 端点`)
|
||||
emit('endpointUpdated')
|
||||
} catch (error: any) {
|
||||
showError(error.response?.data?.detail || '删除失败', '错误')
|
||||
} catch (error: unknown) {
|
||||
showError(parseApiError(error, '删除失败'), '错误')
|
||||
} finally {
|
||||
deletingEndpointId.value = null
|
||||
endpointToDelete.value = null
|
||||
|
||||
@@ -142,6 +142,7 @@ import EndpointHealthTimeline from './EndpointHealthTimeline.vue'
|
||||
import { getEndpointStatusMonitor, getPublicEndpointStatusMonitor } from '@/api/endpoints/health'
|
||||
import type { EndpointStatusMonitor, PublicEndpointStatusMonitor } from '@/api/endpoints/types'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { formatApiFormat } from '@/api/endpoints/types/api-format'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
@@ -176,8 +177,8 @@ async function loadMonitors() {
|
||||
const data = await getPublicEndpointStatusMonitor(params)
|
||||
monitors.value = data.formats || []
|
||||
}
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '加载健康监控数据失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '加载健康监控数据失败'), '错误')
|
||||
} finally {
|
||||
loadingMonitors.value = false
|
||||
}
|
||||
|
||||
@@ -191,7 +191,7 @@ import Button from '@/components/ui/button.vue'
|
||||
import Badge from '@/components/ui/badge.vue'
|
||||
import Checkbox from '@/components/ui/checkbox.vue'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseUpstreamModelError } from '@/utils/errorParser'
|
||||
import { parseApiError, parseUpstreamModelError } from '@/utils/errorParser'
|
||||
import {
|
||||
importModelsFromUpstream,
|
||||
getProviderModels,
|
||||
@@ -305,9 +305,8 @@ async function fetchUpstreamModels() {
|
||||
// 上游返回空列表但无错误
|
||||
hasQueried.value = true
|
||||
}
|
||||
} catch (err: any) {
|
||||
const rawError = err.response?.data?.detail || err.message || '获取上游模型失败'
|
||||
errorMessage.value = parseUpstreamModelError(rawError)
|
||||
} catch (err: unknown) {
|
||||
errorMessage.value = parseUpstreamModelError(parseApiError(err, '获取上游模型失败'))
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -378,8 +377,8 @@ async function handleImport() {
|
||||
const errorMsg = response.errors?.[0]?.error || '导入失败'
|
||||
showError(errorMsg, '导入失败')
|
||||
}
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '导入失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '导入失败'), '错误')
|
||||
} finally {
|
||||
importing.value = false
|
||||
}
|
||||
|
||||
@@ -796,7 +796,7 @@ async function handleSave() {
|
||||
success('模型权限已更新', '成功')
|
||||
emit('saved')
|
||||
emit('close')
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '保存失败'), '错误')
|
||||
} finally {
|
||||
saving.value = false
|
||||
|
||||
@@ -563,7 +563,7 @@ function parsePatternText(text: string): string[] {
|
||||
}
|
||||
|
||||
// 解析 Service Account JSON 文本
|
||||
function parseAuthConfig(): Record<string, any> | null {
|
||||
function parseAuthConfig(): Record<string, unknown> | null {
|
||||
if (form.value.auth_type !== 'vertex_ai') return null
|
||||
const text = form.value.auth_config_text.trim()
|
||||
if (!text) return null
|
||||
@@ -699,7 +699,7 @@ async function handleSave() {
|
||||
|
||||
emit('saved')
|
||||
emit('close')
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
const errorMessage = parseApiError(err, '保存密钥失败')
|
||||
showError(errorMessage, '错误')
|
||||
} finally {
|
||||
|
||||
@@ -153,6 +153,7 @@ import { ref, watch } from 'vue'
|
||||
import { Tag, Plus, X, Loader2, GripVertical, Info } from 'lucide-vue-next'
|
||||
import { Dialog, Button, Input, Label } from '@/components/ui'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { updateModel } from '@/api/endpoints/models'
|
||||
import type { Model, ProviderModelAlias } from '@/api/endpoints'
|
||||
|
||||
@@ -262,7 +263,7 @@ function handleDrop(targetIndex: number) {
|
||||
items.forEach(alias => {
|
||||
// 找到这个映射在原数组中的索引
|
||||
const originalIdx = aliases.value.findIndex(a => a === alias)
|
||||
const originalPriority = originalIdx >= 0 ? originalPriorityMap.get(originalIdx)! : alias.priority
|
||||
const originalPriority = originalIdx >= 0 ? (originalPriorityMap.get(originalIdx) ?? alias.priority) : alias.priority
|
||||
|
||||
if (alias === draggedItem) {
|
||||
// 被拖动的映射是独立的新组,获得当前优先级
|
||||
@@ -271,7 +272,7 @@ function handleDrop(targetIndex: number) {
|
||||
} else {
|
||||
if (groupNewPriority.has(originalPriority)) {
|
||||
// 这个组已经分配过优先级,使用相同的值
|
||||
alias.priority = groupNewPriority.get(originalPriority)!
|
||||
alias.priority = groupNewPriority.get(originalPriority) ?? currentPriority
|
||||
} else {
|
||||
// 这个组第一次出现,分配新优先级
|
||||
groupNewPriority.set(originalPriority, currentPriority)
|
||||
@@ -325,8 +326,8 @@ async function handleSubmit() {
|
||||
showSuccess('映射配置已保存')
|
||||
emit('update:open', false)
|
||||
emit('saved')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '保存失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '保存失败'), '错误')
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
|
||||
@@ -261,6 +261,7 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import {
|
||||
type Model,
|
||||
type ProviderModelAlias,
|
||||
@@ -461,8 +462,8 @@ async function fetchUpstreamModels() {
|
||||
if (result.error) {
|
||||
showError(result.error, '获取上游模型失败')
|
||||
}
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '获取上游模型列表失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '获取上游模型列表失败'), '错误')
|
||||
} finally {
|
||||
loadingModels.value = false
|
||||
fetchingUpstreamModels.value = false
|
||||
@@ -579,8 +580,8 @@ async function handleSubmit() {
|
||||
showSuccess(props.editingGroup ? '映射组已更新' : '映射已添加')
|
||||
emit('update:open', false)
|
||||
emit('saved')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '操作失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '操作失败'), '错误')
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
|
||||
@@ -92,34 +92,72 @@
|
||||
>
|
||||
<!-- Kiro: 设备授权模式 -->
|
||||
<template v-if="isKiroProvider">
|
||||
<!-- 初始状态:输入 Start URL / Region + 开始 -->
|
||||
<!-- 初始状态:选择授权类型 + 开始 -->
|
||||
<div
|
||||
v-if="!device.session_id && !device.starting"
|
||||
class="space-y-3"
|
||||
>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs font-medium">Start URL</label>
|
||||
<input
|
||||
v-model="device.start_url"
|
||||
type="text"
|
||||
placeholder="https://view.awsapps.com/start"
|
||||
class="w-full h-8 px-2 text-xs rounded-md border border-border bg-background font-mono"
|
||||
spellcheck="false"
|
||||
<!-- Builder ID / Identity Center 切换 -->
|
||||
<div class="grid grid-cols-2 gap-1.5">
|
||||
<button
|
||||
v-for="opt in ([
|
||||
{ key: 'builder_id', label: 'Builder ID' },
|
||||
{ key: 'identity_center', label: 'Identity Center' },
|
||||
] as const)"
|
||||
:key="opt.key"
|
||||
class="h-8 text-xs font-medium rounded-md border transition-colors"
|
||||
:class="device.auth_type === opt.key
|
||||
? 'border-primary bg-primary/5 text-foreground'
|
||||
: 'border-border text-muted-foreground hover:text-foreground hover:border-foreground/20'"
|
||||
@click="device.auth_type = opt.key"
|
||||
>
|
||||
{{ opt.label }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs font-medium">Region</label>
|
||||
<input
|
||||
v-model="device.region"
|
||||
type="text"
|
||||
placeholder="us-east-1"
|
||||
class="w-full h-8 px-2 text-xs rounded-md border border-border bg-background font-mono"
|
||||
spellcheck="false"
|
||||
|
||||
<!-- grid 叠放保持高度稳定 -->
|
||||
<div class="grid [&>*]:col-start-1 [&>*]:row-start-1">
|
||||
<!-- Builder ID: 说明文字 -->
|
||||
<div
|
||||
class="flex items-center justify-center transition-opacity duration-150"
|
||||
:class="device.auth_type === 'builder_id' ? 'opacity-100' : 'opacity-0 pointer-events-none'"
|
||||
>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
使用个人 AWS Builder ID 进行设备授权,无需额外配置。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Identity Center: Start URL + Region -->
|
||||
<div
|
||||
class="space-y-3 transition-opacity duration-150"
|
||||
:class="device.auth_type === 'identity_center' ? 'opacity-100' : 'opacity-0 pointer-events-none'"
|
||||
>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs font-medium">Start URL</label>
|
||||
<input
|
||||
v-model="device.start_url"
|
||||
type="text"
|
||||
placeholder="https://your-org.awsapps.com/start"
|
||||
class="w-full h-8 px-2 text-xs rounded-md border border-border bg-background font-mono"
|
||||
spellcheck="false"
|
||||
>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs font-medium">Region</label>
|
||||
<input
|
||||
v-model="device.region"
|
||||
type="text"
|
||||
placeholder="us-east-1"
|
||||
class="w-full h-8 px-2 text-xs rounded-md border border-border bg-background font-mono"
|
||||
spellcheck="false"
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
class="w-full"
|
||||
:disabled="!device.start_url.trim()"
|
||||
:disabled="device.auth_type === 'identity_center' && !device.start_url.trim()"
|
||||
@click="startDeviceAuth"
|
||||
>
|
||||
开始授权
|
||||
@@ -480,7 +518,10 @@ function createInitialOAuthState(): OAuthState {
|
||||
const oauth = ref<OAuthState>(createInitialOAuthState())
|
||||
|
||||
// 设备授权状态
|
||||
type DeviceAuthType = 'builder_id' | 'identity_center'
|
||||
|
||||
interface DeviceAuthState {
|
||||
auth_type: DeviceAuthType
|
||||
start_url: string
|
||||
region: string
|
||||
starting: boolean
|
||||
@@ -494,8 +535,12 @@ interface DeviceAuthState {
|
||||
error: string
|
||||
}
|
||||
|
||||
const BUILDER_ID_START_URL = 'https://view.awsapps.com/start'
|
||||
const BUILDER_ID_REGION = 'us-east-1'
|
||||
|
||||
function createInitialDeviceState(): DeviceAuthState {
|
||||
return {
|
||||
auth_type: 'builder_id',
|
||||
start_url: '',
|
||||
region: 'us-east-1',
|
||||
starting: false,
|
||||
@@ -563,8 +608,9 @@ function stopDevicePolling() {
|
||||
|
||||
function resetDevice() {
|
||||
stopDevicePolling()
|
||||
const { start_url, region } = device.value
|
||||
const { auth_type, start_url, region } = device.value
|
||||
device.value = createInitialDeviceState()
|
||||
device.value.auth_type = auth_type
|
||||
device.value.start_url = start_url
|
||||
device.value.region = region
|
||||
}
|
||||
@@ -635,7 +681,7 @@ async function initOAuth() {
|
||||
oauth.value.redirect_uri = resp.redirect_uri
|
||||
oauth.value.instructions = resp.instructions
|
||||
oauth.value.provider_type = resp.provider_type
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
const errorMessage = parseApiError(err, '初始化授权失败')
|
||||
showError(errorMessage, '错误')
|
||||
mode.value = 'import'
|
||||
@@ -655,7 +701,7 @@ async function handleCompleteOAuth() {
|
||||
success('授权成功,账号已添加')
|
||||
emit('saved')
|
||||
handleClose()
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
const errorMessage = parseApiError(err, '完成授权失败')
|
||||
showError(errorMessage, '错误')
|
||||
} finally {
|
||||
@@ -699,13 +745,14 @@ function parseImportText(text: string): { refresh_token: string; name?: string }
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed)
|
||||
const parsed: unknown = JSON.parse(trimmed)
|
||||
if (typeof parsed === 'object' && parsed !== null) {
|
||||
const refreshToken = (parsed as any).refresh_token
|
||||
const obj = parsed as Record<string, unknown>
|
||||
const refreshToken = obj.refresh_token
|
||||
if (typeof refreshToken === 'string' && refreshToken.trim()) {
|
||||
return {
|
||||
refresh_token: refreshToken.trim(),
|
||||
name: (parsed as any).name || (parsed as any).oauth_email || undefined,
|
||||
name: (typeof obj.name === 'string' ? obj.name : undefined) || (typeof obj.oauth_email === 'string' ? obj.oauth_email : undefined),
|
||||
}
|
||||
}
|
||||
return null
|
||||
@@ -789,7 +836,7 @@ async function handleImport() {
|
||||
emit('saved')
|
||||
handleClose()
|
||||
}
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
const errorMessage = parseApiError(err, '导入失败')
|
||||
showError(errorMessage, '错误')
|
||||
} finally {
|
||||
@@ -821,9 +868,10 @@ async function startDeviceAuth() {
|
||||
device.value.starting = true
|
||||
device.value.error = ''
|
||||
try {
|
||||
const isBuilderID = device.value.auth_type === 'builder_id'
|
||||
const resp = await startDeviceAuthorize(props.providerId, {
|
||||
start_url: device.value.start_url.trim() || undefined,
|
||||
region: device.value.region.trim() || undefined,
|
||||
start_url: isBuilderID ? BUILDER_ID_START_URL : (device.value.start_url.trim() || undefined),
|
||||
region: isBuilderID ? BUILDER_ID_REGION : (device.value.region.trim() || undefined),
|
||||
proxy_node_id: selectedProxyNodeId.value || undefined,
|
||||
})
|
||||
device.value.session_id = resp.session_id
|
||||
@@ -835,7 +883,7 @@ async function startDeviceAuth() {
|
||||
device.value.status = 'pending'
|
||||
startCountdown()
|
||||
scheduleDevicePoll()
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
const errorMessage = parseApiError(err, '发起设备授权失败')
|
||||
showError(errorMessage, '错误')
|
||||
device.value.status = 'error'
|
||||
@@ -884,7 +932,7 @@ async function pollDevice() {
|
||||
device.value.error = result.error || '授权失败'
|
||||
return
|
||||
}
|
||||
} catch (err: any) {
|
||||
} catch {
|
||||
// 网络错误等,继续轮询
|
||||
scheduleDevicePoll()
|
||||
}
|
||||
|
||||
@@ -361,7 +361,7 @@ async function handleSave() {
|
||||
success('账号已更新', '成功')
|
||||
emit('saved')
|
||||
emit('close')
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
const errorMessage = parseApiError(err, '保存失败')
|
||||
showError(errorMessage, '错误')
|
||||
} finally {
|
||||
|
||||
@@ -432,12 +432,14 @@ import { Dialog } from '@/components/ui'
|
||||
import Button from '@/components/ui/button.vue'
|
||||
import Badge from '@/components/ui/badge.vue'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { updateProvider, updateProviderKey } from '@/api/endpoints'
|
||||
import type { ProviderWithEndpointsSummary } from '@/api/endpoints'
|
||||
import { adminApi } from '@/api/admin'
|
||||
import { batchQueryBalance, type ActionResultResponse, type BalanceInfo } from '@/api/providerOps'
|
||||
import { API_FORMAT_SHORT } from '@/api/endpoints/types'
|
||||
import { formatApiFormat } from '@/api/endpoints/types/api-format'
|
||||
import { log } from '@/utils/logger'
|
||||
|
||||
interface KeyWithMeta {
|
||||
id: string
|
||||
@@ -555,7 +557,7 @@ async function loadBalances() {
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[loadBalances] 加载余额数据失败:', e)
|
||||
log.warn('[loadBalances] 加载余额数据失败', e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -632,7 +634,7 @@ async function loadKeysByFormat() {
|
||||
|
||||
// 每个格式独立管理优先级,使用后端返回的 format_priority
|
||||
const data: Record<string, KeyWithMeta[]> = {}
|
||||
for (const [format, keys] of Object.entries(response.data as Record<string, any[]>)) {
|
||||
for (const [format, keys] of Object.entries(response.data as Record<string, Record<string, unknown>[]>)) {
|
||||
// 计算该格式下的默认优先级
|
||||
let maxPriority = 0
|
||||
for (const key of keys) {
|
||||
@@ -656,8 +658,8 @@ async function loadKeysByFormat() {
|
||||
if (formats.length > 0 && !formats.includes(activeFormatTab.value)) {
|
||||
activeFormatTab.value = formats[0]
|
||||
}
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '加载 Key 列表失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '加载 Key 列表失败'), '错误')
|
||||
} finally {
|
||||
loadingKeys.value = false
|
||||
}
|
||||
@@ -681,8 +683,8 @@ async function toggleKeyActive(format: string, key: KeyWithMeta) {
|
||||
keysByFormat.value[fmt] = sortKeysByActiveAndPriority(keysByFormat.value[fmt])
|
||||
}
|
||||
success(newStatus ? 'Key 已启用' : 'Key 已停用')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '操作失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '操作失败'), '错误')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -797,7 +799,7 @@ function handleProviderDrop(dropIndex: number) {
|
||||
let currentPriority = 1
|
||||
|
||||
items.forEach(provider => {
|
||||
const originalPriority = originalPriorityMap.get(provider.id)!
|
||||
const originalPriority = originalPriorityMap.get(provider.id) ?? 0
|
||||
|
||||
if (provider === draggedItem) {
|
||||
// 被拖动的项单独成组
|
||||
@@ -806,7 +808,7 @@ function handleProviderDrop(dropIndex: number) {
|
||||
} else {
|
||||
if (groupNewPriority.has(originalPriority)) {
|
||||
// 同组的其他项使用相同的新优先级
|
||||
provider.provider_priority = groupNewPriority.get(originalPriority)!
|
||||
provider.provider_priority = groupNewPriority.get(originalPriority) ?? currentPriority
|
||||
} else {
|
||||
// 新组,分配新优先级
|
||||
groupNewPriority.set(originalPriority, currentPriority)
|
||||
@@ -881,7 +883,7 @@ function handleKeyDrop(format: string, dropIndex: number) {
|
||||
let currentPriority = 1
|
||||
|
||||
items.forEach(key => {
|
||||
const originalPriority = originalPriorityMap.get(key.id)!
|
||||
const originalPriority = originalPriorityMap.get(key.id) ?? 0
|
||||
|
||||
if (key === draggedItem) {
|
||||
// 被拖动的项单独成组
|
||||
@@ -890,7 +892,7 @@ function handleKeyDrop(format: string, dropIndex: number) {
|
||||
} else {
|
||||
if (groupNewPriority.has(originalPriority)) {
|
||||
// 同组的其他项使用相同的新优先级
|
||||
key.priority = groupNewPriority.get(originalPriority)!
|
||||
key.priority = groupNewPriority.get(originalPriority) ?? currentPriority
|
||||
} else {
|
||||
// 新组,分配新优先级
|
||||
groupNewPriority.set(originalPriority, currentPriority)
|
||||
@@ -959,8 +961,8 @@ async function save() {
|
||||
if (activeMainTab.value === 'provider') {
|
||||
close()
|
||||
}
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '保存失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '保存失败'), '错误')
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
|
||||
@@ -306,6 +306,7 @@ import {
|
||||
deleteProviderOpsConfig,
|
||||
type ArchitectureInfo,
|
||||
} from '@/api/providerOps'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { useConfirm } from '@/composables/useConfirm'
|
||||
import type { AuthTemplateFieldGroup } from '../auth-templates/types'
|
||||
@@ -325,7 +326,7 @@ const props = defineProps<{
|
||||
open: boolean
|
||||
providerId: string
|
||||
providerWebsite?: string
|
||||
currentConfig?: any
|
||||
currentConfig?: Record<string, unknown> | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -373,7 +374,7 @@ const architecturesLoaded = ref(false)
|
||||
// 当前选择
|
||||
const selectedArchitectureId = ref('new_api')
|
||||
const selectedAuthType = ref('')
|
||||
const formData = ref<Record<string, any>>({})
|
||||
const formData = ref<Record<string, unknown>>({})
|
||||
|
||||
// 当前架构支持的认证方式
|
||||
const currentAuthTypes = computed(() => {
|
||||
@@ -446,7 +447,7 @@ function handleAuthTypeChange() {
|
||||
formChanged.value = true
|
||||
}
|
||||
|
||||
function handleFieldChange(fieldKey: string, value: any) {
|
||||
function handleFieldChange(fieldKey: string, value: unknown) {
|
||||
formChanged.value = true
|
||||
|
||||
// 执行 schema 定义的字段钩子
|
||||
@@ -475,9 +476,9 @@ function resetFormData() {
|
||||
}
|
||||
|
||||
// 初始化表单数据
|
||||
const data: Record<string, any> = {}
|
||||
const data: Record<string, unknown> = {}
|
||||
for (const [key, prop] of Object.entries(schema.properties)) {
|
||||
data[key] = (prop as any)['x-default-value'] ?? ''
|
||||
data[key] = (prop as Record<string, unknown>)['x-default-value'] ?? ''
|
||||
}
|
||||
// 代理相关默认值
|
||||
data.proxy_enabled = false
|
||||
@@ -581,10 +582,9 @@ async function handleVerify() {
|
||||
|
||||
showError(result.message || '验证失败')
|
||||
}
|
||||
} catch (error: any) {
|
||||
} catch (error: unknown) {
|
||||
verifyStatus.value = 'error'
|
||||
const errMsg = error.response?.data?.detail || error.message || '验证失败'
|
||||
showError(errMsg)
|
||||
showError(parseApiError(error, '验证失败'))
|
||||
} finally {
|
||||
isVerifying.value = false
|
||||
}
|
||||
@@ -632,8 +632,8 @@ async function handleSave() {
|
||||
} else {
|
||||
showError(result.message || '保存失败')
|
||||
}
|
||||
} catch (error: any) {
|
||||
showError(error.response?.data?.detail || error.message, '保存失败')
|
||||
} catch (error: unknown) {
|
||||
showError(parseApiError(error, '保存失败'), '保存失败')
|
||||
} finally {
|
||||
isSaving.value = false
|
||||
}
|
||||
@@ -666,14 +666,14 @@ async function handleClear() {
|
||||
} else {
|
||||
showError(result.message || '清除失败')
|
||||
}
|
||||
} catch (error: any) {
|
||||
showError(error.response?.data?.detail || error.message, '清除失败')
|
||||
} catch (error: unknown) {
|
||||
showError(parseApiError(error, '清除失败'), '清除失败')
|
||||
} finally {
|
||||
isClearing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function loadFromConfig(config: any) {
|
||||
function loadFromConfig(config: Record<string, unknown>) {
|
||||
if (!config?.connector) return
|
||||
|
||||
hasExistingConfig.value = true
|
||||
|
||||
@@ -1007,6 +1007,7 @@ import {
|
||||
ShieldX,
|
||||
Globe,
|
||||
} from 'lucide-vue-next'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { useEscapeKey } from '@/composables/useEscapeKey'
|
||||
import Button from '@/components/ui/button.vue'
|
||||
import Badge from '@/components/ui/badge.vue'
|
||||
@@ -1022,7 +1023,8 @@ import {
|
||||
updateProvider,
|
||||
getProviderModels,
|
||||
getProviderMappingPreview,
|
||||
type ProviderMappingPreviewResponse
|
||||
type ProviderMappingPreviewResponse,
|
||||
type ProviderWithEndpointsSummary,
|
||||
} from '@/api/endpoints'
|
||||
import { adminApi } from '@/api/admin'
|
||||
import {
|
||||
@@ -1074,8 +1076,8 @@ interface Props {
|
||||
const props = defineProps<Props>()
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:open', value: boolean): void
|
||||
(e: 'edit', provider: any): void
|
||||
(e: 'toggleStatus', provider: any): void
|
||||
(e: 'edit', provider: ProviderWithEndpointsSummary): void
|
||||
(e: 'toggleStatus', provider: ProviderWithEndpointsSummary): void
|
||||
(e: 'refresh'): void
|
||||
}>()
|
||||
|
||||
@@ -1085,7 +1087,7 @@ const { copyToClipboard } = useClipboard()
|
||||
const { tick: countdownTick, start: startCountdownTimer, stop: stopCountdownTimer } = useCountdownTimer()
|
||||
|
||||
const loading = ref(false)
|
||||
const provider = ref<any>(null)
|
||||
const provider = ref<ProviderWithEndpointsSummary | null>(null)
|
||||
const endpoints = ref<ProviderEndpointWithKeys[]>([])
|
||||
const providerKeys = ref<EndpointAPIKey[]>([]) // Provider 级别的 keys
|
||||
const providerModels = ref<Model[]>([]) // Provider 级别的 models
|
||||
@@ -1364,8 +1366,8 @@ async function copyFullKey(key: EndpointAPIKey) {
|
||||
|
||||
revealedKeys.value.set(key.id, textToCopy)
|
||||
copyToClipboard(textToCopy)
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '获取密钥失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '获取密钥失败'), '错误')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1385,8 +1387,8 @@ async function downloadRefreshToken(key: EndpointAPIKey) {
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '导出失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '导出失败'), '错误')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1409,8 +1411,8 @@ async function confirmDeleteKey() {
|
||||
// 刷新端点列表及模型数据(删除 Key 触发自动解除模型关联)
|
||||
await loadEndpoints()
|
||||
emit('refresh')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '删除密钥失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '删除密钥失败'), '错误')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1420,8 +1422,8 @@ async function handleRecoverKey(key: EndpointAPIKey) {
|
||||
showSuccess(result.message || 'Key已完全恢复')
|
||||
await loadEndpoints()
|
||||
emit('refresh')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || 'Key恢复失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, 'Key恢复失败'), '错误')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1446,8 +1448,8 @@ async function handleRefreshOAuth(key: EndpointAPIKey) {
|
||||
// Antigravity:token 刷新后可能完成了账号激活,触发配额获取
|
||||
// (不 emit('refresh'),避免触发全局 provider 余额刷新)
|
||||
void autoRefreshQuotaInBackground()
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || 'Token 刷新失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, 'Token 刷新失败'), '错误')
|
||||
} finally {
|
||||
refreshingOAuthKeyId.value = null
|
||||
}
|
||||
@@ -1483,8 +1485,8 @@ async function handleClearOAuthInvalid(key: EndpointAPIKey) {
|
||||
keyInList.is_active = true
|
||||
}
|
||||
await loadEndpoints()
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '清除失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '清除失败'), '错误')
|
||||
} finally {
|
||||
clearingOAuthInvalidKeyId.value = null
|
||||
}
|
||||
@@ -1703,9 +1705,9 @@ async function autoRefreshQuotaInBackground() {
|
||||
} else if (!hadCachedQuota && providerType === 'antigravity') {
|
||||
showError('没有获取到配额信息(请检查账号是否已授权、project_id 是否存在)', '提示')
|
||||
}
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
if (!hadCachedQuota && providerType === 'antigravity') {
|
||||
showError(err.response?.data?.detail || '后台刷新配额失败', '错误')
|
||||
showError(parseApiError(err, '后台刷新配额失败'), '错误')
|
||||
}
|
||||
} finally {
|
||||
refreshingQuota.value = false
|
||||
@@ -1756,8 +1758,8 @@ async function toggleKeyActive(key: EndpointAPIKey) {
|
||||
key.is_active = newStatus
|
||||
showSuccess(newStatus ? '密钥已启用' : '密钥已停用')
|
||||
emit('refresh')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '操作失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '操作失败'), '错误')
|
||||
} finally {
|
||||
togglingKeyId.value = null
|
||||
}
|
||||
@@ -1768,7 +1770,7 @@ async function toggleKeyActive(key: EndpointAPIKey) {
|
||||
/** 获取 Key 当前代理节点的名称(用于显示) */
|
||||
function getKeyProxyNodeName(key: EndpointAPIKey): string | null {
|
||||
if (!key.proxy?.node_id) return null
|
||||
const node = proxyNodesStore.nodes.find(n => n.id === key.proxy!.node_id)
|
||||
const node = proxyNodesStore.nodes.find(n => n.id === key.proxy?.node_id)
|
||||
return node ? node.name : `${key.proxy.node_id.slice(0, 8) }...`
|
||||
}
|
||||
|
||||
@@ -1791,8 +1793,8 @@ async function setKeyProxy(key: EndpointAPIKey, nodeId: string) {
|
||||
proxyPopoverOpenKeyId.value = null
|
||||
showSuccess('代理节点已设置')
|
||||
emit('refresh')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '设置代理失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '设置代理失败'), '错误')
|
||||
} finally {
|
||||
savingProxyKeyId.value = null
|
||||
}
|
||||
@@ -1807,8 +1809,8 @@ async function clearKeyProxy(key: EndpointAPIKey) {
|
||||
proxyPopoverOpenKeyId.value = null
|
||||
showSuccess('已清除账号代理,将使用提供商级别代理')
|
||||
emit('refresh')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '清除代理失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '清除代理失败'), '错误')
|
||||
} finally {
|
||||
savingProxyKeyId.value = null
|
||||
}
|
||||
@@ -1911,8 +1913,8 @@ async function savePriority(key: EndpointAPIKey) {
|
||||
// 重新排序
|
||||
providerKeys.value.sort((a, b) => (a.internal_priority ?? 0) - (b.internal_priority ?? 0))
|
||||
emit('refresh')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '更新优先级失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '更新优先级失败'), '错误')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1999,8 +2001,8 @@ async function saveMultiplier(key: EndpointAPIKey, format: string) {
|
||||
keyToUpdate.rate_multipliers = rateMultipliers
|
||||
}
|
||||
emit('refresh')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '更新倍率失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '更新倍率失败'), '错误')
|
||||
} finally {
|
||||
multiplierSaving.value = false
|
||||
}
|
||||
@@ -2082,7 +2084,7 @@ async function handleKeyDrop(event: DragEvent, targetIndex: number) {
|
||||
const newPriorityMap = new Map<string, number>()
|
||||
|
||||
items.forEach(key => {
|
||||
const originalPriority = originalPriorityMap.get(key.id)!
|
||||
const originalPriority = originalPriorityMap.get(key.id) ?? 0
|
||||
|
||||
if (key === draggedKey) {
|
||||
// 被拖动的项单独成组
|
||||
@@ -2091,7 +2093,7 @@ async function handleKeyDrop(event: DragEvent, targetIndex: number) {
|
||||
} else {
|
||||
if (groupNewPriority.has(originalPriority)) {
|
||||
// 同组的其他项使用相同的新优先级
|
||||
newPriorityMap.set(key.id, groupNewPriority.get(originalPriority)!)
|
||||
newPriorityMap.set(key.id, groupNewPriority.get(originalPriority) ?? currentPriority)
|
||||
} else {
|
||||
// 新组,分配新优先级
|
||||
groupNewPriority.set(originalPriority, currentPriority)
|
||||
@@ -2115,8 +2117,8 @@ async function handleKeyDrop(event: DragEvent, targetIndex: number) {
|
||||
showSuccess('优先级已更新')
|
||||
await loadEndpoints()
|
||||
emit('refresh')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '更新优先级失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '更新优先级失败'), '错误')
|
||||
await loadEndpoints()
|
||||
}
|
||||
}
|
||||
@@ -2479,8 +2481,8 @@ async function loadProvider() {
|
||||
if (!provider.value) {
|
||||
throw new Error('Provider 不存在')
|
||||
}
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || err.message || '加载失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '加载失败'), '错误')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -2511,8 +2513,8 @@ async function loadEndpoints() {
|
||||
if (bIdx === -1) return -1
|
||||
return aIdx - bIdx
|
||||
})
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '加载端点失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '加载端点失败'), '错误')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -500,7 +500,7 @@ const handleSubmit = async () => {
|
||||
}
|
||||
|
||||
emit('update:modelValue', false)
|
||||
} catch (error: any) {
|
||||
} catch (error: unknown) {
|
||||
const action = isEditMode.value ? '更新' : '创建'
|
||||
showError(parseApiError(error, `${action}提供商失败`), `${action}失败`)
|
||||
} finally {
|
||||
|
||||
@@ -202,6 +202,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { Loader2, Layers, SquarePen, Plus, Trash2 } from 'lucide-vue-next'
|
||||
import {
|
||||
Dialog,
|
||||
@@ -298,7 +299,7 @@ const VIDEO_RESOLUTION_PRICE_PRESETS: Record<
|
||||
const form = ref({
|
||||
global_model_id: '',
|
||||
price_per_request: undefined as number | undefined,
|
||||
config: {} as Record<string, any>,
|
||||
config: {} as Record<string, unknown>,
|
||||
// 能力配置
|
||||
supports_vision: undefined as boolean | undefined,
|
||||
supports_function_calling: undefined as boolean | undefined,
|
||||
@@ -392,53 +393,54 @@ function resetForm() {
|
||||
availableGlobalModels.value = []
|
||||
}
|
||||
|
||||
function getNested(obj: any, path: string): any {
|
||||
function getNested(obj: Record<string, unknown>, path: string): unknown {
|
||||
if (!obj || typeof obj !== 'object') return undefined
|
||||
const parts = path.split('.').filter(Boolean)
|
||||
let cur: any = obj
|
||||
let cur: unknown = obj
|
||||
for (const p of parts) {
|
||||
if (!cur || typeof cur !== 'object') return undefined
|
||||
cur = cur[p]
|
||||
cur = (cur as Record<string, unknown>)[p]
|
||||
}
|
||||
return cur
|
||||
}
|
||||
|
||||
function setNested(obj: any, path: string, value: any) {
|
||||
function setNested(obj: Record<string, unknown>, path: string, value: unknown) {
|
||||
if (!obj || typeof obj !== 'object') return
|
||||
const parts = path.split('.').filter(Boolean)
|
||||
if (parts.length === 0) return
|
||||
let cur: any = obj
|
||||
let cur: Record<string, unknown> = obj
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
const p = parts[i]
|
||||
if (!cur[p] || typeof cur[p] !== 'object') {
|
||||
cur[p] = {}
|
||||
}
|
||||
cur = cur[p]
|
||||
cur = cur[p] as Record<string, unknown>
|
||||
}
|
||||
cur[parts[parts.length - 1]] = value
|
||||
}
|
||||
|
||||
function deleteNested(obj: any, path: string) {
|
||||
function deleteNested(obj: Record<string, unknown>, path: string) {
|
||||
if (!obj || typeof obj !== 'object') return
|
||||
const parts = path.split('.').filter(Boolean)
|
||||
if (parts.length === 0) return
|
||||
let cur: any = obj
|
||||
let cur: Record<string, unknown> = obj
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
const p = parts[i]
|
||||
if (!cur[p] || typeof cur[p] !== 'object') return
|
||||
cur = cur[p]
|
||||
cur = cur[p] as Record<string, unknown>
|
||||
}
|
||||
delete cur[parts[parts.length - 1]]
|
||||
}
|
||||
|
||||
function pruneEmptyBillingConfig(cfg: Record<string, any>) {
|
||||
function pruneEmptyBillingConfig(cfg: Record<string, unknown>) {
|
||||
const billing = cfg.billing
|
||||
if (!billing || typeof billing !== 'object') return
|
||||
const video = billing.video
|
||||
const billingObj = billing as Record<string, unknown>
|
||||
const video = billingObj.video
|
||||
if (video && typeof video === 'object' && Object.keys(video).length === 0) {
|
||||
delete billing.video
|
||||
delete billingObj.video
|
||||
}
|
||||
if (Object.keys(billing).length === 0) {
|
||||
if (Object.keys(billingObj).length === 0) {
|
||||
delete cfg.billing
|
||||
}
|
||||
}
|
||||
@@ -461,7 +463,7 @@ function normalizeResolutionKey(raw: string): string {
|
||||
return k
|
||||
}
|
||||
|
||||
function loadVideoPricingFromConfig(cfg: Record<string, any>) {
|
||||
function loadVideoPricingFromConfig(cfg: Record<string, unknown>) {
|
||||
const raw = getNested(cfg, 'billing.video.price_per_second_by_resolution')
|
||||
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
||||
// 按分辨率从低到高排序
|
||||
@@ -475,7 +477,7 @@ function loadVideoPricingFromConfig(cfg: Record<string, any>) {
|
||||
}
|
||||
}
|
||||
|
||||
function applyVideoPricingToConfig(cfg: Record<string, any>) {
|
||||
function applyVideoPricingToConfig(cfg: Record<string, unknown>) {
|
||||
// Clean legacy keys
|
||||
deleteNested(cfg, 'billing.video.price_per_second')
|
||||
deleteNested(cfg, 'billing.video.resolution_multipliers')
|
||||
@@ -546,8 +548,8 @@ async function loadAvailableGlobalModels() {
|
||||
availableGlobalModels.value = allGlobalModels.filter(
|
||||
(gm: GlobalModelResponse) => !existingGlobalModelIds.has(gm.id)
|
||||
)
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '加载模型列表失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '加载模型列表失败'), '错误')
|
||||
} finally {
|
||||
loadingGlobalModels.value = false
|
||||
}
|
||||
@@ -612,8 +614,8 @@ async function handleSubmit() {
|
||||
}
|
||||
emit('update:open', false)
|
||||
emit('saved')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || (isEditing.value ? '更新失败' : '添加失败'), '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, isEditing.value ? '更新失败' : '添加失败'), '错误')
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
|
||||
@@ -200,11 +200,12 @@ import {
|
||||
type ProviderModelAlias
|
||||
} from '@/api/endpoints'
|
||||
import { updateModel } from '@/api/endpoints/models'
|
||||
import { parseTestModelError } from '@/utils/errorParser'
|
||||
import { parseApiError, parseTestModelError } from '@/utils/errorParser'
|
||||
import { formatApiFormat } from '@/api/endpoints/types/api-format'
|
||||
import type { ProviderWithEndpointsSummary } from '@/api/endpoints'
|
||||
|
||||
const props = defineProps<{
|
||||
provider: any
|
||||
provider: ProviderWithEndpointsSummary
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -264,7 +265,7 @@ const aliasGroups = computed<AliasGroup[]>(() => {
|
||||
groupMap.set(groupKey, group)
|
||||
groups.push(group)
|
||||
}
|
||||
groupMap.get(groupKey)!.aliases.push(alias)
|
||||
groupMap.get(groupKey)?.aliases.push(alias)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,8 +286,8 @@ async function loadModels() {
|
||||
try {
|
||||
loading.value = true
|
||||
models.value = await getProviderModels(props.provider.id)
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '加载失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '加载失败'), '错误')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -361,8 +362,8 @@ async function confirmDelete() {
|
||||
deletingGroup.value = null
|
||||
await loadModels()
|
||||
emit('refresh')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '删除失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '删除失败'), '错误')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -373,7 +374,7 @@ async function onDialogSaved() {
|
||||
}
|
||||
|
||||
// 测试模型映射
|
||||
async function testMapping(group: any, mapping: any) {
|
||||
async function testMapping(group: AliasGroup, mapping: ProviderModelAlias) {
|
||||
const testingKey = `${group.model.id}-${group.apiFormatsKey}-${mapping.name}`
|
||||
testingMapping.value = testingKey
|
||||
|
||||
@@ -407,9 +408,8 @@ async function testMapping(group: any, mapping: any) {
|
||||
} else {
|
||||
showError(`映射测试失败: ${parseTestModelError(result)}`)
|
||||
}
|
||||
} catch (err: any) {
|
||||
const errorMsg = err.response?.data?.detail || err.message || '测试请求失败'
|
||||
showError(`映射测试失败: ${errorMsg}`)
|
||||
} catch (err: unknown) {
|
||||
showError(`映射测试失败: ${parseApiError(err, '测试请求失败')}`)
|
||||
} finally {
|
||||
testingMapping.value = null
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@
|
||||
size="icon"
|
||||
class="h-8 w-8"
|
||||
title="编辑映射"
|
||||
@click="editGroup(item.group!)"
|
||||
@click="item.group && editGroup(item.group)"
|
||||
>
|
||||
<Edit class="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
@@ -126,7 +126,7 @@
|
||||
size="icon"
|
||||
class="h-8 w-8 hover:text-destructive"
|
||||
title="删除映射"
|
||||
@click="deleteGroup(item.group!)"
|
||||
@click="item.group && deleteGroup(item.group)"
|
||||
>
|
||||
<Trash2 class="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
@@ -362,7 +362,8 @@ import {
|
||||
import { type EndpointAPIKey } from '@/api/endpoints/keys'
|
||||
import type { ProviderEndpoint } from '@/api/endpoints/types'
|
||||
import { updateModel } from '@/api/endpoints/models'
|
||||
import { parseTestModelError } from '@/utils/errorParser'
|
||||
import { parseApiError, parseTestModelError } from '@/utils/errorParser'
|
||||
import type { ProviderWithEndpointsSummary } from '@/api/endpoints'
|
||||
|
||||
interface MappingItem {
|
||||
name: string
|
||||
@@ -389,7 +390,7 @@ interface CombinedMapping {
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
provider: any
|
||||
provider: ProviderWithEndpointsSummary
|
||||
providerKeys?: EndpointAPIKey[]
|
||||
models?: Model[]
|
||||
mappingPreview?: ProviderMappingPreviewResponse | null
|
||||
@@ -456,7 +457,7 @@ const exactMappingGroups = computed<AliasGroup[]>(() => {
|
||||
groupMap.set(groupKey, group)
|
||||
groups.push(group)
|
||||
}
|
||||
groupMap.get(groupKey)!.aliases.push(alias)
|
||||
groupMap.get(groupKey)?.aliases.push(alias)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -486,10 +487,11 @@ const regexMappings = computed<CombinedMapping[]>(() => {
|
||||
mappings: [],
|
||||
matchedKeys: []
|
||||
})
|
||||
result.push(modelMap.get(gm.global_model_id)!)
|
||||
result.push(modelMap.get(gm.global_model_id) as CombinedMapping)
|
||||
}
|
||||
|
||||
const mapping = modelMap.get(gm.global_model_id)!
|
||||
const mapping = modelMap.get(gm.global_model_id)
|
||||
if (!mapping) continue
|
||||
|
||||
// 添加 Key 信息
|
||||
const keyMatches: MappingItem[] = gm.matched_models.map(m => ({
|
||||
@@ -497,7 +499,7 @@ const regexMappings = computed<CombinedMapping[]>(() => {
|
||||
pattern: m.mapping_pattern
|
||||
}))
|
||||
|
||||
mapping.matchedKeys!.push({
|
||||
mapping.matchedKeys?.push({
|
||||
keyId: keyInfo.key_id,
|
||||
keyName: keyInfo.key_name,
|
||||
maskedKey: keyInfo.masked_key,
|
||||
@@ -635,8 +637,8 @@ async function confirmDelete() {
|
||||
deleteConfirmOpen.value = false
|
||||
deletingGroup.value = null
|
||||
emit('refresh')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '删除失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '删除失败'), '错误')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -715,9 +717,8 @@ async function testMapping(item: CombinedMapping, mapping: MappingItem, apiForma
|
||||
} else {
|
||||
showError(`映射测试失败: ${parseTestModelError(result)}`)
|
||||
}
|
||||
} catch (err: any) {
|
||||
const errorMsg = err.response?.data?.detail || err.message || '测试请求失败'
|
||||
showError(`映射测试失败: ${errorMsg}`)
|
||||
} catch (err: unknown) {
|
||||
showError(`映射测试失败: ${parseApiError(err, '测试请求失败')}`)
|
||||
} finally {
|
||||
testingMapping.value = null
|
||||
}
|
||||
@@ -741,9 +742,8 @@ async function testRegexMapping(item: CombinedMapping, keyItem: MatchedKeyInfo,
|
||||
} else {
|
||||
showError(`映射测试失败: ${parseTestModelError(result)}`)
|
||||
}
|
||||
} catch (err: any) {
|
||||
const errorMsg = err.response?.data?.detail || err.message || '测试请求失败'
|
||||
showError(`映射测试失败: ${errorMsg}`)
|
||||
} catch (err: unknown) {
|
||||
showError(`映射测试失败: ${parseApiError(err, '测试请求失败')}`)
|
||||
} finally {
|
||||
testingMapping.value = null
|
||||
}
|
||||
|
||||
@@ -266,7 +266,8 @@ import {
|
||||
type ProviderMappingPreviewResponse
|
||||
} from '@/api/endpoints'
|
||||
import { updateModel } from '@/api/endpoints/models'
|
||||
import { parseTestModelError } from '@/utils/errorParser'
|
||||
import { parseApiError, parseTestModelError } from '@/utils/errorParser'
|
||||
import type { ProviderWithEndpointsSummary } from '@/api/endpoints'
|
||||
|
||||
interface Endpoint {
|
||||
id: string
|
||||
@@ -276,7 +277,7 @@ interface Endpoint {
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
provider: any
|
||||
provider: ProviderWithEndpointsSummary
|
||||
endpoints?: Endpoint[]
|
||||
models?: Model[]
|
||||
mappingPreview?: ProviderMappingPreviewResponse | null
|
||||
@@ -464,8 +465,8 @@ async function toggleModelActive(model: Model) {
|
||||
await updateModel(props.provider.id, model.id, { is_active: newStatus })
|
||||
model.is_active = newStatus
|
||||
showSuccess(newStatus ? '模型已启用' : '模型已停用')
|
||||
} catch (err: any) {
|
||||
showError(err.response?.data?.detail || '操作失败', '错误')
|
||||
} catch (err: unknown) {
|
||||
showError(parseApiError(err, '操作失败'), '错误')
|
||||
} finally {
|
||||
togglingModelId.value = null
|
||||
}
|
||||
@@ -529,9 +530,8 @@ async function testModelConnection(model: Model, apiFormat?: string) {
|
||||
} else {
|
||||
showError(`模型测试失败: ${parseTestModelError(result)}`)
|
||||
}
|
||||
} catch (err: any) {
|
||||
const errorMsg = err.response?.data?.detail || err.message || '测试请求失败'
|
||||
showError(`模型测试失败: ${errorMsg}`)
|
||||
} catch (err: unknown) {
|
||||
showError(`模型测试失败: ${parseApiError(err, '测试请求失败')}`)
|
||||
} finally {
|
||||
testingModelId.value = null
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { ProviderWithEndpointsSummary } from '@/api/endpoints'
|
||||
import { batchQueryBalance, getArchitectures, type ActionResultResponse, type ArchitectureInfo } from '@/api/providerOps'
|
||||
import { formatBalanceExtraFromSchema, type CredentialsSchema } from '@/features/providers/auth-templates/schema-utils'
|
||||
import type { BalanceExtraItem } from '@/features/providers/auth-templates'
|
||||
import { log } from '@/utils/logger'
|
||||
|
||||
const MAX_BALANCE_RETRIES = 3
|
||||
|
||||
@@ -96,7 +97,7 @@ export function useProviderBalance() {
|
||||
pendingTimers.add(timerId)
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[loadBalances] 加载余额数据失败:', e)
|
||||
log.warn('[loadBalances] 加载余额数据失败', e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,7 +128,7 @@ export function useProviderBalance() {
|
||||
pendingTimers.add(timerId)
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[retryPendingBalances] 重试加载余额失败:', e)
|
||||
log.warn('[retryPendingBalances] 重试加载余额失败', e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,7 +166,7 @@ export function useProviderBalance() {
|
||||
if (!result || (result.status !== 'success' && result.status !== 'auth_expired') || !result.data) {
|
||||
return null
|
||||
}
|
||||
const data = result.data as Record<string, any>
|
||||
const data = result.data as Record<string, unknown>
|
||||
const extra = data.extra
|
||||
if (!extra || extra.balance === undefined || extra.points === undefined) {
|
||||
return null
|
||||
@@ -216,7 +217,7 @@ export function useProviderBalance() {
|
||||
if (!result || result.status !== 'success' || !result.data) {
|
||||
return null
|
||||
}
|
||||
const data = result.data as Record<string, any>
|
||||
const data = result.data as Record<string, unknown>
|
||||
const extra = data.extra
|
||||
if (!extra || extra.checkin_success === undefined) {
|
||||
return null
|
||||
@@ -236,7 +237,7 @@ export function useProviderBalance() {
|
||||
if (result.status !== 'success' && result.status !== 'auth_expired') {
|
||||
return null
|
||||
}
|
||||
const data = result.data as Record<string, any>
|
||||
const data = result.data as Record<string, unknown>
|
||||
const extra = data.extra
|
||||
if (!extra || !extra.cookie_expired) {
|
||||
return null
|
||||
@@ -288,7 +289,7 @@ export function useProviderBalance() {
|
||||
return []
|
||||
}
|
||||
|
||||
const data = result.data as Record<string, any>
|
||||
const data = result.data as Record<string, unknown>
|
||||
const extra = data.extra
|
||||
if (!extra) return []
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* 缓存已移至后端(Redis),前端只保留并发请求去重,避免同时发多个相同请求。
|
||||
*/
|
||||
import { ref } from 'vue'
|
||||
import { isAxiosError } from 'axios'
|
||||
import { adminApi } from '@/api/admin'
|
||||
import { parseUpstreamModelError } from '@/utils/errorParser'
|
||||
import type { UpstreamModel } from '@/api/endpoints/types'
|
||||
@@ -42,6 +43,7 @@ export function useUpstreamModelsCache() {
|
||||
|
||||
// 强制刷新时不复用进行中的请求
|
||||
if (!forceRefresh && pendingRequests.has(requestKey)) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
return pendingRequests.get(requestKey)!
|
||||
}
|
||||
|
||||
@@ -62,9 +64,9 @@ export function useUpstreamModelsCache() {
|
||||
const rawError = response.data?.error || '获取上游模型失败'
|
||||
return { models: [], error: parseUpstreamModelError(rawError) }
|
||||
}
|
||||
} catch (err: any) {
|
||||
const rawError = err.response?.data?.detail || err.message || '获取上游模型失败'
|
||||
return { models: [], error: parseUpstreamModelError(rawError) }
|
||||
} catch (err: unknown) {
|
||||
const rawError = isAxiosError(err) ? (err.response?.data?.detail ?? err.message) : (err instanceof Error ? err.message : String(err))
|
||||
return { models: [], error: parseUpstreamModelError(rawError || '获取上游模型失败') }
|
||||
} finally {
|
||||
loadingMap.value.set(requestKey, false)
|
||||
pendingRequests.delete(requestKey)
|
||||
|
||||
@@ -371,6 +371,7 @@ import Skeleton from '@/components/ui/skeleton.vue'
|
||||
import { ChevronLeft, ChevronRight, ExternalLink } from 'lucide-vue-next'
|
||||
import { requestTraceApi, type RequestTrace, type CandidateRecord } from '@/api/requestTrace'
|
||||
import { log } from '@/utils/logger'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { formatApiFormat } from '@/api/endpoints/types/api-format'
|
||||
|
||||
// 节点组类型
|
||||
@@ -459,8 +460,10 @@ const getFinalStatusLabel = (status: string) => {
|
||||
}
|
||||
|
||||
// 获取最终状态徽章样式
|
||||
const getFinalStatusBadgeVariant = (status: string): any => {
|
||||
const variants: Record<string, string> = {
|
||||
type BadgeVariant = 'default' | 'secondary' | 'destructive' | 'outline' | 'success' | 'warning' | 'dark'
|
||||
|
||||
const getFinalStatusBadgeVariant = (status: string): BadgeVariant => {
|
||||
const variants: Record<string, BadgeVariant> = {
|
||||
success: 'success',
|
||||
failed: 'destructive',
|
||||
streaming: 'secondary',
|
||||
@@ -493,19 +496,19 @@ const formatSize = (bytes: number): string => {
|
||||
}
|
||||
|
||||
// 代理 timing 分阶段展示
|
||||
const proxyTimingBreakdown = (proxy: Record<string, any>): string => {
|
||||
const t = proxy.timing
|
||||
const proxyTimingBreakdown = (proxy: Record<string, unknown>): string => {
|
||||
const t = proxy.timing as Record<string, number | null | undefined> | undefined
|
||||
if (!t) return ''
|
||||
|
||||
const parts: string[] = []
|
||||
|
||||
// 兼容旧版 timing(含 body_read_ms/decompress_ms)
|
||||
const readDecompress = (t.body_read_ms || 0) + (t.decompress_ms || 0)
|
||||
const readDecompress = ((t.body_read_ms as number) || 0) + ((t.decompress_ms as number) || 0)
|
||||
if (readDecompress > 0) {
|
||||
let label = `读取 ${formatLatency(readDecompress)}`
|
||||
if (t.decompress_ms != null && t.decompress_ms > 0 && t.wire_size != null && t.body_size != null && t.body_size > 0) {
|
||||
const ratio = Math.round((1 - t.wire_size / t.body_size) * 100)
|
||||
label += ` ${formatSize(t.wire_size)}→${formatSize(t.body_size)}`
|
||||
if (t.decompress_ms != null && t.decompress_ms > 0 && t.wire_size != null && t.body_size != null && (t.body_size as number) > 0) {
|
||||
const ratio = Math.round((1 - (t.wire_size as number) / (t.body_size as number)) * 100)
|
||||
label += ` ${formatSize(t.wire_size as number)}→${formatSize(t.body_size as number)}`
|
||||
if (ratio > 0) label += ` -${ratio}%`
|
||||
}
|
||||
parts.push(label)
|
||||
@@ -514,29 +517,29 @@ const proxyTimingBreakdown = (proxy: Record<string, any>): string => {
|
||||
const ttfbMs = t.ttfb_ms ?? t.upstream_ms
|
||||
const processingMs = t.upstream_processing_ms ?? (
|
||||
ttfbMs != null && t.connect_ms != null && t.tls_ms != null
|
||||
? Math.max(0, ttfbMs - t.connect_ms - t.tls_ms)
|
||||
? Math.max(0, (ttfbMs as number) - (t.connect_ms as number) - (t.tls_ms as number))
|
||||
: null
|
||||
)
|
||||
|
||||
if (t.dns_ms != null && t.dns_ms > 0) {
|
||||
parts.push(`DNS ${formatLatency(t.dns_ms)}`)
|
||||
if (t.dns_ms != null && (t.dns_ms as number) > 0) {
|
||||
parts.push(`DNS ${formatLatency(t.dns_ms as number)}`)
|
||||
}
|
||||
if (t.connect_ms != null && t.connect_ms > 0) {
|
||||
parts.push(`连接 ${formatLatency(t.connect_ms)}`)
|
||||
if (t.connect_ms != null && (t.connect_ms as number) > 0) {
|
||||
parts.push(`连接 ${formatLatency(t.connect_ms as number)}`)
|
||||
}
|
||||
if (t.tls_ms != null && t.tls_ms > 0) {
|
||||
parts.push(`TLS ${formatLatency(t.tls_ms)}`)
|
||||
if (t.tls_ms != null && (t.tls_ms as number) > 0) {
|
||||
parts.push(`TLS ${formatLatency(t.tls_ms as number)}`)
|
||||
}
|
||||
if (ttfbMs != null && ttfbMs > 0) {
|
||||
parts.push(`TTFB ${formatLatency(ttfbMs)}`)
|
||||
if (ttfbMs != null && (ttfbMs as number) > 0) {
|
||||
parts.push(`TTFB ${formatLatency(ttfbMs as number)}`)
|
||||
}
|
||||
if (processingMs != null && processingMs > 0) {
|
||||
parts.push(`上游处理 ${formatLatency(Math.round(processingMs))}`)
|
||||
if (processingMs != null && (processingMs as number) > 0) {
|
||||
parts.push(`上游处理 ${formatLatency(Math.round(processingMs as number))}`)
|
||||
}
|
||||
|
||||
// 计算 Aether→代理 之间无法解释的耗时差
|
||||
if (proxy.ttfb_ms != null && t.total_ms != null) {
|
||||
const gap = proxy.ttfb_ms - t.total_ms
|
||||
const gap = (proxy.ttfb_ms as number) - (t.total_ms as number)
|
||||
if (gap > 500) {
|
||||
parts.push(`传输 ${formatLatency(Math.round(gap))}`)
|
||||
}
|
||||
@@ -817,9 +820,9 @@ const loadTrace = async (silent = false) => {
|
||||
|
||||
try {
|
||||
trace.value = await requestTraceApi.getRequestTrace(props.requestId)
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
if (!silent) {
|
||||
error.value = err.response?.data?.detail || err.message || '加载失败'
|
||||
error.value = parseApiError(err, '加载失败')
|
||||
}
|
||||
log.error('加载请求追踪失败:', err)
|
||||
} finally {
|
||||
|
||||
@@ -699,6 +699,7 @@ const autoRefreshing = ref(false)
|
||||
const curlCopying = ref(false)
|
||||
const curlCopied = ref(false)
|
||||
const replayDialogOpen = ref(false)
|
||||
const AUTO_REFRESH_INTERVAL_MS = 1000
|
||||
|
||||
// 监听标签页切换
|
||||
watch(activeTab, (newTab) => {
|
||||
@@ -1010,15 +1011,15 @@ const visibleTabs = computed(() => {
|
||||
return tabs.filter(tab => {
|
||||
switch (tab.name) {
|
||||
case 'request-headers':
|
||||
return hasContent(detail.value!.request_headers)
|
||||
return hasContent(detail.value?.request_headers) || hasContent(detail.value?.provider_request_headers)
|
||||
case 'request-body':
|
||||
return hasContent(detail.value!.request_body) || hasContent(detail.value!.provider_request_body)
|
||||
return hasContent(detail.value?.request_body) || hasContent(detail.value?.provider_request_body)
|
||||
case 'response-headers':
|
||||
return hasContent(detail.value!.response_headers) || hasContent(detail.value!.client_response_headers)
|
||||
return hasContent(detail.value?.response_headers) || hasContent(detail.value?.client_response_headers)
|
||||
case 'response-body':
|
||||
return hasContent(detail.value!.response_body) || hasContent(detail.value!.client_response_body)
|
||||
return hasContent(detail.value?.response_body) || hasContent(detail.value?.client_response_body)
|
||||
case 'metadata':
|
||||
return hasContent(detail.value!.metadata)
|
||||
return hasContent(detail.value?.metadata)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
@@ -1078,6 +1079,15 @@ async function loadDetail(id: string, silent = false) {
|
||||
if (silent) {
|
||||
timelineRef.value?.refresh()
|
||||
}
|
||||
|
||||
// 抽屉打开时,对进行中请求自动保持刷新,保证详情实时更新
|
||||
if (props.isOpen) {
|
||||
if (isRequestCompleted()) {
|
||||
stopAutoRefresh()
|
||||
} else {
|
||||
startAutoRefresh()
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
log.error('Failed to load request detail:', err)
|
||||
if (!silent) {
|
||||
@@ -1108,6 +1118,23 @@ function stopAutoRefresh() {
|
||||
autoRefreshing.value = false
|
||||
}
|
||||
|
||||
function startAutoRefresh() {
|
||||
if (autoRefreshTimer.value || !props.requestId || !props.isOpen) {
|
||||
return
|
||||
}
|
||||
autoRefreshing.value = true
|
||||
autoRefreshTimer.value = setInterval(async () => {
|
||||
if (!props.requestId || !props.isOpen) {
|
||||
stopAutoRefresh()
|
||||
return
|
||||
}
|
||||
await loadDetail(props.requestId, true)
|
||||
if (isRequestCompleted()) {
|
||||
stopAutoRefresh()
|
||||
}
|
||||
}, AUTO_REFRESH_INTERVAL_MS)
|
||||
}
|
||||
|
||||
async function refreshDetail() {
|
||||
if (!props.requestId) return
|
||||
|
||||
@@ -1132,16 +1159,7 @@ async function refreshDetail() {
|
||||
return
|
||||
}
|
||||
|
||||
autoRefreshTimer.value = setInterval(async () => {
|
||||
if (!props.requestId || !props.isOpen) {
|
||||
stopAutoRefresh()
|
||||
return
|
||||
}
|
||||
await loadDetail(props.requestId, true)
|
||||
if (isRequestCompleted()) {
|
||||
stopAutoRefresh()
|
||||
}
|
||||
}, 1000)
|
||||
startAutoRefresh()
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
@@ -1300,7 +1318,7 @@ function copyContent(tabName: string) {
|
||||
}
|
||||
} else {
|
||||
// JSON 视图模式:复制原始 JSON
|
||||
let data: any = null
|
||||
let data: unknown = null
|
||||
switch (tabName) {
|
||||
case 'request-headers':
|
||||
data = dataSource.value === 'provider'
|
||||
@@ -1380,8 +1398,8 @@ function openReplayDialog() {
|
||||
interface HeaderEntry {
|
||||
key: string
|
||||
status: 'added' | 'modified' | 'removed' | 'unchanged'
|
||||
originalValue?: any
|
||||
newValue?: any
|
||||
originalValue?: unknown
|
||||
newValue?: unknown
|
||||
}
|
||||
|
||||
const mergedHeaderEntries = computed(() => {
|
||||
|
||||
@@ -17,17 +17,17 @@
|
||||
</Card>
|
||||
<!-- 非 JSON 响应(如 HTML 错误页面) -->
|
||||
<Card
|
||||
v-else-if="data.raw_response && data.metadata?.parse_error"
|
||||
v-else-if="hasParseError"
|
||||
class="bg-muted/30 overflow-hidden"
|
||||
>
|
||||
<div class="p-3 bg-amber-50 dark:bg-amber-900/20 border-b border-amber-200 dark:border-amber-800">
|
||||
<div class="flex items-start gap-2">
|
||||
<span class="text-amber-600 dark:text-amber-400 text-sm font-medium">Warning: 响应解析失败</span>
|
||||
<span class="text-xs text-amber-700 dark:text-amber-300">{{ data.metadata.parse_error }}</span>
|
||||
<span class="text-xs text-amber-700 dark:text-amber-300">{{ parseErrorMessage }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-4 overflow-x-auto max-h-[500px] overflow-y-auto">
|
||||
<pre class="text-xs font-mono whitespace-pre-wrap text-muted-foreground">{{ data.raw_response }}</pre>
|
||||
<pre class="text-xs font-mono whitespace-pre-wrap text-muted-foreground">{{ rawResponseContent }}</pre>
|
||||
</div>
|
||||
</Card>
|
||||
<Card
|
||||
@@ -74,12 +74,14 @@
|
||||
:style="{ width: `${line.indent * 16}px` }"
|
||||
/>
|
||||
<!-- 内容 -->
|
||||
<!-- eslint-disable vue/no-v-html -->
|
||||
<span
|
||||
class="line-content"
|
||||
:class="{ 'clickable-collapsed': line.canFold && collapsedBlocks.has(line.blockId) }"
|
||||
@click="line.canFold && collapsedBlocks.has(line.blockId) && toggleFold(line.blockId)"
|
||||
v-html="getDisplayHtml(line)"
|
||||
/>
|
||||
<!-- eslint-enable vue/no-v-html -->
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -112,14 +114,47 @@ interface DisplayLine extends JsonLine {
|
||||
displayLineNumber: number
|
||||
}
|
||||
|
||||
/** JSON data can be any serializable value: object, array, string, number, boolean, null */
|
||||
type JsonValue = Record<string, unknown> | unknown[] | string | number | boolean | null | undefined
|
||||
|
||||
const props = defineProps<{
|
||||
data: any
|
||||
data: JsonValue
|
||||
viewMode: 'formatted' | 'raw' | 'compare'
|
||||
expandDepth: number
|
||||
isDark: boolean
|
||||
emptyMessage: string
|
||||
}>()
|
||||
|
||||
/** Safely cast data to an object for property access in templates */
|
||||
const dataAsObject = computed(() => {
|
||||
if (props.data && typeof props.data === 'object' && !Array.isArray(props.data)) {
|
||||
return props.data as Record<string, unknown>
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
/** Whether the data contains a raw_response with a parse error (non-JSON response) */
|
||||
const hasParseError = computed(() => {
|
||||
const obj = dataAsObject.value
|
||||
if (!obj) return false
|
||||
const metadata = obj.metadata as Record<string, unknown> | undefined
|
||||
return Boolean(obj.raw_response && metadata?.parse_error)
|
||||
})
|
||||
|
||||
/** Parse error message */
|
||||
const parseErrorMessage = computed(() => {
|
||||
const obj = dataAsObject.value
|
||||
if (!obj) return ''
|
||||
const metadata = obj.metadata as Record<string, unknown> | undefined
|
||||
return String(metadata?.parse_error || '')
|
||||
})
|
||||
|
||||
/** Raw response content */
|
||||
const rawResponseContent = computed(() => {
|
||||
const obj = dataAsObject.value
|
||||
return obj ? String(obj.raw_response || '') : ''
|
||||
})
|
||||
|
||||
const collapsedBlocks = ref<Set<string>>(new Set())
|
||||
const lines = ref<JsonLine[]>([])
|
||||
|
||||
@@ -145,14 +180,14 @@ const escapeHtml = (str: string): string => {
|
||||
.replace(/"/g, '"')
|
||||
}
|
||||
|
||||
const parseJsonToLines = (data: any): JsonLine[] => {
|
||||
const parseJsonToLines = (data: unknown): JsonLine[] => {
|
||||
const result: JsonLine[] = []
|
||||
let lineNumber = 1
|
||||
let blockIdCounter = 0
|
||||
|
||||
const getBlockId = () => `block-${blockIdCounter++}`
|
||||
|
||||
const processValue = (value: any, indent: number, isLast: boolean, keyPrefix: string = ''): void => {
|
||||
const processValue = (value: unknown, indent: number, isLast: boolean, keyPrefix: string = ''): void => {
|
||||
const comma = isLast ? '' : ','
|
||||
|
||||
if (value === null) {
|
||||
@@ -232,7 +267,8 @@ const parseJsonToLines = (data: any): JsonLine[] => {
|
||||
result[startLine].blockEnd = result.length - 1
|
||||
}
|
||||
} else if (typeof value === 'object') {
|
||||
const keys = Object.keys(value)
|
||||
const obj = value as Record<string, unknown>
|
||||
const keys = Object.keys(obj)
|
||||
if (keys.length === 0) {
|
||||
result.push({
|
||||
id: result.length,
|
||||
@@ -259,7 +295,7 @@ const parseJsonToLines = (data: any): JsonLine[] => {
|
||||
|
||||
keys.forEach((key, i) => {
|
||||
const keyHtml = getTokenHtml(`"${escapeHtml(key)}"`, 'key') + getTokenHtml(': ', 'punctuation')
|
||||
processValue(value[key], indent + 1, i === keys.length - 1, keyHtml)
|
||||
processValue(obj[key], indent + 1, i === keys.length - 1, keyHtml)
|
||||
})
|
||||
|
||||
result.push({
|
||||
|
||||
@@ -165,11 +165,11 @@ const props = defineProps<{
|
||||
detail: RequestDetail
|
||||
viewMode: 'compare' | 'formatted' | 'raw'
|
||||
dataSource: 'client' | 'provider'
|
||||
currentHeaderData: any
|
||||
currentHeaderData: Record<string, unknown> | null
|
||||
currentExpandDepth: number
|
||||
hasProviderHeaders: boolean
|
||||
clientHeadersWithDiff: Array<{ key: string; value: any; status: string }>
|
||||
providerHeadersWithDiff: Array<{ key: string; value: any; status: string }>
|
||||
clientHeadersWithDiff: Array<{ key: string; value: unknown; status: string }>
|
||||
providerHeadersWithDiff: Array<{ key: string; value: unknown; status: string }>
|
||||
headerStats: { added: number; modified: number; removed: number; unchanged: number }
|
||||
isDark: boolean
|
||||
}>()
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
} from '../types'
|
||||
import { createDefaultStats } from '../types'
|
||||
import { log } from '@/utils/logger'
|
||||
import { getErrorStatus } from '@/types/api-error'
|
||||
|
||||
export interface UseUsageDataOptions {
|
||||
isAdminPage: Ref<boolean>
|
||||
@@ -81,27 +82,31 @@ export function useUsageData(options: UseUsageDataOptions) {
|
||||
usageApi.getUsageByApiFormat(dateRange)
|
||||
])
|
||||
|
||||
// statsData may contain additional fields not declared in UsageStats
|
||||
const statsRaw = statsData as Record<string, unknown>
|
||||
stats.value = {
|
||||
total_requests: statsData.total_requests || 0,
|
||||
total_tokens: statsData.total_tokens || 0,
|
||||
total_cost: statsData.total_cost || 0,
|
||||
total_actual_cost: (statsData as any).total_actual_cost,
|
||||
total_actual_cost: statsData.total_actual_cost,
|
||||
avg_response_time: statsData.avg_response_time || 0,
|
||||
error_count: (statsData as any).error_count,
|
||||
error_rate: (statsData as any).error_rate,
|
||||
cache_stats: (statsData as any).cache_stats,
|
||||
error_count: typeof statsRaw.error_count === 'number' ? statsRaw.error_count : undefined,
|
||||
error_rate: typeof statsRaw.error_rate === 'number' ? statsRaw.error_rate : undefined,
|
||||
cache_stats: statsRaw.cache_stats as UsageStatsState['cache_stats'],
|
||||
period_start: '',
|
||||
period_end: '',
|
||||
activity_heatmap: null
|
||||
}
|
||||
|
||||
modelStats.value = modelData.map(item => ({
|
||||
model: item.model,
|
||||
request_count: item.request_count || 0,
|
||||
total_tokens: item.total_tokens || 0,
|
||||
total_cost: item.total_cost || 0,
|
||||
actual_cost: (item as any).actual_cost
|
||||
}))
|
||||
modelStats.value = modelData.map(item => {
|
||||
const raw = item as Record<string, unknown>
|
||||
return {
|
||||
model: item.model,
|
||||
request_count: item.request_count || 0,
|
||||
total_tokens: item.total_tokens || 0,
|
||||
total_cost: item.total_cost || 0,
|
||||
actual_cost: typeof raw.actual_cost === 'number' ? raw.actual_cost : undefined
|
||||
}
|
||||
})
|
||||
|
||||
providerStats.value = providerData.map(item => ({
|
||||
provider: item.provider,
|
||||
@@ -142,10 +147,9 @@ export function useUsageData(options: UseUsageDataOptions) {
|
||||
avg_response_time: userData.avg_response_time || 0,
|
||||
period_start: '',
|
||||
period_end: '',
|
||||
activity_heatmap: null
|
||||
}
|
||||
|
||||
modelStats.value = (userData.summary_by_model || []).map((item: any) => ({
|
||||
modelStats.value = (userData.summary_by_model || []).map((item) => ({
|
||||
model: item.model,
|
||||
request_count: item.requests || 0,
|
||||
total_tokens: item.total_tokens || 0,
|
||||
@@ -153,13 +157,14 @@ export function useUsageData(options: UseUsageDataOptions) {
|
||||
actual_cost: item.actual_total_cost_usd
|
||||
}))
|
||||
|
||||
providerStats.value = (userData.summary_by_provider || []).map((item: any) => ({
|
||||
providerStats.value = (userData.summary_by_provider || []).map((item) => ({
|
||||
provider: item.provider,
|
||||
requests: item.requests || 0,
|
||||
totalTokens: 0,
|
||||
totalCost: item.total_cost_usd || 0,
|
||||
successRate: item.success_rate || 0,
|
||||
avgResponseTime: item.avg_response_time_ms > 0
|
||||
? `${(item.avg_response_time_ms / 1000).toFixed(2)}s`
|
||||
avgResponseTime: (item.avg_response_time_ms ?? 0) > 0
|
||||
? `${((item.avg_response_time_ms ?? 0) / 1000).toFixed(2)}s`
|
||||
: '-'
|
||||
}))
|
||||
|
||||
@@ -221,8 +226,8 @@ export function useUsageData(options: UseUsageDataOptions) {
|
||||
})
|
||||
.sort((a, b) => b.request_count - a.request_count)
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error.response?.status !== 403) {
|
||||
} catch (error: unknown) {
|
||||
if (getErrorStatus(error) !== 403) {
|
||||
log.error('加载统计数据失败:', error)
|
||||
}
|
||||
stats.value = createDefaultStats()
|
||||
@@ -244,7 +249,7 @@ export function useUsageData(options: UseUsageDataOptions) {
|
||||
const offset = (pagination.page - 1) * pagination.pageSize
|
||||
|
||||
// 构建请求参数
|
||||
const params: any = {
|
||||
const params: Record<string, unknown> = {
|
||||
limit: pagination.pageSize,
|
||||
offset,
|
||||
...currentDateRange.value
|
||||
|
||||
@@ -33,6 +33,9 @@ import {
|
||||
createEmptyRenderResult,
|
||||
} from './render'
|
||||
|
||||
/** Raw JSON object from API (loosely typed) */
|
||||
type RawObject = Record<string, unknown>
|
||||
|
||||
/**
|
||||
* Claude API 格式解析器
|
||||
*/
|
||||
@@ -43,7 +46,7 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 检测是否为 Claude 格式
|
||||
*/
|
||||
detect(requestBody: any, responseBody: any, hint?: string): number {
|
||||
detect(requestBody: unknown, responseBody: unknown, hint?: string): number {
|
||||
// 1. 后端提示优先
|
||||
if (hint) {
|
||||
const lowerHint = hint.toLowerCase()
|
||||
@@ -52,37 +55,41 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
if (lowerHint.includes('openai') || lowerHint.includes('gemini')) return 0
|
||||
}
|
||||
|
||||
const req = requestBody as RawObject | null | undefined
|
||||
|
||||
// 2. 检查模型名
|
||||
const model = requestBody?.model?.toLowerCase() || ''
|
||||
const model = (typeof req?.model === 'string' ? req.model : '').toLowerCase()
|
||||
if (model.includes('claude')) return 95
|
||||
|
||||
// 3. 检查请求体结构
|
||||
if (!requestBody?.messages || !Array.isArray(requestBody.messages)) {
|
||||
if (!req?.messages || !Array.isArray(req.messages)) {
|
||||
return 0
|
||||
}
|
||||
|
||||
// 4. 检查响应体特征
|
||||
const respBody = isStreamResponse(responseBody)
|
||||
? responseBody.chunks?.[0]
|
||||
: responseBody
|
||||
const respBody = (isStreamResponse(responseBody)
|
||||
? (responseBody.chunks?.[0] as RawObject | undefined)
|
||||
: responseBody) as RawObject | null | undefined
|
||||
|
||||
if (respBody) {
|
||||
// Claude 响应特征
|
||||
const respType = typeof respBody.type === 'string' ? respBody.type : ''
|
||||
if (
|
||||
respBody.type === 'message' ||
|
||||
respBody.type?.startsWith('content_block') ||
|
||||
respBody.type?.startsWith('message_')
|
||||
respType === 'message' ||
|
||||
respType.startsWith('content_block') ||
|
||||
respType.startsWith('message_')
|
||||
) {
|
||||
return 90
|
||||
}
|
||||
// 明确是 OpenAI 格式
|
||||
if (respBody.choices || respBody.object?.includes('chat.completion')) {
|
||||
const respObject = typeof respBody.object === 'string' ? respBody.object : ''
|
||||
if (respBody.choices || respObject.includes('chat.completion')) {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 检查 Claude 特有的请求字段
|
||||
if (requestBody.system !== undefined) {
|
||||
if (req.system !== undefined) {
|
||||
// system 可以是字符串或数组,这是 Claude 的特征
|
||||
return 70
|
||||
}
|
||||
@@ -94,26 +101,27 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析请求体
|
||||
*/
|
||||
parseRequest(requestBody: any): ParsedConversation {
|
||||
parseRequest(requestBody: unknown): ParsedConversation {
|
||||
if (!requestBody) {
|
||||
return createEmptyConversation('claude', '无请求体')
|
||||
}
|
||||
|
||||
try {
|
||||
const body = requestBody as RawObject
|
||||
const result: ParsedConversation = {
|
||||
messages: [],
|
||||
isStream: requestBody.stream === true,
|
||||
isStream: body.stream === true,
|
||||
apiFormat: 'claude',
|
||||
model: requestBody.model,
|
||||
model: typeof body.model === 'string' ? body.model : undefined,
|
||||
}
|
||||
|
||||
// 提取 system prompt
|
||||
result.system = this.extractSystemPrompt(requestBody.system)
|
||||
result.system = this.extractSystemPrompt(body.system)
|
||||
|
||||
// 提取 messages
|
||||
if (Array.isArray(requestBody.messages)) {
|
||||
for (const msg of requestBody.messages) {
|
||||
const parsedMsg = this.parseMessage(msg)
|
||||
if (Array.isArray(body.messages)) {
|
||||
for (const msg of body.messages) {
|
||||
const parsedMsg = this.parseMessage(msg as RawObject)
|
||||
if (parsedMsg) {
|
||||
result.messages.push(parsedMsg)
|
||||
}
|
||||
@@ -129,22 +137,23 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析响应体
|
||||
*/
|
||||
parseResponse(responseBody: any): ParsedConversation {
|
||||
parseResponse(responseBody: unknown): ParsedConversation {
|
||||
if (!responseBody) {
|
||||
return createEmptyConversation('claude', '无响应体')
|
||||
}
|
||||
|
||||
try {
|
||||
const body = responseBody as RawObject
|
||||
const result: ParsedConversation = {
|
||||
messages: [],
|
||||
isStream: false,
|
||||
apiFormat: 'claude',
|
||||
model: responseBody.model,
|
||||
model: typeof body.model === 'string' ? body.model : undefined,
|
||||
}
|
||||
|
||||
// Claude 响应格式: { type: "message", content: [...] }
|
||||
if (Array.isArray(responseBody.content)) {
|
||||
const contentBlocks = this.parseContentBlocks(responseBody.content, 'assistant')
|
||||
if (Array.isArray(body.content)) {
|
||||
const contentBlocks = this.parseContentBlocks(body.content as RawObject[], 'assistant')
|
||||
if (contentBlocks.length > 0) {
|
||||
result.messages.push(createMessage('assistant', contentBlocks))
|
||||
}
|
||||
@@ -159,7 +168,7 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析流式响应
|
||||
*/
|
||||
parseStreamResponse(chunks: any[]): ParsedConversation {
|
||||
parseStreamResponse(chunks: unknown[]): ParsedConversation {
|
||||
if (!chunks || chunks.length === 0) {
|
||||
return createEmptyConversation('claude', '无响应数据')
|
||||
}
|
||||
@@ -175,47 +184,49 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
const blocks = new Map<number, {
|
||||
type: ContentBlock['type']
|
||||
parts: string[]
|
||||
metadata?: any
|
||||
metadata?: Record<string, string>
|
||||
}>()
|
||||
|
||||
for (const chunk of chunks) {
|
||||
for (const rawChunk of chunks) {
|
||||
const chunk = rawChunk as RawObject
|
||||
// 提取模型名
|
||||
if (chunk.message?.model && !result.model) {
|
||||
result.model = chunk.message.model
|
||||
const chunkMessage = chunk.message as RawObject | undefined
|
||||
if (typeof chunkMessage?.model === 'string' && !result.model) {
|
||||
result.model = chunkMessage.model
|
||||
}
|
||||
|
||||
if (chunk.type === 'content_block_start') {
|
||||
const index = chunk.index ?? 0
|
||||
const block = chunk.content_block
|
||||
const index = (typeof chunk.index === 'number' ? chunk.index : 0)
|
||||
const block = chunk.content_block as RawObject | undefined
|
||||
if (block?.type === 'text') {
|
||||
blocks.set(index, { type: 'text', parts: [block.text || ''] })
|
||||
blocks.set(index, { type: 'text', parts: [String(block.text || '')] })
|
||||
} else if (block?.type === 'thinking') {
|
||||
blocks.set(index, {
|
||||
type: 'thinking',
|
||||
parts: [block.thinking || ''],
|
||||
metadata: { signature: block.signature },
|
||||
parts: [String(block.thinking || '')],
|
||||
metadata: { signature: String(block.signature || '') },
|
||||
})
|
||||
} else if (block?.type === 'tool_use') {
|
||||
blocks.set(index, {
|
||||
type: 'tool_use',
|
||||
parts: [],
|
||||
metadata: { toolName: block.name, toolId: block.id },
|
||||
metadata: { toolName: String(block.name || ''), toolId: String(block.id || '') },
|
||||
})
|
||||
}
|
||||
} else if (chunk.type === 'content_block_delta') {
|
||||
const index = chunk.index ?? 0
|
||||
const delta = chunk.delta
|
||||
const index = (typeof chunk.index === 'number' ? chunk.index : 0)
|
||||
const delta = chunk.delta as RawObject | undefined
|
||||
const block = blocks.get(index)
|
||||
if (block) {
|
||||
if (delta?.type === 'text_delta') {
|
||||
block.parts.push(delta.text || '')
|
||||
} else if (delta?.type === 'thinking_delta') {
|
||||
block.parts.push(delta.thinking || '')
|
||||
} else if (delta?.type === 'input_json_delta') {
|
||||
block.parts.push(delta.partial_json || '')
|
||||
} else if (delta?.type === 'signature_delta') {
|
||||
if (block && delta) {
|
||||
if (delta.type === 'text_delta') {
|
||||
block.parts.push(String(delta.text || ''))
|
||||
} else if (delta.type === 'thinking_delta') {
|
||||
block.parts.push(String(delta.thinking || ''))
|
||||
} else if (delta.type === 'input_json_delta') {
|
||||
block.parts.push(String(delta.partial_json || ''))
|
||||
} else if (delta.type === 'signature_delta') {
|
||||
block.metadata = block.metadata || {}
|
||||
block.metadata.signature = (block.metadata.signature || '') + (delta.signature || '')
|
||||
block.metadata.signature = (block.metadata.signature || '') + String(delta.signature || '')
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -258,7 +269,7 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 提取 system prompt
|
||||
*/
|
||||
private extractSystemPrompt(system: any): string | undefined {
|
||||
private extractSystemPrompt(system: unknown): string | undefined {
|
||||
if (!system) return undefined
|
||||
|
||||
if (typeof system === 'string') {
|
||||
@@ -267,8 +278,8 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
|
||||
if (Array.isArray(system)) {
|
||||
return system
|
||||
.filter((b: any) => b.type === 'text')
|
||||
.map((b: any) => b.text)
|
||||
.filter((b: RawObject) => b.type === 'text')
|
||||
.map((b: RawObject) => String(b.text || ''))
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
@@ -278,7 +289,7 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析单条消息
|
||||
*/
|
||||
private parseMessage(msg: any): ParsedMessage | null {
|
||||
private parseMessage(msg: RawObject): ParsedMessage | null {
|
||||
if (!msg || !msg.role) return null
|
||||
|
||||
const role = msg.role as MessageRole
|
||||
@@ -292,13 +303,13 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析消息内容
|
||||
*/
|
||||
private parseMessageContent(content: any, role: MessageRole): ContentBlock[] {
|
||||
private parseMessageContent(content: unknown, role: MessageRole): ContentBlock[] {
|
||||
if (typeof content === 'string') {
|
||||
return [createTextBlock(content)]
|
||||
}
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
return this.parseContentBlocks(content, role)
|
||||
return this.parseContentBlocks(content as RawObject[], role)
|
||||
}
|
||||
|
||||
return []
|
||||
@@ -307,7 +318,7 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析内容块数组
|
||||
*/
|
||||
private parseContentBlocks(blocks: any[], role: MessageRole): ContentBlock[] {
|
||||
private parseContentBlocks(blocks: RawObject[], role: MessageRole): ContentBlock[] {
|
||||
const result: ContentBlock[] = []
|
||||
|
||||
for (const block of blocks) {
|
||||
@@ -323,28 +334,31 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析单个内容块
|
||||
*/
|
||||
private parseContentBlock(block: any, _role: MessageRole): ContentBlock | null {
|
||||
private parseContentBlock(block: RawObject, _role: MessageRole): ContentBlock | null {
|
||||
if (!block || !block.type) return null
|
||||
|
||||
switch (block.type) {
|
||||
case 'text':
|
||||
return createTextBlock(block.text || '')
|
||||
return createTextBlock(String(block.text || ''))
|
||||
|
||||
case 'thinking':
|
||||
return createThinkingBlock(block.thinking || '', block.signature)
|
||||
return createThinkingBlock(
|
||||
String(block.thinking || ''),
|
||||
typeof block.signature === 'string' ? block.signature : undefined
|
||||
)
|
||||
|
||||
case 'tool_use':
|
||||
return createToolUseBlock(
|
||||
block.id || '',
|
||||
block.name || '',
|
||||
block.input || {}
|
||||
String(block.id || ''),
|
||||
String(block.name || ''),
|
||||
(block.input as Record<string, unknown>) || {}
|
||||
)
|
||||
|
||||
case 'tool_result':
|
||||
return createToolResultBlock(
|
||||
block.tool_use_id || '',
|
||||
String(block.tool_use_id || ''),
|
||||
this.parseToolResultContent(block.content),
|
||||
block.is_error
|
||||
block.is_error as boolean | undefined
|
||||
)
|
||||
|
||||
case 'image':
|
||||
@@ -358,23 +372,23 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析图片块
|
||||
*/
|
||||
private parseImageBlock(block: any): ContentBlock | null {
|
||||
const source = block.source
|
||||
private parseImageBlock(block: RawObject): ContentBlock | null {
|
||||
const source = block.source as RawObject | undefined
|
||||
if (!source) {
|
||||
return createImageBlock('base64', { alt: '[图片]' })
|
||||
}
|
||||
|
||||
if (source.type === 'base64') {
|
||||
return createImageBlock('base64', {
|
||||
data: source.data,
|
||||
mimeType: source.media_type,
|
||||
data: typeof source.data === 'string' ? source.data : undefined,
|
||||
mimeType: typeof source.media_type === 'string' ? source.media_type : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
if (source.type === 'url') {
|
||||
return createImageBlock('url', {
|
||||
url: source.url,
|
||||
mimeType: source.media_type,
|
||||
url: typeof source.url === 'string' ? source.url : undefined,
|
||||
mimeType: typeof source.media_type === 'string' ? source.media_type : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -384,16 +398,17 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析工具结果内容
|
||||
*/
|
||||
private parseToolResultContent(content: any): string | ContentBlock[] {
|
||||
private parseToolResultContent(content: unknown): string | ContentBlock[] {
|
||||
if (typeof content === 'string') {
|
||||
return content
|
||||
}
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
const blocks: ContentBlock[] = []
|
||||
for (const item of content) {
|
||||
for (const rawItem of content) {
|
||||
const item = rawItem as RawObject
|
||||
if (item.type === 'text') {
|
||||
blocks.push(createTextBlock(item.text || ''))
|
||||
blocks.push(createTextBlock(String(item.text || '')))
|
||||
} else if (item.type === 'image') {
|
||||
const imgBlock = this.parseImageBlock(item)
|
||||
if (imgBlock) blocks.push(imgBlock)
|
||||
@@ -412,17 +427,18 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染请求体
|
||||
*/
|
||||
renderRequest(requestBody: any): RenderResult {
|
||||
renderRequest(requestBody: unknown): RenderResult {
|
||||
if (!requestBody) {
|
||||
return createEmptyRenderResult('无请求体')
|
||||
}
|
||||
|
||||
try {
|
||||
const body = requestBody as RawObject
|
||||
const blocks: RenderBlock[] = []
|
||||
const isStream = requestBody.stream === true
|
||||
const isStream = body.stream === true
|
||||
|
||||
// 渲染 system prompt
|
||||
const system = this.extractSystemPrompt(requestBody.system)
|
||||
const system = this.extractSystemPrompt(body.system)
|
||||
if (system) {
|
||||
blocks.push(createMessageBlock('system', [
|
||||
createTextRenderBlock(system),
|
||||
@@ -430,9 +446,9 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
}
|
||||
|
||||
// 渲染 messages
|
||||
if (Array.isArray(requestBody.messages)) {
|
||||
for (const msg of requestBody.messages) {
|
||||
const msgBlock = this.renderMessage(msg)
|
||||
if (Array.isArray(body.messages)) {
|
||||
for (const msg of body.messages) {
|
||||
const msgBlock = this.renderMessage(msg as RawObject)
|
||||
if (msgBlock) {
|
||||
blocks.push(msgBlock)
|
||||
}
|
||||
@@ -448,7 +464,7 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染响应体
|
||||
*/
|
||||
renderResponse(responseBody: any): RenderResult {
|
||||
renderResponse(responseBody: unknown): RenderResult {
|
||||
if (!responseBody) {
|
||||
return createEmptyRenderResult('无响应体')
|
||||
}
|
||||
@@ -459,13 +475,15 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
}
|
||||
|
||||
try {
|
||||
const body = responseBody as RawObject
|
||||
const blocks: RenderBlock[] = []
|
||||
|
||||
// Claude 响应格式: { type: "message", content: [...] }
|
||||
if (Array.isArray(responseBody.content)) {
|
||||
const contentBlocks = this.renderContentBlocks(responseBody.content)
|
||||
if (Array.isArray(body.content)) {
|
||||
const rawContent = body.content as RawObject[]
|
||||
const contentBlocks = this.renderContentBlocks(rawContent)
|
||||
if (contentBlocks.length > 0) {
|
||||
const badges = this.getBadgesForContent(responseBody.content)
|
||||
const badges = this.getBadgesForContent(rawContent)
|
||||
blocks.push(createMessageBlock('assistant', contentBlocks, {
|
||||
roleLabel: 'Assistant',
|
||||
badges,
|
||||
@@ -482,7 +500,7 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染流式响应
|
||||
*/
|
||||
private renderStreamResponse(chunks: any[]): RenderResult {
|
||||
private renderStreamResponse(chunks: unknown[]): RenderResult {
|
||||
if (!chunks || chunks.length === 0) {
|
||||
return createEmptyRenderResult('无响应数据')
|
||||
}
|
||||
@@ -517,7 +535,7 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染单条消息
|
||||
*/
|
||||
private renderMessage(msg: any): RenderBlock | null {
|
||||
private renderMessage(msg: RawObject): RenderBlock | null {
|
||||
if (!msg || !msg.role) return null
|
||||
|
||||
const role = msg.role as MessageRole
|
||||
@@ -536,13 +554,13 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染消息内容
|
||||
*/
|
||||
private renderMessageContent(content: any): RenderBlock[] {
|
||||
private renderMessageContent(content: unknown): RenderBlock[] {
|
||||
if (typeof content === 'string') {
|
||||
return [createTextRenderBlock(content)]
|
||||
}
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
return this.renderContentBlocks(content)
|
||||
return this.renderContentBlocks(content as RawObject[])
|
||||
}
|
||||
|
||||
return []
|
||||
@@ -551,7 +569,7 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染原始内容块数组
|
||||
*/
|
||||
private renderContentBlocks(blocks: any[]): RenderBlock[] {
|
||||
private renderContentBlocks(blocks: RawObject[]): RenderBlock[] {
|
||||
const result: RenderBlock[] = []
|
||||
|
||||
for (const block of blocks) {
|
||||
@@ -567,30 +585,30 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染单个原始内容块
|
||||
*/
|
||||
private renderContentBlock(block: any): RenderBlock | null {
|
||||
private renderContentBlock(block: RawObject): RenderBlock | null {
|
||||
if (!block || !block.type) return null
|
||||
|
||||
switch (block.type) {
|
||||
case 'text':
|
||||
return createTextRenderBlock(block.text || '')
|
||||
return createTextRenderBlock(String(block.text || ''))
|
||||
|
||||
case 'thinking':
|
||||
return createCollapsibleBlock(
|
||||
`思考过程 (${(block.thinking || '').length} 字符)`,
|
||||
[createCodeBlock(block.thinking || '')],
|
||||
`思考过程 (${String(block.thinking || '').length} 字符)`,
|
||||
[createCodeBlock(String(block.thinking || ''))],
|
||||
{ defaultOpen: false, className: 'thinking-block' }
|
||||
)
|
||||
|
||||
case 'tool_use':
|
||||
return createToolUseRenderBlock(
|
||||
block.name || '工具调用',
|
||||
String(block.name || '工具调用'),
|
||||
this.formatJson(block.input),
|
||||
block.id
|
||||
typeof block.id === 'string' ? block.id : undefined
|
||||
)
|
||||
|
||||
case 'tool_result': {
|
||||
const content = this.formatToolResultContent(block.content)
|
||||
return createToolResultRenderBlock(content, block.is_error)
|
||||
return createToolResultRenderBlock(content, block.is_error as boolean | undefined)
|
||||
}
|
||||
|
||||
case 'image':
|
||||
@@ -666,8 +684,8 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染图片块
|
||||
*/
|
||||
private renderImageBlock(block: any): RenderBlock | null {
|
||||
const source = block.source
|
||||
private renderImageBlock(block: RawObject): RenderBlock | null {
|
||||
const source = block.source as RawObject | undefined
|
||||
if (!source) {
|
||||
return createImageRenderBlock({ alt: '[图片]' })
|
||||
}
|
||||
@@ -675,14 +693,14 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
if (source.type === 'base64') {
|
||||
return createImageRenderBlock({
|
||||
src: `data:${source.media_type || 'image/png'};base64,${source.data}`,
|
||||
mimeType: source.media_type,
|
||||
mimeType: typeof source.media_type === 'string' ? source.media_type : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
if (source.type === 'url') {
|
||||
return createImageRenderBlock({
|
||||
src: source.url,
|
||||
mimeType: source.media_type,
|
||||
src: typeof source.url === 'string' ? source.url : undefined,
|
||||
mimeType: typeof source.media_type === 'string' ? source.media_type : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -705,11 +723,11 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 获取原始内容的徽章
|
||||
*/
|
||||
private getBadgesForRawContent(content: any): BadgeRenderBlock[] {
|
||||
private getBadgesForRawContent(content: unknown): BadgeRenderBlock[] {
|
||||
if (!Array.isArray(content)) return []
|
||||
|
||||
const badges: BadgeRenderBlock[] = []
|
||||
const types = new Set(content.map((b: any) => b.type))
|
||||
const types = new Set(content.map((b: RawObject) => b.type))
|
||||
|
||||
if (types.has('thinking')) {
|
||||
badges.push(createBadgeBlock('思考', 'secondary'))
|
||||
@@ -730,7 +748,7 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 获取内容的徽章
|
||||
*/
|
||||
private getBadgesForContent(content: any[]): BadgeRenderBlock[] {
|
||||
private getBadgesForContent(content: RawObject[]): BadgeRenderBlock[] {
|
||||
return this.getBadgesForRawContent(content)
|
||||
}
|
||||
|
||||
@@ -760,10 +778,10 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 格式化 JSON
|
||||
*/
|
||||
private formatJson(input: any): string {
|
||||
private formatJson(input: unknown): string {
|
||||
if (typeof input === 'string') {
|
||||
try {
|
||||
const parsed = JSON.parse(input)
|
||||
const parsed = JSON.parse(input) as unknown
|
||||
return JSON.stringify(parsed, null, 2)
|
||||
} catch {
|
||||
return input
|
||||
@@ -775,15 +793,15 @@ export class ClaudeParser implements ApiFormatParser {
|
||||
/**
|
||||
* 格式化工具结果内容
|
||||
*/
|
||||
private formatToolResultContent(content: any): string {
|
||||
private formatToolResultContent(content: unknown): string {
|
||||
if (typeof content === 'string') {
|
||||
return content
|
||||
}
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
return content
|
||||
.map((item: any) => {
|
||||
if (item.type === 'text') return item.text
|
||||
.map((item: RawObject) => {
|
||||
if (item.type === 'text') return String(item.text || '')
|
||||
if (item.type === 'image') return '[图片]'
|
||||
return ''
|
||||
})
|
||||
|
||||
@@ -29,6 +29,9 @@ import {
|
||||
createEmptyRenderResult,
|
||||
} from './render'
|
||||
|
||||
/** Raw JSON object from API (loosely typed) */
|
||||
type RawObject = Record<string, unknown>
|
||||
|
||||
/**
|
||||
* Gemini API 格式解析器
|
||||
*/
|
||||
@@ -39,7 +42,7 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 检测是否为 Gemini 格式
|
||||
*/
|
||||
detect(requestBody: any, responseBody: any, hint?: string): number {
|
||||
detect(requestBody: unknown, responseBody: unknown, hint?: string): number {
|
||||
// 1. 后端提示优先
|
||||
if (hint) {
|
||||
const lowerHint = hint.toLowerCase()
|
||||
@@ -47,19 +50,21 @@ export class GeminiParser implements ApiFormatParser {
|
||||
if (lowerHint.includes('claude') || lowerHint.includes('openai')) return 0
|
||||
}
|
||||
|
||||
const req = requestBody as RawObject | null | undefined
|
||||
|
||||
// 2. 检查模型名
|
||||
const model = requestBody?.model?.toLowerCase() || ''
|
||||
const model = (typeof req?.model === 'string' ? req.model : '').toLowerCase()
|
||||
if (model.includes('gemini')) return 95
|
||||
|
||||
// 3. Gemini 特有结构: 使用 contents 而非 messages
|
||||
if (requestBody?.contents && Array.isArray(requestBody.contents)) {
|
||||
if (req?.contents && Array.isArray(req.contents)) {
|
||||
return 90
|
||||
}
|
||||
|
||||
// 4. 检查响应体特征
|
||||
const respBody = isStreamResponse(responseBody)
|
||||
? responseBody.chunks?.[0]
|
||||
: responseBody
|
||||
const respBody = (isStreamResponse(responseBody)
|
||||
? (responseBody.chunks?.[0] as RawObject | undefined)
|
||||
: responseBody) as RawObject | null | undefined
|
||||
|
||||
if (respBody?.candidates) {
|
||||
return 85
|
||||
@@ -71,32 +76,33 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析请求体
|
||||
*/
|
||||
parseRequest(requestBody: any): ParsedConversation {
|
||||
parseRequest(requestBody: unknown): ParsedConversation {
|
||||
if (!requestBody) {
|
||||
return createEmptyConversation('gemini', '无请求体')
|
||||
}
|
||||
|
||||
try {
|
||||
const body = requestBody as RawObject
|
||||
const result: ParsedConversation = {
|
||||
messages: [],
|
||||
isStream: false,
|
||||
apiFormat: 'gemini',
|
||||
model: requestBody.model,
|
||||
model: typeof body.model === 'string' ? body.model : undefined,
|
||||
}
|
||||
|
||||
// 提取 system instruction
|
||||
const sysInst = requestBody.system_instruction || requestBody.systemInstruction
|
||||
if (sysInst?.parts) {
|
||||
result.system = sysInst.parts
|
||||
.filter((p: any) => p.text)
|
||||
.map((p: any) => p.text)
|
||||
const sysInst = (body.system_instruction || body.systemInstruction) as RawObject | undefined
|
||||
if (sysInst?.parts && Array.isArray(sysInst.parts)) {
|
||||
result.system = (sysInst.parts as RawObject[])
|
||||
.filter((p: RawObject) => typeof p.text === 'string')
|
||||
.map((p: RawObject) => String(p.text))
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
// 提取 contents
|
||||
if (Array.isArray(requestBody.contents)) {
|
||||
for (const content of requestBody.contents) {
|
||||
const parsedMsg = this.parseContent(content)
|
||||
if (Array.isArray(body.contents)) {
|
||||
for (const content of body.contents) {
|
||||
const parsedMsg = this.parseContent(content as RawObject)
|
||||
if (parsedMsg) {
|
||||
result.messages.push(parsedMsg)
|
||||
}
|
||||
@@ -112,12 +118,13 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析响应体
|
||||
*/
|
||||
parseResponse(responseBody: any): ParsedConversation {
|
||||
parseResponse(responseBody: unknown): ParsedConversation {
|
||||
if (!responseBody) {
|
||||
return createEmptyConversation('gemini', '无响应体')
|
||||
}
|
||||
|
||||
try {
|
||||
const body = responseBody as RawObject
|
||||
const result: ParsedConversation = {
|
||||
messages: [],
|
||||
isStream: false,
|
||||
@@ -125,9 +132,11 @@ export class GeminiParser implements ApiFormatParser {
|
||||
}
|
||||
|
||||
// Gemini 响应格式: { candidates: [{ content: { parts: [...] } }] }
|
||||
const candidate = responseBody.candidates?.[0]
|
||||
if (candidate?.content?.parts) {
|
||||
const contentBlocks = this.parseParts(candidate.content.parts)
|
||||
const candidates = body.candidates as RawObject[] | undefined
|
||||
const candidate = candidates?.[0] as RawObject | undefined
|
||||
const candidateContent = candidate?.content as RawObject | undefined
|
||||
if (candidateContent?.parts && Array.isArray(candidateContent.parts)) {
|
||||
const contentBlocks = this.parseParts(candidateContent.parts as RawObject[])
|
||||
if (contentBlocks.length > 0) {
|
||||
result.messages.push(createMessage('assistant', contentBlocks))
|
||||
}
|
||||
@@ -142,7 +151,7 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析流式响应
|
||||
*/
|
||||
parseStreamResponse(chunks: any[]): ParsedConversation {
|
||||
parseStreamResponse(chunks: unknown[]): ParsedConversation {
|
||||
if (!chunks || chunks.length === 0) {
|
||||
return createEmptyConversation('gemini', '无响应数据')
|
||||
}
|
||||
@@ -155,16 +164,24 @@ export class GeminiParser implements ApiFormatParser {
|
||||
}
|
||||
|
||||
const textParts: string[] = []
|
||||
const toolCalls: { name: string; args: any }[] = []
|
||||
const toolCalls: { name: string; args: Record<string, unknown> }[] = []
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const parts = chunk.candidates?.[0]?.content?.parts
|
||||
for (const rawChunk of chunks) {
|
||||
const chunk = rawChunk as RawObject
|
||||
const candidates = chunk.candidates as RawObject[] | undefined
|
||||
const firstCandidate = candidates?.[0] as RawObject | undefined
|
||||
const candidateContent = firstCandidate?.content as RawObject | undefined
|
||||
const parts = candidateContent?.parts as RawObject[] | undefined
|
||||
if (parts) {
|
||||
for (const part of parts) {
|
||||
if (part.text) {
|
||||
if (typeof part.text === 'string') {
|
||||
textParts.push(part.text)
|
||||
} else if (part.functionCall) {
|
||||
toolCalls.push(part.functionCall)
|
||||
const fc = part.functionCall as RawObject
|
||||
toolCalls.push({
|
||||
name: String(fc.name || ''),
|
||||
args: (fc.args as Record<string, unknown>) || {},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -199,11 +216,12 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析 content 对象
|
||||
*/
|
||||
private parseContent(content: any): ParsedMessage | null {
|
||||
private parseContent(content: RawObject): ParsedMessage | null {
|
||||
if (!content) return null
|
||||
|
||||
const role = this.mapRole(content.role)
|
||||
const contentBlocks = this.parseParts(content.parts || [])
|
||||
const role = this.mapRole(typeof content.role === 'string' ? content.role : undefined)
|
||||
const parts = Array.isArray(content.parts) ? content.parts as RawObject[] : []
|
||||
const contentBlocks = this.parseParts(parts)
|
||||
|
||||
if (contentBlocks.length === 0) return null
|
||||
|
||||
@@ -213,7 +231,7 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析 parts 数组
|
||||
*/
|
||||
private parseParts(parts: any[]): ContentBlock[] {
|
||||
private parseParts(parts: RawObject[]): ContentBlock[] {
|
||||
const result: ContentBlock[] = []
|
||||
|
||||
for (const part of parts) {
|
||||
@@ -229,36 +247,39 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析单个 part
|
||||
*/
|
||||
private parsePart(part: any): ContentBlock | null {
|
||||
private parsePart(part: RawObject): ContentBlock | null {
|
||||
if (!part) return null
|
||||
|
||||
// 文本
|
||||
if (part.text !== undefined) {
|
||||
return createTextBlock(part.text)
|
||||
return createTextBlock(String(part.text))
|
||||
}
|
||||
|
||||
// 内联数据(图片等)
|
||||
if (part.inlineData) {
|
||||
const inlineData = part.inlineData as RawObject
|
||||
return createImageBlock('base64', {
|
||||
data: part.inlineData.data,
|
||||
mimeType: part.inlineData.mimeType,
|
||||
data: typeof inlineData.data === 'string' ? inlineData.data : undefined,
|
||||
mimeType: typeof inlineData.mimeType === 'string' ? inlineData.mimeType : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
// 函数调用
|
||||
if (part.functionCall) {
|
||||
const fc = part.functionCall as RawObject
|
||||
return createToolUseBlock(
|
||||
'',
|
||||
part.functionCall.name || '',
|
||||
part.functionCall.args || {}
|
||||
String(fc.name || ''),
|
||||
(fc.args as Record<string, unknown>) || {}
|
||||
)
|
||||
}
|
||||
|
||||
// 函数响应
|
||||
if (part.functionResponse) {
|
||||
const fr = part.functionResponse as RawObject
|
||||
return createToolResultBlock(
|
||||
'', // Gemini 用 name 关联
|
||||
JSON.stringify(part.functionResponse.response, null, 2)
|
||||
JSON.stringify(fr.response, null, 2)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -286,20 +307,21 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染请求体
|
||||
*/
|
||||
renderRequest(requestBody: any): RenderResult {
|
||||
renderRequest(requestBody: unknown): RenderResult {
|
||||
if (!requestBody) {
|
||||
return createEmptyRenderResult('无请求体')
|
||||
}
|
||||
|
||||
try {
|
||||
const body = requestBody as RawObject
|
||||
const blocks: RenderBlock[] = []
|
||||
|
||||
// 渲染 system instruction
|
||||
const sysInst = requestBody.system_instruction || requestBody.systemInstruction
|
||||
if (sysInst?.parts) {
|
||||
const systemText = sysInst.parts
|
||||
.filter((p: any) => p.text)
|
||||
.map((p: any) => p.text)
|
||||
const sysInst = (body.system_instruction || body.systemInstruction) as RawObject | undefined
|
||||
if (sysInst?.parts && Array.isArray(sysInst.parts)) {
|
||||
const systemText = (sysInst.parts as RawObject[])
|
||||
.filter((p: RawObject) => typeof p.text === 'string')
|
||||
.map((p: RawObject) => String(p.text))
|
||||
.join('\n')
|
||||
if (systemText) {
|
||||
blocks.push(createMessageBlock('system', [
|
||||
@@ -309,9 +331,9 @@ export class GeminiParser implements ApiFormatParser {
|
||||
}
|
||||
|
||||
// 渲染 contents
|
||||
if (Array.isArray(requestBody.contents)) {
|
||||
for (const content of requestBody.contents) {
|
||||
const msgBlock = this.renderContent(content)
|
||||
if (Array.isArray(body.contents)) {
|
||||
for (const content of body.contents) {
|
||||
const msgBlock = this.renderContent(content as RawObject)
|
||||
if (msgBlock) {
|
||||
blocks.push(msgBlock)
|
||||
}
|
||||
@@ -327,7 +349,7 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染响应体
|
||||
*/
|
||||
renderResponse(responseBody: any): RenderResult {
|
||||
renderResponse(responseBody: unknown): RenderResult {
|
||||
if (!responseBody) {
|
||||
return createEmptyRenderResult('无响应体')
|
||||
}
|
||||
@@ -338,14 +360,18 @@ export class GeminiParser implements ApiFormatParser {
|
||||
}
|
||||
|
||||
try {
|
||||
const body = responseBody as RawObject
|
||||
const blocks: RenderBlock[] = []
|
||||
|
||||
// Gemini 响应格式: { candidates: [{ content: { parts: [...] } }] }
|
||||
const candidate = responseBody.candidates?.[0]
|
||||
if (candidate?.content?.parts) {
|
||||
const contentBlocks = this.renderParts(candidate.content.parts)
|
||||
const candidates = body.candidates as RawObject[] | undefined
|
||||
const candidate = candidates?.[0] as RawObject | undefined
|
||||
const candidateContent = candidate?.content as RawObject | undefined
|
||||
if (candidateContent?.parts && Array.isArray(candidateContent.parts)) {
|
||||
const parts = candidateContent.parts as RawObject[]
|
||||
const contentBlocks = this.renderParts(parts)
|
||||
if (contentBlocks.length > 0) {
|
||||
const badges = this.getBadgesForParts(candidate.content.parts)
|
||||
const badges = this.getBadgesForParts(parts)
|
||||
blocks.push(createMessageBlock('assistant', contentBlocks, {
|
||||
roleLabel: 'Assistant',
|
||||
badges: badges.length > 0 ? badges : undefined,
|
||||
@@ -362,7 +388,7 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染流式响应
|
||||
*/
|
||||
private renderStreamResponse(chunks: any[]): RenderResult {
|
||||
private renderStreamResponse(chunks: unknown[]): RenderResult {
|
||||
if (!chunks || chunks.length === 0) {
|
||||
return createEmptyRenderResult('无响应数据')
|
||||
}
|
||||
@@ -397,15 +423,16 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染 content 对象
|
||||
*/
|
||||
private renderContent(content: any): RenderBlock | null {
|
||||
private renderContent(content: RawObject): RenderBlock | null {
|
||||
if (!content) return null
|
||||
|
||||
const role = this.mapRole(content.role)
|
||||
const contentBlocks = this.renderParts(content.parts || [])
|
||||
const role = this.mapRole(typeof content.role === 'string' ? content.role : undefined)
|
||||
const parts = Array.isArray(content.parts) ? content.parts as RawObject[] : []
|
||||
const contentBlocks = this.renderParts(parts)
|
||||
|
||||
if (contentBlocks.length === 0) return null
|
||||
|
||||
const badges = this.getBadgesForParts(content.parts || [])
|
||||
const badges = this.getBadgesForParts(parts)
|
||||
|
||||
return createMessageBlock(role, contentBlocks, {
|
||||
roleLabel: this.getRoleLabel(role),
|
||||
@@ -416,7 +443,7 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染 parts 数组
|
||||
*/
|
||||
private renderParts(parts: any[]): RenderBlock[] {
|
||||
private renderParts(parts: RawObject[]): RenderBlock[] {
|
||||
const result: RenderBlock[] = []
|
||||
|
||||
for (const part of parts) {
|
||||
@@ -432,34 +459,37 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染单个 part
|
||||
*/
|
||||
private renderPart(part: any): RenderBlock | null {
|
||||
private renderPart(part: RawObject): RenderBlock | null {
|
||||
if (!part) return null
|
||||
|
||||
// 文本
|
||||
if (part.text !== undefined) {
|
||||
return createTextRenderBlock(part.text)
|
||||
return createTextRenderBlock(String(part.text))
|
||||
}
|
||||
|
||||
// 内联数据(图片等)
|
||||
if (part.inlineData) {
|
||||
const inlineData = part.inlineData as RawObject
|
||||
return createImageRenderBlock({
|
||||
src: `data:${part.inlineData.mimeType || 'image/png'};base64,${part.inlineData.data}`,
|
||||
mimeType: part.inlineData.mimeType,
|
||||
src: `data:${inlineData.mimeType || 'image/png'};base64,${inlineData.data}`,
|
||||
mimeType: typeof inlineData.mimeType === 'string' ? inlineData.mimeType : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
// 函数调用
|
||||
if (part.functionCall) {
|
||||
const fc = part.functionCall as RawObject
|
||||
return createToolUseRenderBlock(
|
||||
part.functionCall.name || '函数调用',
|
||||
this.formatJson(part.functionCall.args)
|
||||
String(fc.name || '函数调用'),
|
||||
this.formatJson(fc.args)
|
||||
)
|
||||
}
|
||||
|
||||
// 函数响应
|
||||
if (part.functionResponse) {
|
||||
const fr = part.functionResponse as RawObject
|
||||
return createToolResultRenderBlock(
|
||||
this.formatJson(part.functionResponse.response)
|
||||
this.formatJson(fr.response)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -533,11 +563,11 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 获取 parts 的徽章
|
||||
*/
|
||||
private getBadgesForParts(parts: any[]): BadgeRenderBlock[] {
|
||||
private getBadgesForParts(parts: RawObject[]): BadgeRenderBlock[] {
|
||||
const badges: BadgeRenderBlock[] = []
|
||||
const hasImage = parts.some((p: any) => p.inlineData)
|
||||
const hasToolCall = parts.some((p: any) => p.functionCall)
|
||||
const hasToolResult = parts.some((p: any) => p.functionResponse)
|
||||
const hasImage = parts.some((p: RawObject) => p.inlineData)
|
||||
const hasToolCall = parts.some((p: RawObject) => p.functionCall)
|
||||
const hasToolResult = parts.some((p: RawObject) => p.functionResponse)
|
||||
|
||||
if (hasToolCall) {
|
||||
badges.push(createBadgeBlock('函数调用', 'outline'))
|
||||
@@ -575,10 +605,10 @@ export class GeminiParser implements ApiFormatParser {
|
||||
/**
|
||||
* 格式化 JSON
|
||||
*/
|
||||
private formatJson(input: any): string {
|
||||
private formatJson(input: unknown): string {
|
||||
if (typeof input === 'string') {
|
||||
try {
|
||||
const parsed = JSON.parse(input)
|
||||
const parsed = JSON.parse(input) as unknown
|
||||
return JSON.stringify(parsed, null, 2)
|
||||
} catch {
|
||||
return input
|
||||
|
||||
@@ -29,6 +29,9 @@ import {
|
||||
createEmptyRenderResult,
|
||||
} from './render'
|
||||
|
||||
/** Raw JSON object from API (loosely typed) */
|
||||
type RawObject = Record<string, unknown>
|
||||
|
||||
/**
|
||||
* OpenAI API 格式解析器
|
||||
*/
|
||||
@@ -39,7 +42,7 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 检测是否为 OpenAI 格式(包括 Chat Completions 和 CLI/Responses API)
|
||||
*/
|
||||
detect(requestBody: any, responseBody: any, hint?: string): number {
|
||||
detect(requestBody: unknown, responseBody: unknown, hint?: string): number {
|
||||
// 1. 后端提示优先
|
||||
if (hint) {
|
||||
const lowerHint = hint.toLowerCase()
|
||||
@@ -47,24 +50,26 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
if (lowerHint.includes('claude') || lowerHint.includes('gemini')) return 0
|
||||
}
|
||||
|
||||
const req = requestBody as RawObject | null | undefined
|
||||
|
||||
// 2. 检查模型名
|
||||
const model = requestBody?.model?.toLowerCase() || ''
|
||||
const model = (typeof req?.model === 'string' ? req.model : '').toLowerCase()
|
||||
if (model.includes('gpt') || model.includes('o1') || model.includes('o3')) return 95
|
||||
|
||||
// 3. 检查请求体结构
|
||||
// OpenAI CLI (Responses API) 使用 input 字段
|
||||
const isCliFormat = requestBody?.input !== undefined || requestBody?.instructions !== undefined
|
||||
const isCliFormat = req?.input !== undefined || req?.instructions !== undefined
|
||||
// OpenAI Chat Completions 使用 messages 数组
|
||||
const isChatFormat = requestBody?.messages && Array.isArray(requestBody.messages)
|
||||
const isChatFormat = req?.messages && Array.isArray(req.messages)
|
||||
|
||||
if (!isCliFormat && !isChatFormat) {
|
||||
return 0
|
||||
}
|
||||
|
||||
// 4. 检查响应体特征
|
||||
const respBody = isStreamResponse(responseBody)
|
||||
? responseBody.chunks?.[0]
|
||||
: responseBody
|
||||
const respBody = (isStreamResponse(responseBody)
|
||||
? (responseBody.chunks?.[0] as RawObject | undefined)
|
||||
: responseBody) as RawObject | null | undefined
|
||||
|
||||
if (respBody) {
|
||||
// OpenAI CLI 响应特征: type 字段为 response.* 格式
|
||||
@@ -72,11 +77,13 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
return 95
|
||||
}
|
||||
// OpenAI Chat Completions 响应特征: choices 数组
|
||||
if (respBody.choices || respBody.object?.includes('chat.completion')) {
|
||||
const respObject = typeof respBody.object === 'string' ? respBody.object : ''
|
||||
if (respBody.choices || respObject.includes('chat.completion')) {
|
||||
return 90
|
||||
}
|
||||
// 明确是 Claude 格式
|
||||
if (respBody.type === 'message' || respBody.type?.startsWith('content_block')) {
|
||||
const respType = typeof respBody.type === 'string' ? respBody.type : ''
|
||||
if (respType === 'message' || respType.startsWith('content_block')) {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
@@ -87,8 +94,9 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
}
|
||||
|
||||
// OpenAI 的 system 是在 messages 数组中作为 role: system
|
||||
const hasSystemInMessages = requestBody.messages?.some(
|
||||
(m: any) => m.role === 'system'
|
||||
const messages = req?.messages as RawObject[] | undefined
|
||||
const hasSystemInMessages = messages?.some(
|
||||
(m: RawObject) => m.role === 'system'
|
||||
)
|
||||
if (hasSystemInMessages) {
|
||||
return 60
|
||||
@@ -100,7 +108,7 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 检查是否为 OpenAI CLI (Responses API) 的响应事件
|
||||
*/
|
||||
private isCliResponseEvent(chunk: any): boolean {
|
||||
private isCliResponseEvent(chunk: RawObject | null | undefined): boolean {
|
||||
const type = chunk?.type
|
||||
if (typeof type !== 'string') return false
|
||||
return type.startsWith('response.') || chunk?.object === 'response'
|
||||
@@ -109,35 +117,38 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析请求体(支持 Chat Completions 和 CLI/Responses API 格式)
|
||||
*/
|
||||
parseRequest(requestBody: any): ParsedConversation {
|
||||
parseRequest(requestBody: unknown): ParsedConversation {
|
||||
if (!requestBody) {
|
||||
return createEmptyConversation('openai', '无请求体')
|
||||
}
|
||||
|
||||
const body = requestBody as RawObject
|
||||
|
||||
// 检测是否为 CLI 格式
|
||||
const isCliFormat = requestBody.input !== undefined || requestBody.instructions !== undefined
|
||||
const isCliFormat = body.input !== undefined || body.instructions !== undefined
|
||||
|
||||
if (isCliFormat) {
|
||||
return this.parseCliRequest(requestBody)
|
||||
return this.parseCliRequest(body)
|
||||
}
|
||||
|
||||
return this.parseChatRequest(requestBody)
|
||||
return this.parseChatRequest(body)
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 OpenAI Chat Completions 请求
|
||||
*/
|
||||
private parseChatRequest(requestBody: any): ParsedConversation {
|
||||
private parseChatRequest(requestBody: RawObject): ParsedConversation {
|
||||
try {
|
||||
const result: ParsedConversation = {
|
||||
messages: [],
|
||||
isStream: requestBody.stream === true,
|
||||
apiFormat: 'openai',
|
||||
model: requestBody.model,
|
||||
model: typeof requestBody.model === 'string' ? requestBody.model : undefined,
|
||||
}
|
||||
|
||||
if (Array.isArray(requestBody.messages)) {
|
||||
for (const msg of requestBody.messages) {
|
||||
for (const rawMsg of requestBody.messages) {
|
||||
const msg = rawMsg as RawObject
|
||||
// OpenAI 的 system 消息在 messages 数组中
|
||||
if (msg.role === 'system') {
|
||||
const systemText = typeof msg.content === 'string'
|
||||
@@ -169,17 +180,17 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
* - 使用 input 字段(可以是字符串、消息数组或对象)
|
||||
* - 使用 instructions 字段作为系统指令
|
||||
*/
|
||||
private parseCliRequest(requestBody: any): ParsedConversation {
|
||||
private parseCliRequest(requestBody: RawObject): ParsedConversation {
|
||||
try {
|
||||
const result: ParsedConversation = {
|
||||
messages: [],
|
||||
isStream: requestBody.stream === true,
|
||||
apiFormat: 'openai',
|
||||
model: requestBody.model,
|
||||
model: typeof requestBody.model === 'string' ? requestBody.model : undefined,
|
||||
}
|
||||
|
||||
// 处理 instructions(系统指令)
|
||||
if (requestBody.instructions) {
|
||||
if (typeof requestBody.instructions === 'string') {
|
||||
result.system = requestBody.instructions
|
||||
}
|
||||
|
||||
@@ -192,17 +203,20 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
} else if (Array.isArray(input)) {
|
||||
// 消息数组
|
||||
for (const item of input) {
|
||||
const parsedMsg = this.parseCliInputItem(item)
|
||||
const parsedMsg = this.parseCliInputItem(item as RawObject)
|
||||
if (parsedMsg) {
|
||||
result.messages.push(parsedMsg)
|
||||
}
|
||||
}
|
||||
} else if (input?.messages && Array.isArray(input.messages)) {
|
||||
} else if (input && typeof input === 'object') {
|
||||
const inputObj = input as RawObject
|
||||
// 包装在对象中的消息数组
|
||||
for (const item of input.messages) {
|
||||
const parsedMsg = this.parseCliInputItem(item)
|
||||
if (parsedMsg) {
|
||||
result.messages.push(parsedMsg)
|
||||
if (Array.isArray(inputObj.messages)) {
|
||||
for (const item of inputObj.messages) {
|
||||
const parsedMsg = this.parseCliInputItem(item as RawObject)
|
||||
if (parsedMsg) {
|
||||
result.messages.push(parsedMsg)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -216,23 +230,24 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析 CLI 格式的单个输入项
|
||||
*/
|
||||
private parseCliInputItem(item: any): ParsedMessage | null {
|
||||
private parseCliInputItem(item: RawObject): ParsedMessage | null {
|
||||
if (!item) return null
|
||||
|
||||
const itemType = item.type
|
||||
|
||||
// 标准消息(有 role 字段)
|
||||
if (itemType === 'message' || item.role) {
|
||||
const role = this.mapRole(item.role)
|
||||
const role = this.mapRole(String(item.role || ''))
|
||||
const contentBlocks: ContentBlock[] = []
|
||||
|
||||
const content = item.content
|
||||
if (typeof content === 'string') {
|
||||
contentBlocks.push(createTextBlock(content))
|
||||
} else if (Array.isArray(content)) {
|
||||
for (const part of content) {
|
||||
for (const rawPart of content) {
|
||||
const part = rawPart as RawObject
|
||||
if (part.type === 'input_text' || part.type === 'output_text' || part.type === 'text') {
|
||||
contentBlocks.push(createTextBlock(part.text || ''))
|
||||
contentBlocks.push(createTextBlock(String(part.text || '')))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -243,15 +258,15 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
|
||||
// function_call -> 工具调用
|
||||
if (itemType === 'function_call') {
|
||||
const toolId = item.call_id || item.id || ''
|
||||
const toolName = item.name || ''
|
||||
const args = item.arguments || '{}'
|
||||
const toolId = String(item.call_id || item.id || '')
|
||||
const toolName = String(item.name || '')
|
||||
const args = String(item.arguments || '{}')
|
||||
return createMessage('assistant', [createToolUseBlock(toolId, toolName, args)])
|
||||
}
|
||||
|
||||
// function_call_output -> 工具结果
|
||||
if (itemType === 'function_call_output') {
|
||||
const toolUseId = item.call_id || item.id || ''
|
||||
const toolUseId = String(item.call_id || item.id || '')
|
||||
const output = typeof item.output === 'string'
|
||||
? item.output
|
||||
: JSON.stringify(item.output, null, 2)
|
||||
@@ -264,52 +279,58 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析响应体(支持 Chat Completions 和 CLI/Responses API 格式)
|
||||
*/
|
||||
parseResponse(responseBody: any): ParsedConversation {
|
||||
parseResponse(responseBody: unknown): ParsedConversation {
|
||||
if (!responseBody) {
|
||||
return createEmptyConversation('openai', '无响应体')
|
||||
}
|
||||
|
||||
const body = responseBody as RawObject
|
||||
|
||||
// 检测是否为 CLI 格式
|
||||
const isCliFormat = this.isCliResponseEvent(responseBody) ||
|
||||
responseBody.object === 'response' ||
|
||||
responseBody.output !== undefined
|
||||
const isCliFormat = this.isCliResponseEvent(body) ||
|
||||
body.object === 'response' ||
|
||||
body.output !== undefined
|
||||
|
||||
if (isCliFormat) {
|
||||
return this.parseCliResponse(responseBody)
|
||||
return this.parseCliResponse(body)
|
||||
}
|
||||
|
||||
return this.parseChatResponse(responseBody)
|
||||
return this.parseChatResponse(body)
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 OpenAI Chat Completions 响应
|
||||
*/
|
||||
private parseChatResponse(responseBody: any): ParsedConversation {
|
||||
private parseChatResponse(responseBody: RawObject): ParsedConversation {
|
||||
try {
|
||||
const result: ParsedConversation = {
|
||||
messages: [],
|
||||
isStream: false,
|
||||
apiFormat: 'openai',
|
||||
model: responseBody.model,
|
||||
model: typeof responseBody.model === 'string' ? responseBody.model : undefined,
|
||||
}
|
||||
|
||||
// OpenAI 响应格式: { choices: [{ message: { role, content, tool_calls } }] }
|
||||
const message = responseBody.choices?.[0]?.message
|
||||
const choices = responseBody.choices as RawObject[] | undefined
|
||||
const firstChoice = choices?.[0] as RawObject | undefined
|
||||
const message = firstChoice?.message as RawObject | undefined
|
||||
if (message) {
|
||||
const contentBlocks: ContentBlock[] = []
|
||||
|
||||
// 文本内容
|
||||
if (message.content) {
|
||||
if (typeof message.content === 'string') {
|
||||
contentBlocks.push(createTextBlock(message.content))
|
||||
}
|
||||
|
||||
// 工具调用
|
||||
if (message.tool_calls) {
|
||||
for (const call of message.tool_calls) {
|
||||
if (Array.isArray(message.tool_calls)) {
|
||||
for (const rawCall of message.tool_calls) {
|
||||
const call = rawCall as RawObject
|
||||
const fn = call.function as RawObject | undefined
|
||||
contentBlocks.push(createToolUseBlock(
|
||||
call.id || '',
|
||||
call.function?.name || '',
|
||||
call.function?.arguments || '{}'
|
||||
String(call.id || ''),
|
||||
String(fn?.name || ''),
|
||||
String(fn?.arguments || '{}')
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -330,13 +351,13 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
*
|
||||
* CLI 响应格式: { output: [{ type: "message", content: [...] }] }
|
||||
*/
|
||||
private parseCliResponse(responseBody: any): ParsedConversation {
|
||||
private parseCliResponse(responseBody: RawObject): ParsedConversation {
|
||||
try {
|
||||
const result: ParsedConversation = {
|
||||
messages: [],
|
||||
isStream: false,
|
||||
apiFormat: 'openai',
|
||||
model: responseBody.model,
|
||||
model: typeof responseBody.model === 'string' ? responseBody.model : undefined,
|
||||
}
|
||||
|
||||
const output = responseBody.output
|
||||
@@ -344,13 +365,15 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
return result
|
||||
}
|
||||
|
||||
for (const item of output) {
|
||||
for (const rawItem of output) {
|
||||
const item = rawItem as RawObject
|
||||
if (item?.type === 'message') {
|
||||
const contentBlocks: ContentBlock[] = []
|
||||
|
||||
if (Array.isArray(item.content)) {
|
||||
for (const content of item.content) {
|
||||
if (content?.type === 'output_text' && content?.text) {
|
||||
for (const rawContent of item.content) {
|
||||
const content = rawContent as RawObject
|
||||
if (content?.type === 'output_text' && typeof content?.text === 'string') {
|
||||
contentBlocks.push(createTextBlock(content.text))
|
||||
}
|
||||
}
|
||||
@@ -371,13 +394,13 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析流式响应(支持 Chat Completions 和 CLI/Responses API 格式)
|
||||
*/
|
||||
parseStreamResponse(chunks: any[]): ParsedConversation {
|
||||
parseStreamResponse(chunks: unknown[]): ParsedConversation {
|
||||
if (!chunks || chunks.length === 0) {
|
||||
return createEmptyConversation('openai', '无响应数据')
|
||||
}
|
||||
|
||||
// 检测是否为 CLI 格式
|
||||
const isCliFormat = chunks.some(chunk => this.isCliResponseEvent(chunk))
|
||||
const isCliFormat = chunks.some(chunk => this.isCliResponseEvent(chunk as RawObject))
|
||||
|
||||
if (isCliFormat) {
|
||||
return this.parseCliStreamResponse(chunks)
|
||||
@@ -389,7 +412,7 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析 OpenAI Chat Completions 流式响应
|
||||
*/
|
||||
private parseChatStreamResponse(chunks: any[]): ParsedConversation {
|
||||
private parseChatStreamResponse(chunks: unknown[]): ParsedConversation {
|
||||
try {
|
||||
const result: ParsedConversation = {
|
||||
messages: [],
|
||||
@@ -400,35 +423,42 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
const textParts: string[] = []
|
||||
const toolCalls = new Map<number, { name: string; id: string; args: string[] }>()
|
||||
|
||||
for (const chunk of chunks) {
|
||||
for (const rawChunk of chunks) {
|
||||
const chunk = rawChunk as RawObject
|
||||
// 提取模型名
|
||||
if (chunk.model && !result.model) {
|
||||
if (typeof chunk.model === 'string' && !result.model) {
|
||||
result.model = chunk.model
|
||||
}
|
||||
|
||||
const delta = chunk.choices?.[0]?.delta
|
||||
if (delta?.content) {
|
||||
const choices = chunk.choices as RawObject[] | undefined
|
||||
const firstChoice = choices?.[0] as RawObject | undefined
|
||||
const delta = firstChoice?.delta as RawObject | undefined
|
||||
if (typeof delta?.content === 'string') {
|
||||
textParts.push(delta.content)
|
||||
}
|
||||
if (delta?.tool_calls) {
|
||||
for (const call of delta.tool_calls) {
|
||||
const index = call.index ?? 0
|
||||
if (Array.isArray(delta?.tool_calls)) {
|
||||
for (const rawCall of delta.tool_calls as unknown[]) {
|
||||
const call = rawCall as RawObject
|
||||
const fn = call.function as RawObject | undefined
|
||||
const index = (typeof call.index === 'number' ? call.index : 0)
|
||||
if (!toolCalls.has(index)) {
|
||||
toolCalls.set(index, {
|
||||
name: call.function?.name || '',
|
||||
id: call.id || '',
|
||||
name: String(fn?.name || ''),
|
||||
id: String(call.id || ''),
|
||||
args: [],
|
||||
})
|
||||
}
|
||||
const existing = toolCalls.get(index)!
|
||||
if (call.function?.name) {
|
||||
existing.name = call.function.name
|
||||
}
|
||||
if (call.id) {
|
||||
existing.id = call.id
|
||||
}
|
||||
if (call.function?.arguments) {
|
||||
existing.args.push(call.function.arguments)
|
||||
const existing = toolCalls.get(index)
|
||||
if (existing) {
|
||||
if (typeof fn?.name === 'string') {
|
||||
existing.name = fn.name
|
||||
}
|
||||
if (typeof call.id === 'string') {
|
||||
existing.id = call.id
|
||||
}
|
||||
if (typeof fn?.arguments === 'string') {
|
||||
existing.args.push(fn.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -469,7 +499,7 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
* - response.completed: 响应完成(包含完整响应和 usage)
|
||||
* - response.function_call_arguments.delta: 函数调用参数增量
|
||||
*/
|
||||
private parseCliStreamResponse(chunks: any[]): ParsedConversation {
|
||||
private parseCliStreamResponse(chunks: unknown[]): ParsedConversation {
|
||||
try {
|
||||
const result: ParsedConversation = {
|
||||
messages: [],
|
||||
@@ -482,13 +512,14 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
let currentToolId = ''
|
||||
let currentToolName = ''
|
||||
|
||||
for (const chunk of chunks) {
|
||||
for (const rawChunk of chunks) {
|
||||
const chunk = rawChunk as RawObject
|
||||
const eventType = chunk.type
|
||||
|
||||
// 从 response.created 或 response.completed 提取模型名
|
||||
if (!result.model) {
|
||||
const response = chunk.response
|
||||
if (response?.model) {
|
||||
const response = chunk.response as RawObject | undefined
|
||||
if (typeof response?.model === 'string') {
|
||||
result.model = response.model
|
||||
}
|
||||
}
|
||||
@@ -498,18 +529,21 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
const delta = chunk.delta
|
||||
if (typeof delta === 'string') {
|
||||
textParts.push(delta)
|
||||
} else if (delta?.text) {
|
||||
textParts.push(delta.text)
|
||||
} else if (delta && typeof delta === 'object') {
|
||||
const deltaObj = delta as RawObject
|
||||
if (typeof deltaObj.text === 'string') {
|
||||
textParts.push(deltaObj.text)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// 处理函数调用输出项添加: response.output_item.added
|
||||
if (eventType === 'response.output_item.added') {
|
||||
const item = chunk.item
|
||||
const item = chunk.item as RawObject | undefined
|
||||
if (item?.type === 'function_call') {
|
||||
currentToolId = item.call_id || item.id || ''
|
||||
currentToolName = item.name || ''
|
||||
currentToolId = String(item.call_id || item.id || '')
|
||||
currentToolName = String(item.name || '')
|
||||
if (currentToolId && !toolCalls.has(currentToolId)) {
|
||||
toolCalls.set(currentToolId, {
|
||||
name: currentToolName,
|
||||
@@ -524,8 +558,8 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
// 处理函数调用参数增量: response.function_call_arguments.delta
|
||||
if (eventType === 'response.function_call_arguments.delta') {
|
||||
const delta = chunk.delta
|
||||
if (delta && currentToolId && toolCalls.has(currentToolId)) {
|
||||
toolCalls.get(currentToolId)!.args.push(delta)
|
||||
if (typeof delta === 'string' && currentToolId && toolCalls.has(currentToolId)) {
|
||||
toolCalls.get(currentToolId)?.args.push(delta)
|
||||
}
|
||||
continue
|
||||
}
|
||||
@@ -533,17 +567,19 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
// 处理完成事件: response.completed
|
||||
// 如果之前没有收集到文本,从完成事件中提取
|
||||
if (eventType === 'response.completed') {
|
||||
const response = chunk.response
|
||||
if (response?.model && !result.model) {
|
||||
const response = chunk.response as RawObject | undefined
|
||||
if (typeof response?.model === 'string' && !result.model) {
|
||||
result.model = response.model
|
||||
}
|
||||
|
||||
// 从 output 中提取文本(备用方案)
|
||||
if (textParts.length === 0 && response?.output) {
|
||||
for (const item of response.output) {
|
||||
if (item?.type === 'message' && item?.content) {
|
||||
for (const content of item.content) {
|
||||
if (content?.type === 'output_text' && content?.text) {
|
||||
if (textParts.length === 0 && Array.isArray(response?.output)) {
|
||||
for (const rawItem of response.output as unknown[]) {
|
||||
const item = rawItem as RawObject
|
||||
if (item?.type === 'message' && Array.isArray(item?.content)) {
|
||||
for (const rawContent of item.content as unknown[]) {
|
||||
const content = rawContent as RawObject
|
||||
if (content?.type === 'output_text' && typeof content?.text === 'string') {
|
||||
textParts.push(content.text)
|
||||
}
|
||||
}
|
||||
@@ -583,10 +619,10 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 解析单条消息
|
||||
*/
|
||||
private parseMessage(msg: any): ParsedMessage | null {
|
||||
private parseMessage(msg: RawObject): ParsedMessage | null {
|
||||
if (!msg || !msg.role) return null
|
||||
|
||||
const role = this.mapRole(msg.role)
|
||||
const role = this.mapRole(String(msg.role))
|
||||
const contentBlocks: ContentBlock[] = []
|
||||
|
||||
// 文本内容
|
||||
@@ -594,12 +630,14 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
contentBlocks.push(createTextBlock(msg.content))
|
||||
} else if (Array.isArray(msg.content)) {
|
||||
// Vision API 格式
|
||||
for (const part of msg.content) {
|
||||
for (const rawPart of msg.content) {
|
||||
const part = rawPart as RawObject
|
||||
if (part.type === 'text') {
|
||||
contentBlocks.push(createTextBlock(part.text || ''))
|
||||
contentBlocks.push(createTextBlock(String(part.text || '')))
|
||||
} else if (part.type === 'image_url') {
|
||||
const imageUrl = part.image_url as RawObject | undefined
|
||||
contentBlocks.push(createImageBlock('url', {
|
||||
url: part.image_url?.url,
|
||||
url: typeof imageUrl?.url === 'string' ? imageUrl.url : undefined,
|
||||
alt: '[图片]',
|
||||
}))
|
||||
}
|
||||
@@ -607,12 +645,14 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
}
|
||||
|
||||
// 工具调用(assistant 消息)
|
||||
if (msg.tool_calls) {
|
||||
for (const call of msg.tool_calls) {
|
||||
if (Array.isArray(msg.tool_calls)) {
|
||||
for (const rawCall of msg.tool_calls) {
|
||||
const call = rawCall as RawObject
|
||||
const fn = call.function as RawObject | undefined
|
||||
contentBlocks.push(createToolUseBlock(
|
||||
call.id || '',
|
||||
call.function?.name || '',
|
||||
call.function?.arguments || '{}'
|
||||
String(call.id || ''),
|
||||
String(fn?.name || ''),
|
||||
String(fn?.arguments || '{}')
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -623,7 +663,7 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
? msg.content
|
||||
: JSON.stringify(msg.content, null, 2)
|
||||
contentBlocks.push(createToolResultBlock(
|
||||
msg.tool_call_id,
|
||||
String(msg.tool_call_id),
|
||||
content
|
||||
))
|
||||
}
|
||||
@@ -658,31 +698,34 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染请求体(支持 Chat Completions 和 CLI/Responses API 格式)
|
||||
*/
|
||||
renderRequest(requestBody: any): RenderResult {
|
||||
renderRequest(requestBody: unknown): RenderResult {
|
||||
if (!requestBody) {
|
||||
return createEmptyRenderResult('无请求体')
|
||||
}
|
||||
|
||||
const body = requestBody as RawObject
|
||||
|
||||
// 检测是否为 CLI 格式
|
||||
const isCliFormat = requestBody.input !== undefined || requestBody.instructions !== undefined
|
||||
const isCliFormat = body.input !== undefined || body.instructions !== undefined
|
||||
|
||||
if (isCliFormat) {
|
||||
return this.renderCliRequest(requestBody)
|
||||
return this.renderCliRequest(body)
|
||||
}
|
||||
|
||||
return this.renderChatRequest(requestBody)
|
||||
return this.renderChatRequest(body)
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染 OpenAI Chat Completions 请求
|
||||
*/
|
||||
private renderChatRequest(requestBody: any): RenderResult {
|
||||
private renderChatRequest(requestBody: RawObject): RenderResult {
|
||||
try {
|
||||
const blocks: RenderBlock[] = []
|
||||
const isStream = requestBody.stream === true
|
||||
|
||||
if (Array.isArray(requestBody.messages)) {
|
||||
for (const msg of requestBody.messages) {
|
||||
for (const rawMsg of requestBody.messages) {
|
||||
const msg = rawMsg as RawObject
|
||||
// system 消息单独处理
|
||||
if (msg.role === 'system') {
|
||||
const systemText = typeof msg.content === 'string' ? msg.content : ''
|
||||
@@ -710,13 +753,13 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染 OpenAI CLI (Responses API) 请求
|
||||
*/
|
||||
private renderCliRequest(requestBody: any): RenderResult {
|
||||
private renderCliRequest(requestBody: RawObject): RenderResult {
|
||||
try {
|
||||
const blocks: RenderBlock[] = []
|
||||
const isStream = requestBody.stream === true
|
||||
|
||||
// 渲染 instructions(系统指令)
|
||||
if (requestBody.instructions) {
|
||||
if (typeof requestBody.instructions === 'string') {
|
||||
blocks.push(createMessageBlock('system', [
|
||||
createTextRenderBlock(requestBody.instructions),
|
||||
], { roleLabel: 'Instructions' }))
|
||||
@@ -733,17 +776,20 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
} else if (Array.isArray(input)) {
|
||||
// 消息数组
|
||||
for (const item of input) {
|
||||
const msgBlock = this.renderCliInputItem(item)
|
||||
const msgBlock = this.renderCliInputItem(item as RawObject)
|
||||
if (msgBlock) {
|
||||
blocks.push(msgBlock)
|
||||
}
|
||||
}
|
||||
} else if (input?.messages && Array.isArray(input.messages)) {
|
||||
} else if (input && typeof input === 'object') {
|
||||
const inputObj = input as RawObject
|
||||
// 包装在对象中的消息数组
|
||||
for (const item of input.messages) {
|
||||
const msgBlock = this.renderCliInputItem(item)
|
||||
if (msgBlock) {
|
||||
blocks.push(msgBlock)
|
||||
if (Array.isArray(inputObj.messages)) {
|
||||
for (const item of inputObj.messages) {
|
||||
const msgBlock = this.renderCliInputItem(item as RawObject)
|
||||
if (msgBlock) {
|
||||
blocks.push(msgBlock)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -757,23 +803,24 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染 CLI 格式的单个输入项
|
||||
*/
|
||||
private renderCliInputItem(item: any): RenderBlock | null {
|
||||
private renderCliInputItem(item: RawObject): RenderBlock | null {
|
||||
if (!item) return null
|
||||
|
||||
const itemType = item.type
|
||||
|
||||
// 标准消息
|
||||
if (itemType === 'message' || item.role) {
|
||||
const role = this.mapRole(item.role)
|
||||
const role = this.mapRole(String(item.role || ''))
|
||||
const contentBlocks: RenderBlock[] = []
|
||||
|
||||
const content = item.content
|
||||
if (typeof content === 'string') {
|
||||
contentBlocks.push(createTextRenderBlock(content))
|
||||
} else if (Array.isArray(content)) {
|
||||
for (const part of content) {
|
||||
for (const rawPart of content) {
|
||||
const part = rawPart as RawObject
|
||||
if (part.type === 'input_text' || part.type === 'output_text' || part.type === 'text') {
|
||||
contentBlocks.push(createTextRenderBlock(part.text || ''))
|
||||
contentBlocks.push(createTextRenderBlock(String(part.text || '')))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -784,10 +831,10 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
|
||||
// function_call -> 工具调用
|
||||
if (itemType === 'function_call') {
|
||||
const toolName = item.name || '工具调用'
|
||||
const toolName = String(item.name || '工具调用')
|
||||
const args = this.formatJson(item.arguments)
|
||||
return createMessageBlock('assistant', [
|
||||
createToolUseRenderBlock(toolName, args, item.call_id || item.id),
|
||||
createToolUseRenderBlock(toolName, args, String(item.call_id || item.id || '')),
|
||||
], { roleLabel: 'Assistant', badges: [createBadgeBlock('工具调用', 'outline')] })
|
||||
}
|
||||
|
||||
@@ -807,7 +854,7 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染响应体(支持 Chat Completions 和 CLI/Responses API 格式)
|
||||
*/
|
||||
renderResponse(responseBody: any): RenderResult {
|
||||
renderResponse(responseBody: unknown): RenderResult {
|
||||
if (!responseBody) {
|
||||
return createEmptyRenderResult('无响应体')
|
||||
}
|
||||
@@ -817,44 +864,50 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
return this.renderStreamResponse(responseBody.chunks || [])
|
||||
}
|
||||
|
||||
const body = responseBody as RawObject
|
||||
|
||||
// 检测是否为 CLI 格式
|
||||
const isCliFormat = this.isCliResponseEvent(responseBody) ||
|
||||
responseBody.object === 'response' ||
|
||||
responseBody.output !== undefined
|
||||
const isCliFormat = this.isCliResponseEvent(body) ||
|
||||
body.object === 'response' ||
|
||||
body.output !== undefined
|
||||
|
||||
if (isCliFormat) {
|
||||
return this.renderCliResponse(responseBody)
|
||||
return this.renderCliResponse(body)
|
||||
}
|
||||
|
||||
return this.renderChatResponse(responseBody)
|
||||
return this.renderChatResponse(body)
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染 OpenAI Chat Completions 响应
|
||||
*/
|
||||
private renderChatResponse(responseBody: any): RenderResult {
|
||||
private renderChatResponse(responseBody: RawObject): RenderResult {
|
||||
try {
|
||||
const blocks: RenderBlock[] = []
|
||||
|
||||
// OpenAI 响应格式: { choices: [{ message: { role, content, tool_calls } }] }
|
||||
const message = responseBody.choices?.[0]?.message
|
||||
const choices = responseBody.choices as RawObject[] | undefined
|
||||
const firstChoice = choices?.[0] as RawObject | undefined
|
||||
const message = firstChoice?.message as RawObject | undefined
|
||||
if (message) {
|
||||
const contentBlocks: RenderBlock[] = []
|
||||
const badges: BadgeRenderBlock[] = []
|
||||
|
||||
// 文本内容
|
||||
if (message.content) {
|
||||
if (typeof message.content === 'string') {
|
||||
contentBlocks.push(createTextRenderBlock(message.content))
|
||||
}
|
||||
|
||||
// 工具调用
|
||||
if (message.tool_calls) {
|
||||
if (Array.isArray(message.tool_calls)) {
|
||||
badges.push(createBadgeBlock('工具调用', 'outline'))
|
||||
for (const call of message.tool_calls) {
|
||||
for (const rawCall of message.tool_calls) {
|
||||
const call = rawCall as RawObject
|
||||
const fn = call.function as RawObject | undefined
|
||||
contentBlocks.push(createToolUseRenderBlock(
|
||||
call.function?.name || '工具调用',
|
||||
this.formatJson(call.function?.arguments),
|
||||
call.id
|
||||
String(fn?.name || '工具调用'),
|
||||
this.formatJson(fn?.arguments),
|
||||
typeof call.id === 'string' ? call.id : undefined
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -876,7 +929,7 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染 OpenAI CLI (Responses API) 响应
|
||||
*/
|
||||
private renderCliResponse(responseBody: any): RenderResult {
|
||||
private renderCliResponse(responseBody: RawObject): RenderResult {
|
||||
try {
|
||||
const blocks: RenderBlock[] = []
|
||||
|
||||
@@ -885,13 +938,15 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
return { blocks, isStream: false }
|
||||
}
|
||||
|
||||
for (const item of output) {
|
||||
for (const rawItem of output) {
|
||||
const item = rawItem as RawObject
|
||||
if (item?.type === 'message') {
|
||||
const contentBlocks: RenderBlock[] = []
|
||||
|
||||
if (Array.isArray(item.content)) {
|
||||
for (const content of item.content) {
|
||||
if (content?.type === 'output_text' && content?.text) {
|
||||
for (const rawContent of item.content) {
|
||||
const content = rawContent as RawObject
|
||||
if (content?.type === 'output_text' && typeof content?.text === 'string') {
|
||||
contentBlocks.push(createTextRenderBlock(content.text))
|
||||
}
|
||||
}
|
||||
@@ -914,7 +969,7 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染流式响应
|
||||
*/
|
||||
private renderStreamResponse(chunks: any[]): RenderResult {
|
||||
private renderStreamResponse(chunks: unknown[]): RenderResult {
|
||||
if (!chunks || chunks.length === 0) {
|
||||
return createEmptyRenderResult('无响应数据')
|
||||
}
|
||||
@@ -949,10 +1004,10 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 渲染单条消息
|
||||
*/
|
||||
private renderMessage(msg: any): RenderBlock | null {
|
||||
private renderMessage(msg: RawObject): RenderBlock | null {
|
||||
if (!msg || !msg.role) return null
|
||||
|
||||
const role = this.mapRole(msg.role)
|
||||
const role = this.mapRole(String(msg.role))
|
||||
const contentBlocks: RenderBlock[] = []
|
||||
const badges: BadgeRenderBlock[] = []
|
||||
|
||||
@@ -961,13 +1016,15 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
contentBlocks.push(createTextRenderBlock(msg.content))
|
||||
} else if (Array.isArray(msg.content)) {
|
||||
// Vision API 格式
|
||||
for (const part of msg.content) {
|
||||
for (const rawPart of msg.content) {
|
||||
const part = rawPart as RawObject
|
||||
if (part.type === 'text') {
|
||||
contentBlocks.push(createTextRenderBlock(part.text || ''))
|
||||
contentBlocks.push(createTextRenderBlock(String(part.text || '')))
|
||||
} else if (part.type === 'image_url') {
|
||||
badges.push(createBadgeBlock('图片', 'secondary'))
|
||||
const imageUrl = part.image_url as RawObject | undefined
|
||||
contentBlocks.push(createImageRenderBlock({
|
||||
src: part.image_url?.url,
|
||||
src: typeof imageUrl?.url === 'string' ? imageUrl.url : undefined,
|
||||
alt: '[图片]',
|
||||
}))
|
||||
}
|
||||
@@ -975,13 +1032,15 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
}
|
||||
|
||||
// 工具调用(assistant 消息)
|
||||
if (msg.tool_calls) {
|
||||
if (Array.isArray(msg.tool_calls)) {
|
||||
badges.push(createBadgeBlock('工具调用', 'outline'))
|
||||
for (const call of msg.tool_calls) {
|
||||
for (const rawCall of msg.tool_calls) {
|
||||
const call = rawCall as RawObject
|
||||
const fn = call.function as RawObject | undefined
|
||||
contentBlocks.push(createToolUseRenderBlock(
|
||||
call.function?.name || '工具调用',
|
||||
this.formatJson(call.function?.arguments),
|
||||
call.id
|
||||
String(fn?.name || '工具调用'),
|
||||
this.formatJson(fn?.arguments),
|
||||
typeof call.id === 'string' ? call.id : undefined
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1091,10 +1150,10 @@ export class OpenAIParser implements ApiFormatParser {
|
||||
/**
|
||||
* 格式化 JSON
|
||||
*/
|
||||
private formatJson(input: any): string {
|
||||
private formatJson(input: unknown): string {
|
||||
if (typeof input === 'string') {
|
||||
try {
|
||||
const parsed = JSON.parse(input)
|
||||
const parsed = JSON.parse(input) as unknown
|
||||
return JSON.stringify(parsed, null, 2)
|
||||
} catch {
|
||||
return input
|
||||
|
||||
@@ -40,7 +40,7 @@ class ParserRegistry {
|
||||
/**
|
||||
* 检测 API 格式并返回最佳匹配的解析器
|
||||
*/
|
||||
detectParser(requestBody: any, responseBody: any, hint?: string): ApiFormatParser | undefined {
|
||||
detectParser(requestBody: unknown, responseBody: unknown, hint?: string): ApiFormatParser | undefined {
|
||||
let bestParser: ApiFormatParser | undefined
|
||||
let bestScore = 0
|
||||
|
||||
@@ -58,7 +58,7 @@ class ParserRegistry {
|
||||
/**
|
||||
* 检测 API 格式
|
||||
*/
|
||||
detectFormat(requestBody: any, responseBody: any, hint?: string): ApiFormat {
|
||||
detectFormat(requestBody: unknown, responseBody: unknown, hint?: string): ApiFormat {
|
||||
const parser = this.detectParser(requestBody, responseBody, hint)
|
||||
return parser?.format ?? 'unknown'
|
||||
}
|
||||
@@ -76,8 +76,8 @@ parserRegistry.register(geminiParser)
|
||||
* 解析请求体
|
||||
*/
|
||||
export function parseRequest(
|
||||
requestBody: any,
|
||||
responseBody?: any,
|
||||
requestBody: unknown,
|
||||
responseBody?: unknown,
|
||||
formatHint?: string
|
||||
): ParsedConversation {
|
||||
if (!requestBody) {
|
||||
@@ -96,8 +96,8 @@ export function parseRequest(
|
||||
* 解析响应体
|
||||
*/
|
||||
export function parseResponse(
|
||||
responseBody: any,
|
||||
requestBody?: any,
|
||||
responseBody: unknown,
|
||||
requestBody?: unknown,
|
||||
formatHint?: string
|
||||
): ParsedConversation {
|
||||
if (!responseBody) {
|
||||
@@ -121,8 +121,8 @@ export function parseResponse(
|
||||
* 检测 API 格式
|
||||
*/
|
||||
export function detectApiFormat(
|
||||
requestBody: any,
|
||||
responseBody: any,
|
||||
requestBody: unknown,
|
||||
responseBody: unknown,
|
||||
hint?: string
|
||||
): ApiFormat {
|
||||
return parserRegistry.detectFormat(requestBody, responseBody, hint)
|
||||
@@ -132,8 +132,8 @@ export function detectApiFormat(
|
||||
* 渲染请求体
|
||||
*/
|
||||
export function renderRequest(
|
||||
requestBody: any,
|
||||
responseBody?: any,
|
||||
requestBody: unknown,
|
||||
responseBody?: unknown,
|
||||
formatHint?: string
|
||||
): RenderResult {
|
||||
if (!requestBody) {
|
||||
@@ -152,8 +152,8 @@ export function renderRequest(
|
||||
* 渲染响应体
|
||||
*/
|
||||
export function renderResponse(
|
||||
responseBody: any,
|
||||
requestBody?: any,
|
||||
responseBody: unknown,
|
||||
requestBody?: unknown,
|
||||
formatHint?: string
|
||||
): RenderResult {
|
||||
if (!responseBody) {
|
||||
|
||||
@@ -51,7 +51,7 @@ export interface ToolUseContentBlock extends ContentBlockBase {
|
||||
type: 'tool_use'
|
||||
toolId: string
|
||||
toolName: string
|
||||
input: Record<string, any> | string
|
||||
input: Record<string, unknown> | string
|
||||
}
|
||||
|
||||
/** 工具结果内容块 */
|
||||
@@ -151,7 +151,7 @@ export interface FormatDetector {
|
||||
* @param hint 后端提供的格式提示
|
||||
* @returns 匹配置信度 (0-100),0 表示不匹配
|
||||
*/
|
||||
detect(requestBody: any, responseBody: any, hint?: string): number
|
||||
detect(requestBody: unknown, responseBody: unknown, hint?: string): number
|
||||
}
|
||||
|
||||
/** 请求体解析器 */
|
||||
@@ -161,7 +161,7 @@ export interface RequestParser {
|
||||
* @param requestBody 请求体
|
||||
* @returns 解析后的对话
|
||||
*/
|
||||
parseRequest(requestBody: any): ParsedConversation
|
||||
parseRequest(requestBody: unknown): ParsedConversation
|
||||
}
|
||||
|
||||
/** 响应体解析器 */
|
||||
@@ -171,14 +171,14 @@ export interface ResponseParser {
|
||||
* @param responseBody 响应体
|
||||
* @returns 解析后的对话
|
||||
*/
|
||||
parseResponse(responseBody: any): ParsedConversation
|
||||
parseResponse(responseBody: unknown): ParsedConversation
|
||||
|
||||
/**
|
||||
* 解析流式响应
|
||||
* @param chunks 响应块列表
|
||||
* @returns 解析后的对话
|
||||
*/
|
||||
parseStreamResponse(chunks: any[]): ParsedConversation
|
||||
parseStreamResponse(chunks: unknown[]): ParsedConversation
|
||||
}
|
||||
|
||||
/** 完整的 API 格式解析器 */
|
||||
@@ -193,14 +193,14 @@ export interface ApiFormatParser extends FormatDetector, RequestParser, Response
|
||||
* @param requestBody 请求体
|
||||
* @returns 渲染结果
|
||||
*/
|
||||
renderRequest(requestBody: any): import('./render').RenderResult
|
||||
renderRequest(requestBody: unknown): import('./render').RenderResult
|
||||
|
||||
/**
|
||||
* 渲染响应体为渲染块
|
||||
* @param responseBody 响应体
|
||||
* @returns 渲染结果
|
||||
*/
|
||||
renderResponse(responseBody: any): import('./render').RenderResult
|
||||
renderResponse(responseBody: unknown): import('./render').RenderResult
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
@@ -215,12 +215,15 @@ export interface StreamMetadata {
|
||||
/** 流式响应体结构 */
|
||||
export interface StreamResponseBody {
|
||||
metadata?: StreamMetadata
|
||||
chunks?: any[]
|
||||
chunks?: unknown[]
|
||||
}
|
||||
|
||||
/** 检查是否为流式响应 */
|
||||
export function isStreamResponse(body: any): body is StreamResponseBody {
|
||||
return body?.metadata?.stream === true && Array.isArray(body?.chunks)
|
||||
export function isStreamResponse(body: unknown): body is StreamResponseBody {
|
||||
if (!body || typeof body !== 'object') return false
|
||||
const obj = body as Record<string, unknown>
|
||||
const metadata = obj.metadata as Record<string, unknown> | undefined
|
||||
return metadata?.stream === true && Array.isArray(obj.chunks)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
@@ -241,7 +244,7 @@ export function createThinkingBlock(thinking: string, signature?: string): Think
|
||||
export function createToolUseBlock(
|
||||
toolId: string,
|
||||
toolName: string,
|
||||
input: Record<string, any> | string
|
||||
input: Record<string, unknown> | string
|
||||
): ToolUseContentBlock {
|
||||
return { type: 'tool_use', toolId, toolName, input }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user