( allModels: OpenRouterModel[], preferredModelIds: string[] )
| 37 | * @param preferredModelIds - List of preferred model IDs that should be active |
| 38 | * @returns Summary of sync operation |
| 39 | */ |
| 40 | export async function syncOpenRouterModels( |
| 41 | allModels: OpenRouterCatalogModel[], |
| 42 | preferredModelIds: string[], |
| 43 | additionalModelIds: string[] = [] |
| 44 | ): Promise<SyncOpenRouterResult> { |
| 45 | // Create a map for quick lookup |
| 46 | const allModelsMap = new Map(allModels.map(model => [model.id, model])); |
| 47 | const additionalModelIdSet = new Set(additionalModelIds); |
| 48 | const targetModelData = [...allModelsMap.values()].filter( |
| 49 | model => preferredModelIds.includes(model.id) || additionalModelIdSet.has(model.id) |
| 50 | ); |
| 51 | |
| 52 | // Get ALL existing model stats from database (not just preferred ones) |
| 53 | const existingStats = await db.select().from(modelStats); |
| 54 | const existingStatsMap = new Map(existingStats.map(stat => [stat.openrouterId, stat])); |
| 55 | |
| 56 | const newModels: string[] = []; |
| 57 | const updatedModels: string[] = []; |
| 58 | const modelsToInsert: Array<typeof modelStats.$inferInsert> = []; |
| 59 | const modelsToUpdate: Array<{ id: string; data: Partial<typeof modelStats.$inferInsert> }> = []; |
| 60 | |
| 61 | for (const model of targetModelData) { |
| 62 | const existing = existingStatsMap.get(model.id); |
| 63 | const isRecommended = preferredModelIds.includes(model.id); |
| 64 | if (existing && !isRecommended) continue; |
| 65 | |
| 66 | if (existing) { |
| 67 | // Update existing preferred model - set isActive=true and update data |
| 68 | modelsToUpdate.push({ |
| 69 | id: existing.id, |
| 70 | data: { |
| 71 | isActive: true, |
| 72 | isRecommended, |
| 73 | ...deriveModelStatsIdentity(model.id), |
| 74 | name: modelNameWithRetirement(model), |
| 75 | description: model.description, |
| 76 | priceInput: toPricePerMillion(model.pricing?.prompt), |
| 77 | priceOutput: toPricePerMillion(model.pricing?.completion), |
| 78 | contextLength: model.context_length ?? null, |
| 79 | maxOutputTokens: model.top_provider?.max_completion_tokens ?? null, |
| 80 | inputModalities: model.architecture?.input_modalities ?? null, |
| 81 | openrouterData: sql`${JSON.stringify(model)}::jsonb` as unknown as OpenRouterApiModel, |
| 82 | }, |
| 83 | }); |
| 84 | updatedModels.push(model.id); |
| 85 | } else { |
| 86 | modelsToInsert.push({ |
| 87 | isActive: true, |
| 88 | isRecommended, |
| 89 | openrouterId: model.id, |
| 90 | ...deriveModelStatsIdentity(model.id), |
| 91 | name: modelNameWithRetirement(model), |
| 92 | description: model.description, |
| 93 | priceInput: toPricePerMillion(model.pricing?.prompt), |
| 94 | priceOutput: toPricePerMillion(model.pricing?.completion), |
| 95 | contextLength: model.context_length ?? null, |
| 96 | maxOutputTokens: model.top_provider?.max_completion_tokens ?? null, |
no test coverage detected