mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 12:24:39 +00:00
feat(provider): refresh models from the public Pi catalog
This commit is contained in:
@@ -28,9 +28,9 @@
|
||||
"@aws-sdk/s3-request-presigner": "3.1121.0",
|
||||
"@better-auth/mcp": "1.7.12",
|
||||
"@better-auth/oauth-provider": "1.7.12",
|
||||
"@earendil-works/chord": "1.5.0",
|
||||
"@earendil-works/pi-ai": "1.5.0",
|
||||
"@earendil-works/pi-durable": "1.5.0",
|
||||
"@earendil-works/chord": "1.7.0",
|
||||
"@earendil-works/pi-ai": "1.7.0",
|
||||
"@earendil-works/pi-durable": "1.7.0",
|
||||
"@google/genai": "2.28.0",
|
||||
"@modelcontextprotocol/client": "2.0.0",
|
||||
"@shumai/db": "workspace:*",
|
||||
|
||||
@@ -92,8 +92,10 @@ export async function openSessionCache(sessionId: string) {
|
||||
throw new Error('Session commit sequence mismatch')
|
||||
seq = receipt.seq
|
||||
}
|
||||
if (result.stored !== commits.length)
|
||||
if (result.kind === 'refused') {
|
||||
throw result.refused ?? new Error('Session restoration refused')
|
||||
}
|
||||
if (result.stored !== commits.length) throw new Error('Session restoration was incomplete')
|
||||
}
|
||||
await save(true)
|
||||
} catch (error) {
|
||||
|
||||
@@ -19,7 +19,7 @@ export const ENV_MAP: Record<string, string> = {
|
||||
openai: 'OPENAI_API_KEY',
|
||||
anthropic: 'ANTHROPIC_API_KEY',
|
||||
'github-copilot': 'COPILOT_GITHUB_TOKEN',
|
||||
'azure-openai-responses': 'AZURE_OPENAI_API_KEY',
|
||||
azure: 'AZURE_OPENAI_API_KEY',
|
||||
deepseek: 'DEEPSEEK_API_KEY',
|
||||
google: 'GEMINI_API_KEY',
|
||||
'google-vertex': 'GOOGLE_CLOUD_API_KEY',
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
{
|
||||
"anthropic": {
|
||||
"models": {
|
||||
"claude-3-5-sonnet-20241022": {
|
||||
"id": "claude-3-5-sonnet-20241022",
|
||||
"name": "Claude 3.5 Sonnet",
|
||||
"tool_call": true,
|
||||
"reasoning": false,
|
||||
"limit": {
|
||||
"context": 200000,
|
||||
"output": 8192
|
||||
},
|
||||
"cost": {
|
||||
"input": 3,
|
||||
"output": 15,
|
||||
"cache_read": 0.3,
|
||||
"cache_write": 3.75
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"openai": {
|
||||
"models": {
|
||||
"gpt-4o": {
|
||||
"id": "gpt-4o",
|
||||
"name": "GPT-4o",
|
||||
"tool_call": true,
|
||||
"reasoning": false,
|
||||
"limit": {
|
||||
"context": 128000,
|
||||
"output": 4096
|
||||
},
|
||||
"cost": {
|
||||
"input": 2.5,
|
||||
"output": 10
|
||||
}
|
||||
},
|
||||
"gpt-4o-extra-new": {
|
||||
"id": "gpt-4o-extra-new",
|
||||
"name": "GPT-4o Extra New",
|
||||
"tool_call": true,
|
||||
"reasoning": false,
|
||||
"limit": {
|
||||
"context": 128000,
|
||||
"output": 4096
|
||||
},
|
||||
"cost": {
|
||||
"input": 2.5,
|
||||
"output": 10
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "meta/llama-3.1-70b-instruct"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": "meta-llama/llama-3.1-8b-instruct",
|
||||
"name": "Meta: Llama 3.1 8B Instruct",
|
||||
"context_length": 131072,
|
||||
"pricing": {
|
||||
"prompt": "0.00000005",
|
||||
"completion": "0.00000008"
|
||||
},
|
||||
"top_provider": {
|
||||
"max_completion_tokens": 8192
|
||||
},
|
||||
"supported_parameters": ["tools"]
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,42 +0,0 @@
|
||||
import type { ThinkingLevel, ThinkingLevelMap } from '@earendil-works/pi-ai'
|
||||
|
||||
export type ModelsDevReasoningOption =
|
||||
| { type: 'toggle' }
|
||||
| {
|
||||
type: 'effort'
|
||||
values: Array<
|
||||
'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'default' | null
|
||||
>
|
||||
}
|
||||
| { type: 'budget_tokens'; min?: number; max?: number }
|
||||
|
||||
const THINKING_LEVELS: readonly ThinkingLevel[] = [
|
||||
'minimal',
|
||||
'low',
|
||||
'medium',
|
||||
'high',
|
||||
'xhigh',
|
||||
'max',
|
||||
]
|
||||
|
||||
/**
|
||||
* Converts models.dev verified effort values into Pi's selectable thinking levels.
|
||||
* Values without a Pi equivalent (`default` and JSON `null`) are intentionally
|
||||
* omitted.
|
||||
*/
|
||||
export function getEffortThinkingLevelMap(
|
||||
options: readonly ModelsDevReasoningOption[],
|
||||
): ThinkingLevelMap | undefined {
|
||||
const effortValues = options.flatMap((option) => (option.type === 'effort' ? option.values : []))
|
||||
if (effortValues.length === 0) return undefined
|
||||
|
||||
const supported = new Set(effortValues)
|
||||
if (!THINKING_LEVELS.some((level) => supported.has(level)) && !supported.has('none'))
|
||||
return undefined
|
||||
|
||||
const map: ThinkingLevelMap = { off: supported.has('none') ? 'none' : null }
|
||||
for (const level of THINKING_LEVELS) {
|
||||
map[level] = supported.has(level) ? level : null
|
||||
}
|
||||
return map
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
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 }
|
||||
}
|
||||
@@ -3,46 +3,53 @@ import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { providerService } from './provider'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import * as generateModelsModule from './generator/generate-models'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
|
||||
import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin'
|
||||
import { z } from 'zod'
|
||||
import modelsDevFixture from './fixtures/models-dev.json'
|
||||
import openRouterFixture from './fixtures/openrouter.json'
|
||||
import nvidiaFixture from './fixtures/nvidia.json'
|
||||
|
||||
const originalFetch = globalThis.fetch
|
||||
const openaiConfig = {
|
||||
api: 'openai-responses',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
apiKey: 'saved-test-key',
|
||||
} satisfies ProviderConfigSerializable
|
||||
|
||||
function setupCatalogFetchMock() {
|
||||
return vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {
|
||||
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
|
||||
if (url.includes('models.dev')) {
|
||||
return new Response(JSON.stringify(modelsDevFixture), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
const candidateConfig = {
|
||||
api: openaiConfig.api,
|
||||
reasoning: true,
|
||||
input: ['text'],
|
||||
contextWindow: 256000,
|
||||
maxTokens: 16000,
|
||||
cost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0 },
|
||||
} satisfies ProviderModel['config']
|
||||
|
||||
function catalogModel(id: string, options?: Record<string, unknown>) {
|
||||
return {
|
||||
...candidateConfig,
|
||||
provider: 'openai',
|
||||
baseUrl: openaiConfig.baseUrl,
|
||||
id,
|
||||
name: id,
|
||||
...options,
|
||||
}
|
||||
}
|
||||
|
||||
function mockCatalog(models: ReturnType<typeof catalogModel>[]) {
|
||||
const requests: Request[] = []
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
|
||||
const request = new Request(input, init)
|
||||
requests.push(request)
|
||||
if (new URL(request.url).origin !== 'https://pi.dev') {
|
||||
throw new Error('Unexpected catalog host')
|
||||
}
|
||||
if (url.includes('openrouter.ai')) {
|
||||
return new Response(JSON.stringify(openRouterFixture), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
if (url.includes('nvidia')) {
|
||||
return new Response(JSON.stringify(nvidiaFixture), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
if (url.includes('ai-gateway')) {
|
||||
return new Response(JSON.stringify({ data: [] }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
return originalFetch(input)
|
||||
return Response.json(Object.fromEntries(models.map((model) => [model.id, model])))
|
||||
})
|
||||
return requests
|
||||
}
|
||||
|
||||
function readyPreview(result: Awaited<ReturnType<typeof providerService.refreshModels>>) {
|
||||
if (result.status !== 'ready') throw new Error('Expected refreshed models')
|
||||
return result
|
||||
}
|
||||
|
||||
type ProviderModel = z.infer<typeof providerModelSchema>
|
||||
@@ -385,182 +392,270 @@ describe('ProviderService', () => {
|
||||
expect((modelsAfterUpdate[1].config as { api: string }).api).toBe('anthropic-messages')
|
||||
})
|
||||
|
||||
it('should check for updates and correctly segregate new vs existing providers', async () => {
|
||||
const fetchSpy = setupCatalogFetchMock()
|
||||
try {
|
||||
// 1. Check updates with empty team: all discovered providers are new
|
||||
const emptyTeam = await prisma.team.create({
|
||||
data: { name: 'Empty Provider Team' },
|
||||
describe('model refresh', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
it('reports resolved credentials and eligibility separately and preserves legacy Kimi', async () => {
|
||||
vi.stubEnv('CUSTOM_OPENAI_KEY', 'a-resolved-test-key')
|
||||
vi.stubEnv('UNSET_ANTHROPIC_KEY', undefined)
|
||||
const team = await prisma.team.create({ data: { name: 'Providers' } })
|
||||
const configured = await providerService.create(team.id, 'OpenAI production', {
|
||||
...openaiConfig,
|
||||
apiKey: 'CUSTOM_OPENAI_KEY',
|
||||
})
|
||||
const initialCheck = await providerService.checkUpdates(emptyTeam.id)
|
||||
expect(initialCheck.totalNewProviders).toBeGreaterThan(0)
|
||||
expect(initialCheck.totalNewModels).toBeGreaterThan(0)
|
||||
expect(initialCheck.providers.every((p) => p.isNewProvider)).toBe(true)
|
||||
const unconfigured = await providerService.create(team.id, 'anthropic', {
|
||||
api: 'anthropic-messages',
|
||||
baseUrl: 'https://api.anthropic.com',
|
||||
apiKey: 'UNSET_ANTHROPIC_KEY',
|
||||
})
|
||||
const legacyConfig = {
|
||||
api: 'anthropic-messages',
|
||||
baseUrl: 'https://api.kimi.com/coding',
|
||||
apiKey: 'literal-kimi-key',
|
||||
} satisfies ProviderConfigSerializable
|
||||
const legacy = await providerService.create(team.id, 'kimi-coding', legacyConfig)
|
||||
const local = await providerService.create(team.id, 'Local Ollama', {
|
||||
api: 'openai-completions',
|
||||
baseUrl: 'http://localhost:11434/v1',
|
||||
})
|
||||
vi.stubEnv('AWS_PROFILE', 'test-profile')
|
||||
const bedrock = await providerService.create(team.id, 'amazon-bedrock', {
|
||||
api: 'bedrock-converse-stream',
|
||||
})
|
||||
const providers = await providerService.listByTeam(team.id)
|
||||
expect(providers).toHaveLength(5)
|
||||
expect(providers).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
id: configured.id,
|
||||
configured: true,
|
||||
refreshUnavailableReason: null,
|
||||
config: { ...openaiConfig, apiKey: 'CUSTOM_OPENAI_KEY' },
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: unconfigured.id,
|
||||
configured: false,
|
||||
refreshUnavailableReason: null,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: legacy.id,
|
||||
configured: true,
|
||||
refreshUnavailableReason: 'legacy_kimi_connection',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: local.id,
|
||||
configured: true,
|
||||
refreshUnavailableReason: 'unsupported_connection',
|
||||
}),
|
||||
expect.objectContaining({ id: bedrock.id, configured: true }),
|
||||
]),
|
||||
)
|
||||
|
||||
// 2. With default team (which has builtin providers initialized)
|
||||
const teamWithBuiltins = await teamService.ensureDefaultTeam()
|
||||
|
||||
// 3. Check updates after init: existing providers should have isNewProvider: false
|
||||
const afterInitCheck = await providerService.checkUpdates(teamWithBuiltins.id)
|
||||
const existing = afterInitCheck.providers.find((p) => !p.isNewProvider)
|
||||
expect(existing).toBeDefined()
|
||||
if (existing) {
|
||||
expect(existing.isNewProvider).toBe(false)
|
||||
const dbModels = await providerService.listModelsByProvider(
|
||||
teamWithBuiltins.id,
|
||||
(await providerService.listByTeam(teamWithBuiltins.id)).find(
|
||||
(p) => p.name === existing.name,
|
||||
)!.id,
|
||||
)
|
||||
const dbModelIds = new Set(dbModels.map((m) => m.modelId))
|
||||
for (const m of existing.models) {
|
||||
expect(dbModelIds.has(m.modelId)).toBe(false)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
fetchSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('should throw an error when upstream catalog fetch fails in checkUpdates', async () => {
|
||||
const team = await teamService.ensureDefaultTeam()
|
||||
const spy = vi
|
||||
.spyOn(generateModelsModule, 'generateModels')
|
||||
.mockRejectedValueOnce(new Error('Failed to load models.dev catalog: 502 Bad Gateway'))
|
||||
|
||||
await expect(providerService.checkUpdates(team.id)).rejects.toThrow(
|
||||
'Failed to load models.dev catalog: 502 Bad Gateway',
|
||||
)
|
||||
spy.mockRestore()
|
||||
})
|
||||
|
||||
it('should throw an error when upstream catalog is empty in checkUpdates', async () => {
|
||||
const team = await teamService.ensureDefaultTeam()
|
||||
const spy = vi.spyOn(generateModelsModule, 'generateModels').mockResolvedValueOnce({
|
||||
providers: {},
|
||||
groupedProviders: {},
|
||||
sortedProviderIds: [],
|
||||
const requests = mockCatalog([])
|
||||
await expect(providerService.refreshModels(team.id, unconfigured.id)).resolves.toMatchObject({
|
||||
status: 'ready',
|
||||
models: [],
|
||||
})
|
||||
await expect(providerService.refreshModels(team.id, legacy.id)).resolves.toEqual({
|
||||
status: 'unavailable',
|
||||
reason: 'legacy_kimi_connection',
|
||||
})
|
||||
expect(requests.map(({ url }) => new URL(url).pathname)).toEqual([
|
||||
'/api/models/providers/anthropic',
|
||||
])
|
||||
expect(await providerService.getById(legacy.id)).toMatchObject({ config: legacyConfig })
|
||||
})
|
||||
|
||||
await expect(providerService.checkUpdates(team.id)).rejects.toThrow(
|
||||
'Failed to retrieve model catalog from upstream services',
|
||||
)
|
||||
spy.mockRestore()
|
||||
})
|
||||
it('refreshes only the requested provider and filters existing and incompatible models', async () => {
|
||||
vi.stubEnv('OPENAI_API_KEY', openaiConfig.apiKey)
|
||||
const team = await teamService.ensureDefaultTeam()
|
||||
const providers = await providerService.listByTeam(team.id)
|
||||
const openai = providers.find(({ name }) => name === 'openai')!
|
||||
const existingModels = await providerService.listModelsByProvider(team.id, openai.id)
|
||||
const requests = mockCatalog([
|
||||
catalogModel(existingModels[0].modelId),
|
||||
catalogModel('new-model', {
|
||||
compat: { supportsStrictMode: true },
|
||||
thinkingLevelMap: { low: 'low' },
|
||||
}),
|
||||
catalogModel('wrong-api', { api: 'openai-completions' }),
|
||||
catalogModel('wrong-url', { baseUrl: 'https://other.example/v1' }),
|
||||
catalogModel('wrong-provider', { provider: 'anthropic' }),
|
||||
catalogModel('not-chat', { type: 'image' }),
|
||||
catalogModel('invalid-compat', { compat: { supportsStrictMode: 'yes' } }),
|
||||
])
|
||||
|
||||
it('should apply sync by adding selected providers and models without modifying existing ones', async () => {
|
||||
const team = await teamService.ensureDefaultTeam()
|
||||
|
||||
// Create an existing provider with 1 model and a custom apiKey
|
||||
const existingProvider = await providerService.create(
|
||||
team.id,
|
||||
'test-existing-provider',
|
||||
{ api: 'openai-responses', apiKey: 'custom-api-key', baseUrl: 'https://example.com' },
|
||||
[
|
||||
{
|
||||
modelId: 'existing-m1',
|
||||
name: 'Existing Model 1',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
const result = await providerService.refreshModels(team.id, openai.id)
|
||||
expect(result).toMatchObject({
|
||||
status: 'ready',
|
||||
models: [
|
||||
{
|
||||
modelId: 'new-model',
|
||||
name: 'new-model',
|
||||
config: {
|
||||
...candidateConfig,
|
||||
compat: { supportsStrictMode: true },
|
||||
thinkingLevelMap: { low: 'low' },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
// Apply sync with 1 new provider and 1 new model on the existing provider
|
||||
const syncResult = await providerService.applySync(team.id, {
|
||||
providers: [
|
||||
{
|
||||
name: 'test-new-synced-provider',
|
||||
isNewProvider: true,
|
||||
config: {
|
||||
api: 'anthropic-messages',
|
||||
apiKey: 'ENV_SYNC_KEY',
|
||||
baseUrl: 'https://api.anthropic.com',
|
||||
},
|
||||
models: [
|
||||
{
|
||||
modelId: 'new-p-m1',
|
||||
name: 'New Provider Model 1',
|
||||
config: {
|
||||
api: 'anthropic-messages',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 200000,
|
||||
maxTokens: 8192,
|
||||
cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'test-existing-provider',
|
||||
isNewProvider: false,
|
||||
config: { api: 'openai-responses', apiKey: 'should-not-override' },
|
||||
models: [
|
||||
{
|
||||
modelId: 'existing-m2',
|
||||
name: 'Newly Added Model 2',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: true,
|
||||
input: ['text'],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
// Duplicate model that already exists: should be ignored
|
||||
{
|
||||
modelId: 'existing-m1',
|
||||
name: 'Existing Model 1 Overwrite Attempt',
|
||||
config: {
|
||||
api: 'openai-responses',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 999999,
|
||||
maxTokens: 999999,
|
||||
cost: { input: 9, output: 9, cacheRead: 9, cacheWrite: 9 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
],
|
||||
})
|
||||
expect(requests.map(({ url }) => new URL(url).pathname)).toEqual([
|
||||
'/api/models/providers/openai',
|
||||
])
|
||||
expect(requests[0].headers.has('Authorization')).toBe(false)
|
||||
expect(JSON.stringify(result)).not.toContain(openaiConfig.apiKey)
|
||||
expect(await providerService.listModelsByProvider(team.id, openai.id)).toEqual(existingModels)
|
||||
expect(await providerService.listByTeam(team.id)).toEqual(providers)
|
||||
})
|
||||
|
||||
expect(syncResult.addedProviders).toBe(1)
|
||||
expect(syncResult.addedModels).toBe(2)
|
||||
it('uses the versioned public OpenRouter catalog without sending saved credentials', async () => {
|
||||
const openRouterKey = 'saved-openrouter-test-key'
|
||||
vi.stubEnv('SHUMAI_TEST_OPENROUTER_KEY', openRouterKey)
|
||||
const team = await prisma.team.create({ data: { name: 'OpenRouter' } })
|
||||
const baseUrl = 'https://openrouter.ai/api/v1'
|
||||
const api = 'openai-completions' as const
|
||||
const provider = await providerService.create(team.id, 'openrouter', {
|
||||
api,
|
||||
baseUrl: baseUrl + '/',
|
||||
apiKey: 'SHUMAI_TEST_OPENROUTER_KEY',
|
||||
})
|
||||
const modelId = 'org/new-openrouter-model'
|
||||
const requests: Request[] = []
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
|
||||
const request = new Request(input, init)
|
||||
requests.push(request)
|
||||
return Response.json({
|
||||
[modelId]: { ...catalogModel(modelId, { api, baseUrl }), provider: 'openrouter' },
|
||||
})
|
||||
})
|
||||
|
||||
// Verify existing provider config was NOT modified
|
||||
const reloadedExisting = await providerService.getById(existingProvider.id)
|
||||
expect((reloadedExisting?.config as { apiKey: string }).apiKey).toBe('custom-api-key')
|
||||
const { models } = readyPreview(await providerService.refreshModels(team.id, provider.id))
|
||||
expect(models.map(({ modelId }) => modelId)).toEqual([modelId])
|
||||
expect(requests.map(({ url }) => url)).toEqual([
|
||||
'https://pi.dev/api/models/providers/openrouter?pi-version=1.7.0',
|
||||
])
|
||||
expect(requests[0].headers.has('Authorization')).toBe(false)
|
||||
|
||||
// Verify existing model was NOT modified
|
||||
const existingModels = await providerService.listModelsByProvider(team.id, existingProvider.id)
|
||||
expect(existingModels).toHaveLength(2)
|
||||
const m1 = existingModels.find((m) => m.modelId === 'existing-m1')
|
||||
expect(m1?.name).toBe('Existing Model 1')
|
||||
expect((m1?.config as { contextWindow: number }).contextWindow).toBe(128000)
|
||||
const customProvider = await providerService.update(team.id, provider.id, {
|
||||
...provider.config,
|
||||
baseUrl: 'https://openrouter-proxy.example/api/v1',
|
||||
})
|
||||
await expect(providerService.refreshModels(team.id, customProvider.id)).resolves.toEqual({
|
||||
status: 'unavailable',
|
||||
reason: 'unsupported_connection',
|
||||
})
|
||||
expect(requests).toHaveLength(1)
|
||||
})
|
||||
|
||||
// Verify newly added model on existing provider
|
||||
const m2 = existingModels.find((m) => m.modelId === 'existing-m2')
|
||||
expect(m2).toBeDefined()
|
||||
expect(m2?.name).toBe('Newly Added Model 2')
|
||||
it('distinguishes a successful empty preview from an upstream error', async () => {
|
||||
vi.stubEnv('OPENAI_API_KEY', openaiConfig.apiKey)
|
||||
const team = await teamService.ensureDefaultTeam()
|
||||
const provider = (await providerService.listByTeam(team.id)).find(
|
||||
({ name }) => name === 'openai',
|
||||
)!
|
||||
mockCatalog([])
|
||||
await expect(providerService.refreshModels(team.id, provider.id)).resolves.toMatchObject({
|
||||
status: 'ready',
|
||||
models: [],
|
||||
})
|
||||
vi.restoreAllMocks()
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch')
|
||||
fetchMock.mockResolvedValueOnce(new Response(null, { status: 404 }))
|
||||
await expect(providerService.refreshModels(team.id, provider.id)).resolves.toEqual({
|
||||
status: 'unavailable',
|
||||
reason: 'catalog_unavailable',
|
||||
})
|
||||
fetchMock.mockResolvedValueOnce(Response.json({ error: 'malformed catalog' }))
|
||||
await expect(providerService.refreshModels(team.id, provider.id)).rejects.toMatchObject({
|
||||
status: 502,
|
||||
})
|
||||
fetchMock.mockRejectedValueOnce(new DOMException('Timed out', 'TimeoutError'))
|
||||
|
||||
// Verify newly added provider
|
||||
const providers = await providerService.listByTeam(team.id)
|
||||
const newProvider = providers.find((p) => p.name === 'test-new-synced-provider')
|
||||
expect(newProvider).toBeDefined()
|
||||
expect(newProvider?.isBuiltin).toBe(true)
|
||||
expect((newProvider?.config as { apiKey: string }).apiKey).toBe('ENV_SYNC_KEY')
|
||||
await expect(providerService.refreshModels(team.id, provider.id)).rejects.toMatchObject({
|
||||
status: 502,
|
||||
})
|
||||
})
|
||||
|
||||
const newProviderModels = await providerService.listModelsByProvider(team.id, newProvider!.id)
|
||||
expect(newProviderModels).toHaveLength(1)
|
||||
expect(newProviderModels[0].modelId).toBe('new-p-m1')
|
||||
it('imports only the selected models once and preserves existing models and settings', async () => {
|
||||
vi.stubEnv('OPENAI_API_KEY', openaiConfig.apiKey)
|
||||
const team = await teamService.ensureDefaultTeam()
|
||||
const provider = (await providerService.listByTeam(team.id)).find(
|
||||
({ name }) => name === 'openai',
|
||||
)!
|
||||
const original = await providerService.getById(provider.id)
|
||||
const existing = await providerService.listModelsByProvider(team.id, provider.id)
|
||||
mockCatalog([catalogModel('new-model'), catalogModel('unselected-model')])
|
||||
const preview = readyPreview(await providerService.refreshModels(team.id, provider.id))
|
||||
const selection = { providerUpdatedAt: preview.providerUpdatedAt, modelIds: ['new-model'] }
|
||||
|
||||
await expect(providerService.importModels(team.id, provider.id, selection)).resolves.toEqual({
|
||||
addedModels: 1,
|
||||
})
|
||||
await expect(providerService.importModels(team.id, provider.id, selection)).resolves.toEqual({
|
||||
addedModels: 0,
|
||||
})
|
||||
expect(await providerService.listModelsByProvider(team.id, provider.id)).toEqual([
|
||||
expect.objectContaining({ modelId: 'new-model', config: candidateConfig }),
|
||||
...existing,
|
||||
])
|
||||
expect(await providerService.getById(provider.id)).toEqual(original)
|
||||
})
|
||||
|
||||
it('rejects out-of-team, unknown, and stale selections without adding models', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Refresh Team' } })
|
||||
const otherTeam = await prisma.team.create({ data: { name: 'Other Team' } })
|
||||
const provider = await providerService.create(team.id, 'openai', openaiConfig)
|
||||
const requests = mockCatalog([catalogModel('new-model')])
|
||||
await expect(providerService.refreshModels(otherTeam.id, provider.id)).rejects.toMatchObject({
|
||||
status: 404,
|
||||
})
|
||||
expect(requests).toHaveLength(0)
|
||||
|
||||
const preview = readyPreview(await providerService.refreshModels(team.id, provider.id))
|
||||
const selection = { providerUpdatedAt: preview.providerUpdatedAt, modelIds: ['new-model'] }
|
||||
await expect(
|
||||
providerService.importModels(otherTeam.id, provider.id, selection),
|
||||
).rejects.toMatchObject({ status: 404 })
|
||||
await expect(
|
||||
providerService.importModels(team.id, provider.id, {
|
||||
...selection,
|
||||
modelIds: ['new-model', 'unknown'],
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 409 })
|
||||
|
||||
await providerService.update(team.id, provider.id, { ...openaiConfig, apiKey: 'changed-key' })
|
||||
await expect(
|
||||
providerService.importModels(team.id, provider.id, selection),
|
||||
).rejects.toMatchObject({ status: 409 })
|
||||
expect(await providerService.listModelsByProvider(team.id, provider.id)).toEqual([])
|
||||
})
|
||||
|
||||
it('refreshes legacy Azure connections using only configured deployment mappings', async () => {
|
||||
vi.stubEnv('AZURE_OPENAI_DEPLOYMENT_NAME_MAP', undefined)
|
||||
const team = await prisma.team.create({ data: { name: 'Azure models' } })
|
||||
const provider = await providerService.create(team.id, 'azure-openai-responses', {
|
||||
api: 'azure-openai-responses',
|
||||
baseUrl: 'https://example.openai.azure.com/openai/v1',
|
||||
})
|
||||
const azure = { provider: 'azure', api: 'azure-openai-responses', baseUrl: '' }
|
||||
const requests = mockCatalog([
|
||||
catalogModel('gpt-deployed', azure),
|
||||
catalogModel('gpt-unmapped', azure),
|
||||
])
|
||||
await expect(providerService.refreshModels(team.id, provider.id)).resolves.toEqual({
|
||||
status: 'unavailable',
|
||||
reason: 'azure_deployment_required',
|
||||
})
|
||||
vi.stubEnv('AZURE_OPENAI_DEPLOYMENT_NAME_MAP', 'gpt-deployed=team-deployment')
|
||||
const preview = readyPreview(await providerService.refreshModels(team.id, provider.id))
|
||||
expect(preview.models.map(({ modelId }) => modelId)).toEqual(['gpt-deployed'])
|
||||
expect(requests.map(({ url }) => new URL(url).pathname)).toEqual([
|
||||
'/api/models/providers/azure',
|
||||
])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,22 +1,16 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import {
|
||||
CreateModelRequest,
|
||||
ImportProviderModelsRequest,
|
||||
ProviderConfigSerializable,
|
||||
ProviderModelRefreshResponse,
|
||||
providerModelSchema,
|
||||
SyncApplyRequest,
|
||||
SyncApplyResponse,
|
||||
SyncCheckResponse,
|
||||
SyncModelItem,
|
||||
SyncProviderItem,
|
||||
UpdateModelRequest,
|
||||
} from '@shumai/dtos'
|
||||
import {
|
||||
ENV_MAP,
|
||||
getBuiltinProvidersMap,
|
||||
PRIORITY_PROVIDERS,
|
||||
} from '@shumai/core/src/provider/builtin'
|
||||
import { generateModels } from '@shumai/core/src/provider/generator/generate-models'
|
||||
import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { z } from 'zod'
|
||||
import { discoverProviderModels, getRefreshConnection, isProviderConfigured } from './model-refresh'
|
||||
|
||||
type ProviderModel = z.infer<typeof providerModelSchema>
|
||||
|
||||
@@ -70,11 +64,23 @@ export class ProviderService {
|
||||
orderBy: { id: 'desc' },
|
||||
})
|
||||
|
||||
return providers.map((p) => ({
|
||||
...p,
|
||||
modelsCount: p._count.models,
|
||||
_count: undefined,
|
||||
}))
|
||||
return providers.map(
|
||||
({ _count, id, teamId, name, config, isBuiltin, createdAt, updatedAt }) => {
|
||||
const connection = getRefreshConnection(name, config)
|
||||
return {
|
||||
id,
|
||||
teamId,
|
||||
name,
|
||||
config,
|
||||
isBuiltin,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
modelsCount: _count.models,
|
||||
configured: isProviderConfigured(name, config),
|
||||
refreshUnavailableReason: connection.unavailableReason,
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
async getById(id: string) {
|
||||
@@ -124,6 +130,11 @@ export class ProviderService {
|
||||
name?: string,
|
||||
) {
|
||||
return this.prismaClient.$transaction(async (tx) => {
|
||||
const provider = await tx.provider.update({
|
||||
where: { id, teamId },
|
||||
data: { config, ...(name ? { name } : {}) },
|
||||
})
|
||||
|
||||
if (models !== undefined) {
|
||||
const existingModels = await tx.model.findMany({
|
||||
where: { providerId: id },
|
||||
@@ -189,15 +200,7 @@ export class ProviderService {
|
||||
}
|
||||
}
|
||||
|
||||
// Update provider config and optional name
|
||||
return tx.provider.update({
|
||||
where: { id, teamId },
|
||||
data: {
|
||||
config,
|
||||
...(name ? { name } : {}),
|
||||
},
|
||||
include: { models: true },
|
||||
})
|
||||
return { ...provider, models: await tx.model.findMany({ where: { providerId: id } }) }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -305,179 +308,66 @@ export class ProviderService {
|
||||
})
|
||||
}
|
||||
|
||||
async checkUpdates(teamId: string): Promise<SyncCheckResponse> {
|
||||
const catalog = await generateModels({ strict: true, timeoutMs: 30000 })
|
||||
|
||||
if (!catalog || catalog.sortedProviderIds.length === 0) {
|
||||
throw new Error('Failed to retrieve model catalog from upstream services')
|
||||
}
|
||||
|
||||
const existingProviders = await this.prismaClient.provider.findMany({
|
||||
where: { teamId },
|
||||
include: { models: true },
|
||||
async refreshModels(teamId: string, providerId: string): Promise<ProviderModelRefreshResponse> {
|
||||
const provider = await this.prismaClient.provider.findUnique({
|
||||
where: { id: providerId, teamId },
|
||||
include: { models: { select: { modelId: true } } },
|
||||
})
|
||||
if (!provider) throw new HTTPException(404, { message: 'Provider not found' })
|
||||
|
||||
const existingProviderMap = new Map<string, (typeof existingProviders)[number]>()
|
||||
for (const p of existingProviders) {
|
||||
existingProviderMap.set(p.name, p)
|
||||
const connection = getRefreshConnection(provider.name, provider.config)
|
||||
if (connection.unavailableReason) {
|
||||
return { status: 'unavailable', reason: connection.unavailableReason }
|
||||
}
|
||||
|
||||
const items: SyncProviderItem[] = []
|
||||
let totalNewProviders = 0
|
||||
let totalNewModels = 0
|
||||
|
||||
for (const providerId of catalog.sortedProviderIds) {
|
||||
const modelsMap = catalog.providers[providerId]
|
||||
if (!modelsMap) continue
|
||||
const modelList = Object.values(modelsMap)
|
||||
if (modelList.length === 0) continue
|
||||
|
||||
const existingProvider = existingProviderMap.get(providerId)
|
||||
|
||||
if (!existingProvider) {
|
||||
const firstModel = modelList[0]
|
||||
const newModels: SyncModelItem[] = modelList.map((m) => ({
|
||||
modelId: m.id,
|
||||
name: m.name || m.id,
|
||||
config: {
|
||||
api: m.api as ProviderConfigSerializable['api'],
|
||||
reasoning: m.reasoning ?? false,
|
||||
input: (m.input ?? ['text']) as ('text' | 'image')[],
|
||||
contextWindow: m.contextWindow,
|
||||
maxTokens: m.maxTokens,
|
||||
cost: {
|
||||
input: m.cost?.input ?? 0,
|
||||
output: m.cost?.output ?? 0,
|
||||
cacheRead: m.cost?.cacheRead ?? 0,
|
||||
cacheWrite: m.cost?.cacheWrite ?? 0,
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
items.push({
|
||||
name: providerId,
|
||||
isNewProvider: true,
|
||||
config: {
|
||||
api: firstModel.api as ProviderConfigSerializable['api'],
|
||||
baseUrl: firstModel.baseUrl,
|
||||
apiKey: ENV_MAP[providerId] || '',
|
||||
},
|
||||
models: newModels,
|
||||
})
|
||||
|
||||
totalNewProviders++
|
||||
totalNewModels += newModels.length
|
||||
} else {
|
||||
const existingModelIds = new Set(existingProvider.models.map((m) => m.modelId))
|
||||
const newModels: SyncModelItem[] = []
|
||||
|
||||
for (const m of modelList) {
|
||||
if (!existingModelIds.has(m.id)) {
|
||||
newModels.push({
|
||||
modelId: m.id,
|
||||
name: m.name || m.id,
|
||||
config: {
|
||||
api: m.api as ProviderConfigSerializable['api'],
|
||||
reasoning: m.reasoning ?? false,
|
||||
input: (m.input ?? ['text']) as ('text' | 'image')[],
|
||||
contextWindow: m.contextWindow,
|
||||
maxTokens: m.maxTokens,
|
||||
cost: {
|
||||
input: m.cost?.input ?? 0,
|
||||
output: m.cost?.output ?? 0,
|
||||
cacheRead: m.cost?.cacheRead ?? 0,
|
||||
cacheWrite: m.cost?.cacheWrite ?? 0,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (newModels.length > 0) {
|
||||
items.push({
|
||||
name: providerId,
|
||||
isNewProvider: false,
|
||||
config: existingProvider.config as ProviderConfigSerializable,
|
||||
models: newModels,
|
||||
})
|
||||
totalNewModels += newModels.length
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
items.sort((a, b) => {
|
||||
const indexA = PRIORITY_PROVIDERS.indexOf(a.name)
|
||||
const indexB = PRIORITY_PROVIDERS.indexOf(b.name)
|
||||
if (indexA !== -1 && indexB !== -1) return indexA - indexB
|
||||
if (indexA !== -1) return -1
|
||||
if (indexB !== -1) return 1
|
||||
return a.name.localeCompare(b.name)
|
||||
})
|
||||
|
||||
const catalog = await discoverProviderModels(connection.piProviderId, provider.config)
|
||||
if (catalog.status === 'unavailable') return catalog
|
||||
const existingIds = new Set(provider.models.map(({ modelId }) => modelId))
|
||||
return {
|
||||
providers: items,
|
||||
totalNewProviders,
|
||||
totalNewModels,
|
||||
status: 'ready',
|
||||
providerUpdatedAt: provider.updatedAt.toISOString(),
|
||||
models: catalog.models.filter(({ modelId }) => !existingIds.has(modelId)),
|
||||
}
|
||||
}
|
||||
|
||||
async applySync(teamId: string, payload: SyncApplyRequest): Promise<SyncApplyResponse> {
|
||||
let addedProviders = 0
|
||||
let addedModels = 0
|
||||
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
for (const providerItem of payload.providers) {
|
||||
let providerId: string
|
||||
|
||||
if (providerItem.isNewProvider) {
|
||||
const existing = await tx.provider.findFirst({
|
||||
where: { teamId, name: providerItem.name },
|
||||
})
|
||||
if (!existing) {
|
||||
const created = await tx.provider.create({
|
||||
data: {
|
||||
teamId,
|
||||
name: providerItem.name,
|
||||
isBuiltin: true,
|
||||
config: providerItem.config,
|
||||
},
|
||||
})
|
||||
providerId = created.id
|
||||
addedProviders++
|
||||
} else {
|
||||
providerId = existing.id
|
||||
}
|
||||
} else {
|
||||
const existing = await tx.provider.findFirst({
|
||||
where: { teamId, name: providerItem.name },
|
||||
})
|
||||
if (!existing) continue
|
||||
providerId = existing.id
|
||||
}
|
||||
|
||||
for (const modelItem of providerItem.models) {
|
||||
const existingModel = await tx.model.findFirst({
|
||||
where: {
|
||||
providerId,
|
||||
modelId: modelItem.modelId,
|
||||
},
|
||||
})
|
||||
if (!existingModel) {
|
||||
await tx.model.create({
|
||||
data: {
|
||||
providerId,
|
||||
modelId: modelItem.modelId,
|
||||
name: modelItem.name || modelItem.modelId,
|
||||
config: modelItem.config,
|
||||
},
|
||||
})
|
||||
addedModels++
|
||||
}
|
||||
}
|
||||
}
|
||||
async importModels(
|
||||
teamId: string,
|
||||
providerId: string,
|
||||
{ modelIds, providerUpdatedAt }: ImportProviderModelsRequest,
|
||||
) {
|
||||
const provider = await this.prismaClient.provider.findUnique({
|
||||
where: { id: providerId, teamId },
|
||||
include: { models: { where: { modelId: { in: modelIds } }, select: { modelId: true } } },
|
||||
})
|
||||
if (!provider) throw new HTTPException(404, { message: 'Provider not found' })
|
||||
const staleSelection = () =>
|
||||
new HTTPException(409, { message: 'Refresh the model list before importing' })
|
||||
if (provider.updatedAt.toISOString() !== providerUpdatedAt) throw staleSelection()
|
||||
const existingIds = new Set(provider.models.map(({ modelId }) => modelId))
|
||||
const newIds = new Set(modelIds.filter((modelId) => !existingIds.has(modelId)))
|
||||
if (newIds.size === 0) return { addedModels: 0 }
|
||||
|
||||
return { addedProviders, addedModels }
|
||||
const connection = getRefreshConnection(provider.name, provider.config)
|
||||
if (connection.unavailableReason) throw staleSelection()
|
||||
const catalog = await discoverProviderModels(connection.piProviderId, provider.config)
|
||||
if (catalog.status === 'unavailable') throw staleSelection()
|
||||
const models = catalog.models.filter(({ modelId }) => newIds.has(modelId))
|
||||
if (models.length !== newIds.size) throw staleSelection()
|
||||
|
||||
return this.prismaClient.$transaction(async (tx) => {
|
||||
// The network request finishes before we lock the connection for the insert.
|
||||
const [locked] = await tx.$queryRaw<{ updatedAt: Date }[]>`
|
||||
SELECT updated_at AS "updatedAt" FROM providers
|
||||
WHERE id = ${providerId} AND team_id = ${teamId} FOR NO KEY UPDATE
|
||||
`
|
||||
if (!locked) throw new HTTPException(404, { message: 'Provider not found' })
|
||||
if (locked.updatedAt.toISOString() !== providerUpdatedAt) throw staleSelection()
|
||||
|
||||
const { count } = await tx.model.createMany({
|
||||
data: models.map(({ modelId, name, config }) => ({ providerId, modelId, name, config })),
|
||||
skipDuplicates: true,
|
||||
})
|
||||
return { addedModels: count }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user