mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-04 23:24:21 +00:00
* feat(provider): refresh models from the public Pi catalog * fix(provider): simplify provider card actions
198 lines
7.2 KiB
TypeScript
198 lines
7.2 KiB
TypeScript
import { PI_AI_VERSION } from '@earendil-works/pi-ai'
|
|
import { getBuiltinModels, getBuiltinProviders } from '@earendil-works/pi-ai/providers/all'
|
|
import { CompatSchemasByApi } from '@earendil-works/pi-ai/providers/compat-schema'
|
|
import { ThinkingLevelMapSchema } from '@earendil-works/pi-ai/providers/model-schema'
|
|
import {
|
|
providerModelConfigSchema,
|
|
type ProviderConfigSerializable,
|
|
type ProviderRefreshUnavailableReason,
|
|
type RefreshedProviderModel,
|
|
} from '@shumai/dtos'
|
|
import { HTTPException } from 'hono/http-exception'
|
|
import { z } from 'zod'
|
|
import { ENV_MAP } from './builtin'
|
|
|
|
type RefreshConnection =
|
|
| { unavailableReason: ProviderRefreshUnavailableReason }
|
|
| { unavailableReason: null; piProviderId: string }
|
|
|
|
type CatalogResult =
|
|
| { status: 'unavailable'; reason: 'catalog_unavailable' }
|
|
| { status: 'ready'; models: RefreshedProviderModel[] }
|
|
|
|
const REFRESH_TIMEOUT_MS = 10_000
|
|
const builtinConnections = new Map<string, Set<string>>(
|
|
getBuiltinProviders().map((id) => [
|
|
id,
|
|
new Set(getBuiltinModels(id).map(({ api, baseUrl }) => connectionKey(api, baseUrl))),
|
|
]),
|
|
)
|
|
const catalogSchema = z.record(
|
|
z.string(),
|
|
z.looseObject({
|
|
id: z.string().min(1),
|
|
provider: z.string(),
|
|
api: z.string(),
|
|
baseUrl: z.string(),
|
|
type: z.string().optional(),
|
|
}),
|
|
)
|
|
const compatSchemas = new Map(
|
|
Object.entries(CompatSchemasByApi).map(([api, schema]) => [api, z.fromJSONSchema(schema)]),
|
|
)
|
|
const thinkingLevelMapSchema = z.fromJSONSchema(ThinkingLevelMapSchema)
|
|
const catalogHeaderNames = new Set([
|
|
'user-agent',
|
|
'editor-version',
|
|
'editor-plugin-version',
|
|
'copilot-integration-id',
|
|
'nvcf-poll-seconds',
|
|
])
|
|
const catalogHeadersSchema = z.record(
|
|
z.string().refine((name) => catalogHeaderNames.has(name.toLowerCase())),
|
|
z.string().regex(/^[\t\x20-\x7E]*$/),
|
|
)
|
|
|
|
function normalizeBaseUrl(baseUrl?: string): string {
|
|
return baseUrl?.trim().replace(/\/+$/, '') ?? ''
|
|
}
|
|
|
|
function connectionKey(api: string, baseUrl?: string): string {
|
|
return JSON.stringify([api, normalizeBaseUrl(baseUrl)])
|
|
}
|
|
|
|
function piProviderName(name: string): string {
|
|
return name === 'azure-openai-responses' ? 'azure' : name
|
|
}
|
|
|
|
export function isProviderConfigured(name: string, config: ProviderConfigSerializable): boolean {
|
|
const key = config.apiKey?.trim()
|
|
if (key) {
|
|
const envValue = process.env[key]
|
|
if (envValue !== undefined) return Boolean(envValue.trim())
|
|
// Existing forms accept literal keys and names such as OPENAI_API_KEY in the same field.
|
|
return !/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(key)
|
|
}
|
|
|
|
const envName = ENV_MAP[piProviderName(name)]
|
|
if (envName && process.env[envName]?.trim()) return true
|
|
if (name === 'amazon-bedrock' && config.api === 'bedrock-converse-stream') {
|
|
return Boolean(
|
|
process.env.AWS_BEARER_TOKEN_BEDROCK ||
|
|
process.env.AWS_PROFILE ||
|
|
(process.env.AWS_ACCESS_KEY_ID && process.env.AWS_SECRET_ACCESS_KEY) ||
|
|
process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI ||
|
|
process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI ||
|
|
process.env.AWS_WEB_IDENTITY_TOKEN_FILE,
|
|
)
|
|
}
|
|
|
|
const url = URL.parse(config.baseUrl ?? '')
|
|
return Boolean(
|
|
url &&
|
|
config.api === 'openai-completions' &&
|
|
(config.authHeader === false ||
|
|
/^(?:localhost|127\.\d+\.\d+\.\d+|\[::1\])$/.test(url.hostname)),
|
|
)
|
|
}
|
|
|
|
function azureDeploymentIds(): Set<string> {
|
|
// Pi uses model-id=deployment-name mappings for Azure's deployment-specific API.
|
|
const entries = process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP?.split(',') ?? []
|
|
return new Set(
|
|
entries.flatMap((entry) => {
|
|
const [modelId, deployment] = entry.split('=', 2).map((value) => value.trim())
|
|
return modelId && deployment ? [modelId] : []
|
|
}),
|
|
)
|
|
}
|
|
|
|
export function getRefreshConnection(
|
|
name: string,
|
|
config: ProviderConfigSerializable,
|
|
): RefreshConnection {
|
|
const providerId = piProviderName(name)
|
|
if (providerId === 'azure' && config.api === 'azure-openai-responses') {
|
|
const endpoint =
|
|
config.baseUrl || process.env.AZURE_OPENAI_BASE_URL || process.env.AZURE_OPENAI_RESOURCE_NAME
|
|
return endpoint && azureDeploymentIds().size > 0
|
|
? { unavailableReason: null, piProviderId: providerId }
|
|
: { unavailableReason: 'azure_deployment_required' }
|
|
}
|
|
if (
|
|
providerId === 'kimi-coding' &&
|
|
config.api === 'anthropic-messages' &&
|
|
normalizeBaseUrl(config.baseUrl) === 'https://api.kimi.com/coding'
|
|
) {
|
|
return { unavailableReason: 'legacy_kimi_connection' }
|
|
}
|
|
|
|
const key = connectionKey(config.api, config.baseUrl)
|
|
const namedConnections = builtinConnections.get(providerId)
|
|
if (namedConnections?.has(key)) return { unavailableReason: null, piProviderId: providerId }
|
|
// A renamed provider can still be resolved if its protocol and endpoint identify one catalog.
|
|
if (!namedConnections && config.baseUrl) {
|
|
const matches = [...builtinConnections].filter(([, connections]) => connections.has(key))
|
|
if (matches.length === 1) return { unavailableReason: null, piProviderId: matches[0][0] }
|
|
}
|
|
return { unavailableReason: 'unsupported_connection' }
|
|
}
|
|
|
|
export async function discoverProviderModels(
|
|
piProviderId: string,
|
|
config: ProviderConfigSerializable,
|
|
): Promise<CatalogResult> {
|
|
const url = new URL(`/api/models/providers/${encodeURIComponent(piProviderId)}`, 'https://pi.dev')
|
|
url.searchParams.set('pi-version', PI_AI_VERSION)
|
|
let catalog: z.infer<typeof catalogSchema>
|
|
try {
|
|
const response = await fetch(url, {
|
|
headers: { Accept: 'application/json' },
|
|
redirect: 'error',
|
|
signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS),
|
|
})
|
|
if (response.status === 404 || response.status === 501) {
|
|
return { status: 'unavailable', reason: 'catalog_unavailable' }
|
|
}
|
|
if (!response.ok) throw new Error(`Pi catalog returned HTTP ${response.status}`)
|
|
catalog = catalogSchema.parse(await response.json())
|
|
} catch (cause) {
|
|
throw new HTTPException(502, { message: 'Could not refresh provider models', cause })
|
|
}
|
|
|
|
const key = connectionKey(config.api, config.baseUrl)
|
|
const azureDeployments = piProviderId === 'azure' ? azureDeploymentIds() : undefined
|
|
const models = Object.entries(catalog).flatMap(([id, model]) => {
|
|
if (
|
|
model.id !== id ||
|
|
model.provider !== piProviderId ||
|
|
(model.type && model.type !== 'chat')
|
|
) {
|
|
return []
|
|
}
|
|
const matches = azureDeployments
|
|
? model.api === config.api && model.baseUrl === '' && azureDeployments.has(id)
|
|
: connectionKey(model.api, model.baseUrl) === key
|
|
if (!matches) return []
|
|
if (
|
|
model.compat !== undefined &&
|
|
!compatSchemas.get(model.api)?.safeParse(model.compat).success
|
|
)
|
|
return []
|
|
if (
|
|
model.thinkingLevelMap !== undefined &&
|
|
!thinkingLevelMapSchema.safeParse(model.thinkingLevelMap).success
|
|
)
|
|
return []
|
|
if (model.headers !== undefined && !catalogHeadersSchema.safeParse(model.headers).success)
|
|
return []
|
|
|
|
// Keep omitted flags absent so Pi can apply model- and endpoint-specific defaults.
|
|
const modelConfig = providerModelConfigSchema.safeParse(model)
|
|
if (!modelConfig.success) return []
|
|
const name = typeof model.name === 'string' && model.name ? model.name : id
|
|
return [{ modelId: id, name, config: modelConfig.data }]
|
|
})
|
|
return { status: 'ready', models }
|
|
}
|