| 1 | import { normalizeOpenAIBaseUrl } from '../agent-runtime/model/options' |
| 2 | |
| 3 | export interface ModelListRequestSpec { |
| 4 | url: string |
| 5 | headers: Record<string, string> |
| 6 | } |
| 7 | |
| 8 | const trimBaseUrl = (baseUrl: unknown): string => { |
| 9 | if (typeof baseUrl !== 'string') return '' |
| 10 | return baseUrl.trim().replace(/\/+$/, '') |
| 11 | } |
| 12 | |
| 13 | /** 按供应商约定拼出拉取模型列表的请求(openai/openai-responses/anthropic/google)。 */ |
| 14 | export const buildModelListRequest = ( |
| 15 | provider: string, |
| 16 | baseUrl: string, |
| 17 | apiKey: string |
| 18 | ): ModelListRequestSpec => { |
| 19 | const key = apiKey.trim() |
| 20 | const base = trimBaseUrl(baseUrl) |
| 21 | if (provider === 'google') { |
| 22 | const origin = base || 'https://generativelanguage.googleapis.com' |
| 23 | return { |
| 24 | url: `${origin}/v1beta/models?pageSize=1000`, |
| 25 | headers: { 'x-goog-api-key': key } |
| 26 | } |
| 27 | } |
| 28 | if (provider === 'anthropic') { |
| 29 | const origin = base || 'https://api.anthropic.com' |
| 30 | return { |
| 31 | url: `${origin}/v1/models?limit=1000`, |
| 32 | headers: { 'x-api-key': key, 'anthropic-version': '2023-06-01' } |
| 33 | } |
| 34 | } |
| 35 | const origin = |
| 36 | normalizeOpenAIBaseUrl(base, provider === 'openai-responses') || 'https://api.openai.com/v1' |
| 37 | return { |
| 38 | url: `${origin}/models`, |
| 39 | headers: { Authorization: `Bearer ${key}` } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | /** 从 /models 响应中提取模型 ID 列表(去重排序),不合法结构直接抛错。 */ |
| 44 | export const parseModelListResponse = (provider: string, json: unknown): string[] => { |
| 45 | const source = |
| 46 | provider === 'google' |
| 47 | ? (json as { models?: unknown } | null)?.models |
| 48 | : (json as { data?: unknown } | null)?.data |
| 49 | if (!Array.isArray(source)) { |
| 50 | throw new Error('unexpected model list response shape') |
| 51 | } |
| 52 | const models = new Set<string>() |
| 53 | for (const item of source) { |
| 54 | if (!item || typeof item !== 'object') continue |
| 55 | const record = item as Record<string, unknown> |
| 56 | if (provider === 'google') { |
| 57 | const name = typeof record.name === 'string' ? record.name.trim() : '' |
| 58 | if (name) models.add(name.replace(/^models\//, '')) |
| 59 | continue |
| 60 | } |
| 61 | const id = typeof record.id === 'string' ? record.id.trim() : '' |
| 62 | const name = typeof record.name === 'string' ? record.name.trim() : '' |
| 63 | const model = id || (name ? name.replace(/^models\//, '') : '') |
| 64 | if (model) models.add(model) |
| 65 | } |
| 66 | return [...models].sort((a, b) => a.localeCompare(b)) |
| 67 | } |
| 68 |