-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathsync_models.ts
More file actions
1459 lines (1315 loc) · 47 KB
/
sync_models.ts
File metadata and controls
1459 lines (1315 loc) · 47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from "fs";
import https from "https";
import path from "path";
import { z } from "zod/v3";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
import { exec, spawn } from "child_process";
import { promisify } from "util";
import { ModelSchema, ModelSpec } from "../schema/models";
const execAsync = promisify(exec);
// Zod schema for individual model details
const searchContextCostPerQuerySchema = z
.object({
search_context_size_low: z.number().optional(),
search_context_size_medium: z.number().optional(),
search_context_size_high: z.number().optional(),
})
.optional();
// Schema for LiteLLM remote model details
const liteLLMModelDetailSchema = z
.object({
max_tokens: z.union([z.number(), z.string()]).optional(), // LEGACY: Can be number or string
max_input_tokens: z
.preprocess(
(val) => (typeof val === "string" ? parseInt(val, 10) : val),
z.number().optional(),
)
.optional(),
max_output_tokens: z
.preprocess(
(val) => (typeof val === "string" ? parseInt(val, 10) : val),
z.number().optional(),
)
.optional(),
input_cost_per_token: z.number().optional(),
output_cost_per_token: z.number().optional(),
input_cost_per_mil_tokens: z.number().optional(), // From LiteLLM if available
output_cost_per_mil_tokens: z.number().optional(), // From LiteLLM if available
output_cost_per_reasoning_token: z.number().optional(),
cache_creation_input_token_cost: z.number().optional(), // from LiteLLM, maps to input_cache_write
cache_read_input_token_cost: z.number().optional(), // from LiteLLM, maps to input_cache_read
litellm_provider: z.string().optional(),
mode: z
.enum([
"chat",
"embedding",
"completion",
"image_generation",
"audio_transcription",
"audio_speech",
"moderation",
"rerank",
"responses",
"video_generation",
"search",
"ocr",
"vector_store",
])
.optional(),
supports_function_calling: z.boolean().optional(),
supports_parallel_function_calling: z.boolean().optional(),
supports_vision: z.boolean().optional(),
supports_audio_input: z.boolean().optional(),
supports_audio_output: z.boolean().optional(),
supports_prompt_caching: z.boolean().optional(),
supports_response_schema: z.boolean().optional(),
supports_system_messages: z.boolean().optional(),
supports_reasoning: z.boolean().optional(),
supports_web_search: z.boolean().optional(),
search_context_cost_per_query: searchContextCostPerQuerySchema,
deprecation_date: z.string().optional(), // YYYY-MM-DD
})
.passthrough();
const liteLLMModelListSchema = z.record(liteLLMModelDetailSchema);
type LiteLLMModelDetail = z.infer<typeof liteLLMModelDetailSchema>;
type LiteLLMModelList = z.infer<typeof liteLLMModelListSchema>;
type LocalModelDetail = ModelSpec; // Use ModelSpec from schema/models.ts
type LocalModelList = { [name: string]: ModelSpec }; // Use ModelSpec from schema/models.ts
const LOCAL_MODEL_LIST_PATH = path.resolve(
__dirname,
"../schema/model_list.json",
);
const SCHEMA_INDEX_PATH = path.resolve(__dirname, "../schema/index.ts");
const REMOTE_MODEL_URL =
"https://raw.githubusercontent.com/BerriAI/litellm/refs/heads/main/litellm/model_prices_and_context_window_backup.json";
async function fetchRemoteModels(url: string): Promise<LiteLLMModelList> {
return new Promise((resolve, reject) => {
https
.get(url, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
try {
const jsonData = JSON.parse(data);
if (
jsonData &&
typeof jsonData === "object" &&
"sample_spec" in jsonData
) {
delete jsonData.sample_spec;
}
const parsedModels = liteLLMModelListSchema.parse(jsonData);
resolve(parsedModels);
} catch (error) {
if (error instanceof z.ZodError) {
console.error(
"Zod validation errors in remote data:",
error.errors,
);
reject(
new Error(
"Failed to parse remote JSON due to schema validation errors.",
),
);
} else {
reject(
new Error(
"Failed to parse remote JSON: " + (error as Error).message,
),
);
}
}
});
})
.on("error", (err) => {
reject(new Error("Failed to fetch remote models: " + err.message));
});
});
}
async function readLocalModels(filePath: string): Promise<LocalModelList> {
try {
const fileContent = await fs.promises.readFile(filePath, "utf-8");
const localData = JSON.parse(fileContent);
// Validate local data with the imported ModelSchema
return z.record(ModelSchema).parse(localData);
} catch (error) {
if (error instanceof z.ZodError) {
console.error(
"Zod validation errors in local model_list.json:",
error.errors,
);
throw new Error("Local model_list.json failed Zod validation.");
}
throw new Error(
"Failed to read or parse local model list: " + (error as Error).message,
);
}
}
function translateToBraintrust(modelName: string, provider?: string): string {
if (provider === "xai" && modelName.startsWith("xai/")) {
return modelName.substring(4); // "xai/"
}
if (provider === "gemini") {
if (modelName.startsWith("gemini/gemini-gemma-")) {
return "google/" + modelName.substring(14);
}
if (modelName.startsWith("gemini/gemma-")) {
return "google/" + modelName.substring(7);
}
if (modelName.startsWith("gemini/")) {
return modelName.substring(7);
}
}
if (modelName.startsWith("google/")) {
return modelName;
}
return modelName;
}
function getProviderMappingForModel(
remoteModelName: string,
remoteModel: LiteLLMModelDetail,
): string[] {
// Helper function to map provider name to endpoint type
const mapProviderName = (providerName: string | undefined): string[] => {
if (!providerName) return [];
const lowerProvider = providerName.toLowerCase();
// Map provider names to our endpoint types
if (lowerProvider === "xai" || lowerProvider.includes("xai")) {
return ["xAI"];
}
if (lowerProvider === "anthropic" || lowerProvider.includes("anthropic")) {
return ["anthropic"];
}
if (lowerProvider === "openai" || lowerProvider.includes("openai")) {
return ["openai"];
}
if (
lowerProvider === "google" ||
lowerProvider === "gemini" ||
lowerProvider.includes("google") ||
lowerProvider.includes("gemini")
) {
return ["google"];
}
if (lowerProvider === "mistral" || lowerProvider.includes("mistral")) {
return ["mistral"];
}
if (lowerProvider === "together" || lowerProvider.includes("together")) {
return ["together"];
}
if (lowerProvider === "groq" || lowerProvider.includes("groq")) {
return ["groq"];
}
if (lowerProvider === "replicate" || lowerProvider.includes("replicate")) {
return ["replicate"];
}
if (lowerProvider === "fireworks" || lowerProvider.includes("fireworks")) {
return ["fireworks"];
}
if (
lowerProvider === "perplexity" ||
lowerProvider.includes("perplexity")
) {
return ["perplexity"];
}
if (lowerProvider === "lepton" || lowerProvider.includes("lepton")) {
return ["lepton"];
}
if (lowerProvider === "cerebras" || lowerProvider.includes("cerebras")) {
return ["cerebras"];
}
if (lowerProvider === "baseten" || lowerProvider.includes("baseten")) {
return ["baseten"];
}
return [];
};
// Try litellm_provider first
const provider = remoteModel.litellm_provider;
let result = mapProviderName(provider);
// If no match, try model name prefix as fallback
if (result.length === 0) {
const modelNameProviderPart = remoteModelName.split("/")[0];
result = mapProviderName(modelNameProviderPart);
}
if (result.length === 0) {
console.warn(`Unknown provider: ${provider} for model ${remoteModelName}`);
}
return result;
}
async function updateProviderMapping(
newModels: Array<{
name: string;
providers: string[];
remoteModel: LiteLLMModelDetail;
}>,
): Promise<void> {
try {
const schemaContent = await fs.promises.readFile(
SCHEMA_INDEX_PATH,
"utf-8",
);
// Generate new entries for the models
const newEntries = newModels.map(
({ name, providers }) => ` "${name}": ${JSON.stringify(providers)},`,
);
// Find the line with "grok-beta": ["xAI"], and insert after it
const grokBetaLine = schemaContent.indexOf('"grok-beta": ["xAI"],');
if (grokBetaLine !== -1) {
const lineEnd = schemaContent.indexOf("\n", grokBetaLine);
const beforeInsertion = schemaContent.substring(0, lineEnd + 1);
const afterInsertion = schemaContent.substring(lineEnd + 1);
const updatedSchemaContent =
beforeInsertion + newEntries.join("\n") + "\n" + afterInsertion;
await fs.promises.writeFile(SCHEMA_INDEX_PATH, updatedSchemaContent);
console.log(
`✅ Updated provider mappings for ${newModels.length} models in schema/index.ts`,
);
} else {
console.warn("Could not find grok-beta entry to use as insertion point");
}
} catch (error) {
console.error("Failed to update provider mappings:", error);
}
}
function convertRemoteToLocalModel(
remoteModelName: string,
remoteModel: LiteLLMModelDetail,
): ModelSpec {
const baseModel: Partial<ModelSpec> = {
format: "openai", // Default format for most models
flavor: "chat", // Default flavor for most models
};
// Helper to round cost values to avoid floating point precision issues
const roundCost = (costPerToken: number): number => {
return parseFloat((costPerToken * 1_000_000).toFixed(8));
};
// Add multimodal support if indicated
if (remoteModel.supports_vision) {
baseModel.multimodal = true;
}
// Add reasoning support if indicated
if (remoteModel.supports_reasoning) {
baseModel.reasoning = true;
}
// Convert cost information
if (remoteModel.input_cost_per_token) {
baseModel.input_cost_per_mil_tokens = roundCost(
remoteModel.input_cost_per_token,
);
}
if (remoteModel.output_cost_per_token) {
baseModel.output_cost_per_mil_tokens = roundCost(
remoteModel.output_cost_per_token,
);
}
if (remoteModel.cache_read_input_token_cost) {
baseModel.input_cache_read_cost_per_mil_tokens = roundCost(
remoteModel.cache_read_input_token_cost,
);
}
if (remoteModel.cache_creation_input_token_cost) {
baseModel.input_cache_write_cost_per_mil_tokens = roundCost(
remoteModel.cache_creation_input_token_cost,
);
}
// Note: output_reasoning_cost_per_mil_tokens may not be in ModelSpec yet,
// so we'll skip this for now to avoid type errors
// if (remoteModel.output_cost_per_reasoning_token) {
// baseModel.output_reasoning_cost_per_mil_tokens = roundCost(remoteModel.output_cost_per_reasoning_token);
// }
// Add token limits
if (remoteModel.max_input_tokens) {
baseModel.max_input_tokens = remoteModel.max_input_tokens;
}
if (remoteModel.max_output_tokens) {
baseModel.max_output_tokens = remoteModel.max_output_tokens;
}
return baseModel as ModelSpec;
}
async function getOptimalModelOrderingFromClaude(
modelsToAdd: Array<{ name: string; model: ModelSpec }>,
existingModels: LocalModelList,
): Promise<string[]> {
const existingModelNames = Object.keys(existingModels);
const newModelNames = modelsToAdd.map((m) => m.name);
// Focus on grok models for validation
const grokModels = existingModelNames.filter((name) => name.includes("grok"));
const prompt = `Order these Grok models optimally:
EXISTING: ${grokModels.join(", ")}
NEW: ${newModelNames.join(", ")}
Rules: version desc (4→3→2), then base→latest→variants, then larger→smaller sizes.
JSON array only:`;
try {
const output = await callClaudeWithSpawn(prompt);
// Try to extract JSON from the output
const jsonMatch = output.match(/\[[\s\S]*\]/);
if (jsonMatch) {
try {
const parsedOrder = JSON.parse(jsonMatch[0]);
// Validate that all grok models are included
const allGrokModels = [...grokModels, ...newModelNames];
if (
parsedOrder.length === allGrokModels.length &&
parsedOrder.every((name) => allGrokModels.includes(name)) &&
allGrokModels.every((name) => parsedOrder.includes(name))
) {
console.log("✅ Claude Code provided optimal Grok ordering");
// Rebuild complete model list with optimally ordered grok models
return rebuildCompleteModelList(existingModelNames, parsedOrder);
} else {
console.warn(
`Claude response validation failed: got ${parsedOrder.length} grok models, expected ${allGrokModels.length}`,
);
}
} catch (parseError) {
console.warn(
"Failed to parse Claude's JSON response:",
parseError.message,
);
}
} else {
console.warn("No JSON array found in Claude's response");
}
console.warn(
"Could not use Claude's response, falling back to smart ordering",
);
return getFallbackCompleteOrdering(existingModelNames, newModelNames);
} catch (error) {
console.warn("Failed to get ordering from Claude:", error.message);
return getFallbackCompleteOrdering(existingModelNames, newModelNames);
}
}
function callClaudeWithSpawn(prompt: string): Promise<string> {
return new Promise((resolve, reject) => {
const claude = spawn("claude", [], {
stdio: ["pipe", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
let isResolved = false;
// Set up timeout
const timeout = setTimeout(() => {
if (!isResolved) {
claude.kill("SIGTERM");
isResolved = true;
reject(new Error("Claude CLI timeout after 15 seconds"));
}
}, 15000);
claude.stdout.on("data", (data) => {
stdout += data.toString();
});
claude.stderr.on("data", (data) => {
stderr += data.toString();
});
claude.on("close", (code) => {
clearTimeout(timeout);
if (!isResolved) {
isResolved = true;
if (code === 0) {
// Try stderr first, then stdout
const output = stderr.trim() || stdout.trim();
resolve(output);
} else {
reject(new Error(`Claude CLI exited with code ${code}`));
}
}
});
claude.on("error", (error) => {
clearTimeout(timeout);
if (!isResolved) {
isResolved = true;
reject(error);
}
});
// Send the prompt to stdin and close it
claude.stdin.write(prompt);
claude.stdin.end();
});
}
function rebuildCompleteModelList(
existingModelNames: string[],
orderedGrokModels: string[],
): string[] {
// Start with existing models, replace grok models with the optimally ordered ones
const result: string[] = [];
const grokModelSet = new Set(orderedGrokModels);
let grokInserted = false;
for (const modelName of existingModelNames) {
if (modelName.includes("grok")) {
// Skip individual grok models, we'll insert them all at once
if (!grokInserted) {
result.push(...orderedGrokModels);
grokInserted = true;
}
} else {
result.push(modelName);
}
}
// If no grok models were in the original list, add them at the end
if (!grokInserted) {
result.push(...orderedGrokModels);
}
return result;
}
function getFallbackCompleteOrdering(
existingModelNames: string[],
newModelNames: string[],
): string[] {
// Create a complete list by intelligently inserting new models into existing order
const allModels = [...existingModelNames];
// Sort new models by their logical order first
const sortedNewModels = newModelNames.sort((a, b) => {
// Extract version numbers and variants for grok models
const aMatch = a.match(/grok-(\d+)(?:-(.+))?/);
const bMatch = b.match(/grok-(\d+)(?:-(.+))?/);
if (aMatch && bMatch) {
const aVersion = parseInt(aMatch[1]);
const bVersion = parseInt(bMatch[1]);
// Sort by version number (higher first)
if (aVersion !== bVersion) {
return bVersion - aVersion;
}
// Same version, sort by variant
const aVariant = aMatch[2] || "";
const bVariant = bMatch[2] || "";
// Base model first, then latest, then others
const variantOrder = [
"",
"latest",
"beta",
"mini",
"mini-latest",
"mini-beta",
"mini-fast",
"mini-fast-latest",
"mini-fast-beta",
"fast-beta",
"fast-latest",
];
const aIndex = variantOrder.indexOf(aVariant);
const bIndex = variantOrder.indexOf(bVariant);
if (aIndex !== -1 && bIndex !== -1) {
return aIndex - bIndex;
}
return aVariant.localeCompare(bVariant);
}
// Fallback to alphabetical
return a.localeCompare(b);
});
// Insert each new model at the appropriate position
for (const newModel of sortedNewModels) {
const insertionIndex = findInsertionIndex(allModels, newModel);
allModels.splice(insertionIndex, 0, newModel);
}
return allModels;
}
function findInsertionIndex(
existingModels: string[],
newModel: string,
): number {
// For grok models, find the right position based on version and variant
const newMatch = newModel.match(/grok-(\d+)(?:-(.+))?/);
if (!newMatch) {
// Non-grok model, add at end
return existingModels.length;
}
const newVersion = parseInt(newMatch[1]);
const newVariant = newMatch[2] || "";
// Find insertion point by comparing with existing models
for (let i = 0; i < existingModels.length; i++) {
const existingModel = existingModels[i];
const existingMatch = existingModel.match(/grok-(\d+)(?:-(.+))?/);
if (existingMatch) {
const existingVersion = parseInt(existingMatch[1]);
const existingVariant = existingMatch[2] || "";
// Insert before models with lower version numbers
if (newVersion > existingVersion) {
return i;
}
// Same version - check variant ordering
if (newVersion === existingVersion) {
const variantOrder = [
"",
"latest",
"beta",
"mini",
"mini-latest",
"mini-beta",
"mini-fast",
"mini-fast-latest",
"mini-fast-beta",
"fast-beta",
"fast-latest",
];
const newVariantIndex = variantOrder.indexOf(newVariant);
const existingVariantIndex = variantOrder.indexOf(existingVariant);
if (newVariantIndex !== -1 && existingVariantIndex !== -1) {
if (newVariantIndex < existingVariantIndex) {
return i;
}
} else if (newVariant.localeCompare(existingVariant) < 0) {
return i;
}
}
}
}
// If we didn't find a position, add at the end
return existingModels.length;
}
async function findMissingCommand(argv: any) {
try {
console.log("Fetching remote models from:", REMOTE_MODEL_URL);
const remoteModels = await fetchRemoteModels(REMOTE_MODEL_URL);
console.log(`Fetched ${Object.keys(remoteModels).length} remote models.`);
console.log("Reading local models from:", LOCAL_MODEL_LIST_PATH);
const localModels = await readLocalModels(LOCAL_MODEL_LIST_PATH);
console.log(`Read ${Object.keys(localModels).length} local models.`);
const localModelNames = new Set(Object.keys(localModels));
const missingInLocal: string[] = [];
const consideredRemoteModels: LiteLLMModelList = {};
for (const remoteModelName in remoteModels) {
const modelDetail = remoteModels[remoteModelName];
if (argv.provider) {
const lowerArgProvider = argv.provider.toLowerCase();
const modelProvider = modelDetail.litellm_provider?.toLowerCase();
const modelNameProviderPart = remoteModelName
.split("/")[0]
.toLowerCase();
if (
!modelProvider?.includes(lowerArgProvider) &&
!modelNameProviderPart.includes(lowerArgProvider) &&
!(modelProvider === lowerArgProvider) &&
!(modelNameProviderPart === lowerArgProvider)
) {
continue;
}
}
consideredRemoteModels[remoteModelName] = modelDetail;
}
const remoteModelNamesFiltered = new Set(
Object.keys(consideredRemoteModels),
);
for (const modelName of remoteModelNamesFiltered) {
const translatedModelName = translateToBraintrust(
modelName,
consideredRemoteModels[modelName]?.litellm_provider,
);
if (argv.provider) {
console.log(
`[DEBUG] Remote: ${modelName} (Provider: ${
consideredRemoteModels[modelName]?.litellm_provider || "N/A"
}) -> Translated: ${translatedModelName}`,
);
}
if (!localModelNames.has(translatedModelName)) {
missingInLocal.push(modelName);
}
}
if (argv.summarize) {
console.log("\n--- Model Summary by Provider ---");
if (argv.provider) {
console.log(`(Filtered for provider: ${argv.provider})`);
}
const providerSummary: {
[provider: string]: { totalRemote: number; missingInLocal: number };
} = {};
for (const modelName in consideredRemoteModels) {
const modelDetail = consideredRemoteModels[modelName];
const provider = modelDetail.litellm_provider || "Unknown Provider";
if (!providerSummary[provider]) {
providerSummary[provider] = { totalRemote: 0, missingInLocal: 0 };
}
providerSummary[provider].totalRemote++;
}
for (const modelName of missingInLocal) {
const modelDetail = consideredRemoteModels[modelName];
if (modelDetail) {
const provider = modelDetail.litellm_provider || "Unknown Provider";
if (!providerSummary[provider]) {
providerSummary[provider] = { totalRemote: 0, missingInLocal: 0 };
}
providerSummary[provider].missingInLocal++;
} else {
const unknownProvider = "Unknown Provider (Details Missing)";
if (!providerSummary[unknownProvider]) {
providerSummary[unknownProvider] = {
totalRemote: 0,
missingInLocal: 0,
};
}
providerSummary[unknownProvider].missingInLocal++;
}
}
const partiallyMissingProviders: string[] = [];
const completelyMissingProviders: string[] = [];
const allPresentProviders: string[] = [];
const sortedProviderNames = Object.keys(providerSummary).sort();
for (const provider of sortedProviderNames) {
const summary = providerSummary[provider];
if (summary.missingInLocal > 0) {
if (summary.missingInLocal < summary.totalRemote) {
partiallyMissingProviders.push(provider);
} else {
completelyMissingProviders.push(provider);
}
} else {
allPresentProviders.push(provider);
}
}
if (partiallyMissingProviders.length > 0) {
console.log("\n--- Providers with Some Models Missing ---");
for (const provider of partiallyMissingProviders) {
const summary = providerSummary[provider];
console.log(
`${provider}: ${summary.missingInLocal} missing out of ${summary.totalRemote} total remote models.`,
);
}
}
if (completelyMissingProviders.length > 0) {
console.log("\n--- Providers with All Models Missing ---");
for (const provider of completelyMissingProviders) {
const summary = providerSummary[provider];
console.log(
`${provider}: All ${summary.missingInLocal} of ${summary.totalRemote} remote models are missing.`,
);
}
}
if (allPresentProviders.length > 0) {
console.log("\n--- Providers with All Models Present ---");
for (const provider of allPresentProviders) {
const summary = providerSummary[provider];
console.log(
`${provider}: All ${summary.totalRemote} remote models present locally.`,
);
}
}
if (missingInLocal.length === 0) {
console.log(
"\nAll models from the remote list are present in the local model_list.json.",
);
} else if (
partiallyMissingProviders.length === 0 &&
completelyMissingProviders.length === 0
) {
// This implies missingInLocal > 0 but they didn't fit categories,
// possibly due to provider filtering or no provider info.
console.log(
"\nSome models are missing. If a provider filter was used, they might be outside that scope or have no provider information.",
);
if (!argv.provider)
console.log(
"Run without --summarize to see individual missing models.",
);
}
} else {
if (missingInLocal.length > 0) {
if (argv.provider) {
console.log(
`\nModels for provider '${argv.provider}' present in remote but missing in local:`,
);
} else {
console.log(
"\nModels present in remote but missing in local model_list.json:",
);
}
missingInLocal.forEach((modelName) => {
const detail = consideredRemoteModels[modelName];
const translated = translateToBraintrust(
modelName,
detail?.litellm_provider,
);
console.log(
`${modelName} (Provider: ${
detail?.litellm_provider || "N/A"
}, Translated: ${translated})`,
);
});
} else {
console.log(
"\nAll models from the remote list (matching filter if any) are present in the local model_list.json.",
);
}
}
} catch (error) {
console.error("Error during find-missing command:", error);
process.exit(1);
}
}
async function updateModelsCommand(argv: any) {
try {
console.log("Fetching remote models for model update...");
const remoteModels = await fetchRemoteModels(REMOTE_MODEL_URL);
console.log(`Fetched ${Object.keys(remoteModels).length} remote models.`);
console.log("Reading local models for model update...");
const localModels = await readLocalModels(LOCAL_MODEL_LIST_PATH);
console.log(`Read ${Object.keys(localModels).length} local models.`);
const updatedLocalModels = JSON.parse(
JSON.stringify(localModels),
) as LocalModelList;
let madeChanges = false;
console.log("\n--- Model Update Report ---");
if (argv.provider) {
console.log(`(Filtered for provider: ${argv.provider})`);
}
let discrepanciesFound = 0;
const modelsToCompare: Array<{
localModelName: string;
localModelDetail: LocalModelDetail;
remoteModelName: string;
remoteModelDetail: LiteLLMModelDetail;
}> = [];
if (argv.provider) {
const lowerArgProvider = argv.provider.toLowerCase();
for (const remoteModelName in remoteModels) {
const remoteModelDetail = remoteModels[remoteModelName];
const modelProvider = remoteModelDetail.litellm_provider?.toLowerCase();
const modelNameProviderPart = remoteModelName
.split("/")[0]
.toLowerCase();
const matchesProviderFilter =
modelProvider?.includes(lowerArgProvider) ||
modelNameProviderPart.includes(lowerArgProvider) ||
modelProvider === lowerArgProvider ||
modelNameProviderPart === lowerArgProvider;
if (matchesProviderFilter) {
const translatedRemoteModelName = translateToBraintrust(
remoteModelName,
remoteModelDetail.litellm_provider,
);
if (localModels[translatedRemoteModelName]) {
modelsToCompare.push({
localModelName: translatedRemoteModelName,
localModelDetail: localModels[translatedRemoteModelName],
remoteModelName: remoteModelName,
remoteModelDetail: remoteModelDetail,
});
}
}
}
} else {
for (const localModelName in localModels) {
const localModelDetail = localModels[localModelName];
let foundRemoteDetail: LiteLLMModelDetail | undefined = undefined;
let originalRemoteModelNameForLoop: string | undefined = undefined;
for (const rName in remoteModels) {
const rDetail = remoteModels[rName];
const translatedName = translateToBraintrust(
rName,
rDetail.litellm_provider,
);
if (translatedName === localModelName) {
foundRemoteDetail = rDetail;
originalRemoteModelNameForLoop = rName;
break;
}
}
if (foundRemoteDetail && originalRemoteModelNameForLoop) {
modelsToCompare.push({
localModelName: localModelName,
localModelDetail: localModelDetail,
remoteModelName: originalRemoteModelNameForLoop,
remoteModelDetail: foundRemoteDetail,
});
}
}
}
for (const item of modelsToCompare) {
const {
localModelName,
localModelDetail,
remoteModelName: originalRemoteModelName,
remoteModelDetail,
} = item;
const modelInUpdatedList = updatedLocalModels[localModelName];
const localInputCost = localModelDetail.input_cost_per_mil_tokens;
const localOutputCost = localModelDetail.output_cost_per_mil_tokens;
const localCacheReadCost =
localModelDetail.input_cache_read_cost_per_mil_tokens;
const localCacheWriteCost =
localModelDetail.input_cache_write_cost_per_mil_tokens;
const remoteInputCostPerToken = remoteModelDetail.input_cost_per_token;
const remoteOutputCostPerToken = remoteModelDetail.output_cost_per_token;
const remoteCacheReadCostPerToken =
remoteModelDetail.cache_read_input_token_cost;
const remoteCacheWriteCostPerToken =
remoteModelDetail.cache_creation_input_token_cost;
let modelReportedThisIteration = false;
const checkAndUpdateCost = (
costType: string,
localCost: number | undefined | null,
remoteCostPerToken: number | undefined,
localFieldName: keyof ModelSpec,
) => {
if (typeof remoteCostPerToken === "number") {
const remoteCostPerMil = remoteCostPerToken * 1_000_000;
const roundedRemoteCostPerMil = parseFloat(
remoteCostPerMil.toFixed(8),
);
if (
localCost === null ||
typeof localCost !== "number" ||
Math.abs(localCost - remoteCostPerMil) > 1e-9
) {
if (!argv.write && !modelReportedThisIteration) {
console.log(
`\nModel: ${localModelName} (Remote: ${originalRemoteModelName})`,
);
modelReportedThisIteration = true;
}
if (!argv.write)
console.log(
` ${costType} Cost Mismatch/Missing: Local: ${
localCost ?? "Not available"
}, Remote (calc): ${remoteCostPerMil} (would write: ${roundedRemoteCostPerMil}) (from ${remoteCostPerToken}/token)`,
);
discrepanciesFound++;
if (argv.write) {
(modelInUpdatedList as any)[localFieldName] =
roundedRemoteCostPerMil;
madeChanges = true;
if (!modelReportedThisIteration) {
console.log(
`\n[WRITE] Updating model for: ${localModelName} (Remote: ${originalRemoteModelName})`,
);
modelReportedThisIteration = true;
}
console.log(
` [WRITE] Updated ${costType} Cost to: ${roundedRemoteCostPerMil}`,
);
}
}
} else if (typeof localCost === "number") {
if (!argv.write && !modelReportedThisIteration) {
console.log(
`\nModel: ${localModelName} (Remote: ${originalRemoteModelName})`,
);
modelReportedThisIteration = true;
}
if (!argv.write)
console.log(
` ${costType} Cost: Local: ${localCost}, Remote: Not available`,
);
}
};