|
| 1 | +/** |
| 2 | + * Script for generating llm.ts |
| 3 | + * The source data is taken from llama.cpp |
| 4 | + */ |
| 5 | + |
| 6 | +import type { GGUFParseOutput } from "../../gguf/src/gguf"; |
| 7 | +import { gguf } from "../../gguf/src/gguf"; |
| 8 | +import { appendFileSync, writeFileSync, existsSync } from "node:fs"; |
| 9 | +import path from "node:path"; |
| 10 | + |
| 11 | +const DEBUG = process.env.DEBUG; |
| 12 | +const RE_SPECIAL_TOKEN = /<[|_A-Za-z0-9]+>|\[[A-Z]+\]|<\uFF5C[\u2581A-Za-z]+\uFF5C>/g; |
| 13 | +const MAX_NUMBER_OF_TAGS_PER_MODEL = 5; |
| 14 | +const N_WORKERS = 16; |
| 15 | +const OUTPUT_FILE = path.join(__dirname, "../src/chat-template-automap.ts"); |
| 16 | +const BLACKLISTED_MODELS = (model: string, tag: string) => { |
| 17 | + // some models are know to give ServiceUnavailable |
| 18 | + return model === "library/deepseek-r1" && tag === "7b"; |
| 19 | +}; |
| 20 | + |
| 21 | +interface OutputItem { |
| 22 | + model: string; |
| 23 | + gguf: string; |
| 24 | + ollama: { |
| 25 | + template: string; |
| 26 | + tokens: string[]; |
| 27 | + // eslint-disable-next-line |
| 28 | + params?: any; |
| 29 | + }; |
| 30 | +} |
| 31 | + |
| 32 | +interface OllamaManifestLayer { |
| 33 | + digest: string; |
| 34 | + mediaType: string; |
| 35 | + size: number; |
| 36 | +} |
| 37 | + |
| 38 | +interface OllamaManifest { |
| 39 | + layers: OllamaManifestLayer[]; |
| 40 | +} |
| 41 | + |
| 42 | +const getSpecialTokens = (tmpl: string): string[] => { |
| 43 | + const matched = tmpl.match(RE_SPECIAL_TOKEN); |
| 44 | + const tokens = Array.from(matched || []); |
| 45 | + return Array.from(new Set(tokens)); // deduplicate |
| 46 | +}; |
| 47 | + |
| 48 | +(async () => { |
| 49 | + if (DEBUG) writeFileSync("ollama_tmp.jsonl", ""); // clear the file |
| 50 | + |
| 51 | + const models: string[] = []; |
| 52 | + const output: OutputItem[] = []; |
| 53 | + |
| 54 | + const html = await (await fetch("https://ollama.com/library")).text(); |
| 55 | + const matched = html.match(/href="\/library\/[^"]+/g); |
| 56 | + if (!matched) { |
| 57 | + throw new Error("cannot find any model url"); |
| 58 | + } |
| 59 | + for (let i = 0; i < matched.length; i++) { |
| 60 | + models.push(matched[i].replace('href="/', "")); |
| 61 | + } |
| 62 | + console.log({ models }); |
| 63 | + |
| 64 | + //////// Get tags //////// |
| 65 | + |
| 66 | + let nDoing = 0; |
| 67 | + let nAll = models.length; |
| 68 | + const modelsWithTag: string[] = []; |
| 69 | + const workerGetTags = async () => { |
| 70 | + while (true) { |
| 71 | + const model = models.shift(); |
| 72 | + if (!model) return; |
| 73 | + nDoing++; |
| 74 | + console.log(`Getting tags ${nDoing} / ${nAll}`); |
| 75 | + const html = await (await fetch(`https://ollama.com/${model}`)).text(); |
| 76 | + const matched = html.match(/href="\/library\/[^"]+/g); |
| 77 | + if (!matched) { |
| 78 | + throw new Error("cannot find any tag url"); |
| 79 | + } |
| 80 | + for (let i = 0; i < matched.length && i < MAX_NUMBER_OF_TAGS_PER_MODEL; i++) { |
| 81 | + const midAndTag: string = matched[i].replace('href="/', ""); |
| 82 | + if (midAndTag.match(/:/) && !midAndTag.match(/\/blobs/)) { |
| 83 | + modelsWithTag.push(midAndTag); |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + }; |
| 88 | + await Promise.all( |
| 89 | + Array(N_WORKERS) |
| 90 | + .fill(null) |
| 91 | + .map(() => workerGetTags()) |
| 92 | + ); |
| 93 | + console.log({ modelsWithTag }); |
| 94 | + |
| 95 | + //////// merging with old file if necessary //////// |
| 96 | + |
| 97 | + const seenGGUFTemplate = new Set<string>(); |
| 98 | + if (existsSync(OUTPUT_FILE)) { |
| 99 | + const oldOutput = await import(OUTPUT_FILE); |
| 100 | + oldOutput.OLLAMA_CHAT_TEMPLATE_MAPPING.forEach((item: OutputItem) => { |
| 101 | + seenGGUFTemplate.add(item.gguf); |
| 102 | + output.push(item); |
| 103 | + }); |
| 104 | + } |
| 105 | + |
| 106 | + //////// Get template //////// |
| 107 | + |
| 108 | + nDoing = 0; |
| 109 | + nAll = modelsWithTag.length; |
| 110 | + const workerGetTemplate = async () => { |
| 111 | + while (true) { |
| 112 | + const modelWithTag = modelsWithTag.shift(); |
| 113 | + if (!modelWithTag) return; |
| 114 | + |
| 115 | + nDoing++; |
| 116 | + const [model, tag] = modelWithTag.split(":"); |
| 117 | + console.log(`Fetch template ${nDoing} / ${nAll} | model=${model} tag=${tag}`); |
| 118 | + const getBlobUrl = (digest: string) => `https://registry.ollama.com/v2/${model}/blobs/${digest}`; |
| 119 | + const manifest: OllamaManifest = await ( |
| 120 | + await fetch(`https://registry.ollama.com/v2/${model}/manifests/${tag}`) |
| 121 | + ).json(); |
| 122 | + if (!manifest.layers) { |
| 123 | + console.log(" --> [X] No layers"); |
| 124 | + continue; |
| 125 | + } |
| 126 | + const layerModelUrl = manifest.layers.find((l) => l.mediaType.match(/\.model/)); |
| 127 | + if (!layerModelUrl) { |
| 128 | + console.log(" --> [X] No model is found"); |
| 129 | + continue; |
| 130 | + } |
| 131 | + const modelUrl = getBlobUrl(layerModelUrl.digest); |
| 132 | + let ggufData: GGUFParseOutput; |
| 133 | + if (BLACKLISTED_MODELS(model, tag)) { |
| 134 | + console.log(" --> [X] Blacklisted model, skip"); |
| 135 | + continue; |
| 136 | + } |
| 137 | + try { |
| 138 | + ggufData = await gguf(modelUrl); |
| 139 | + } catch (e) { |
| 140 | + console.log(" --> [X] FATAL: GGUF error", { model, tag, modelUrl }); |
| 141 | + throw e; // rethrow |
| 142 | + } |
| 143 | + const { metadata } = ggufData; |
| 144 | + const ggufTmpl = metadata["tokenizer.chat_template"]; |
| 145 | + if (ggufTmpl) { |
| 146 | + if (seenGGUFTemplate.has(ggufTmpl)) { |
| 147 | + console.log(" --> Already seen this GGUF template, skip..."); |
| 148 | + continue; |
| 149 | + } |
| 150 | + seenGGUFTemplate.add(ggufTmpl); |
| 151 | + console.log(" --> GGUF chat template OK"); |
| 152 | + const tmplBlob = manifest.layers.find((l) => l.mediaType.match(/\.template/)); |
| 153 | + if (!tmplBlob) continue; |
| 154 | + const ollamaTmplUrl = getBlobUrl(tmplBlob.digest); |
| 155 | + if (!ollamaTmplUrl) { |
| 156 | + console.log(" --> [X] No ollama template"); |
| 157 | + continue; |
| 158 | + } |
| 159 | + const ollamaTmpl = await (await fetch(ollamaTmplUrl)).text(); |
| 160 | + console.log(" --> All OK"); |
| 161 | + const record: OutputItem = { |
| 162 | + model: modelWithTag, |
| 163 | + gguf: ggufTmpl, |
| 164 | + ollama: { |
| 165 | + template: ollamaTmpl, |
| 166 | + tokens: getSpecialTokens(ggufTmpl), |
| 167 | + }, |
| 168 | + }; |
| 169 | + // get params |
| 170 | + const ollamaParamsBlob = manifest.layers.find((l) => l.mediaType.match(/\.params/)); |
| 171 | + const ollamaParamsUrl = ollamaParamsBlob ? getBlobUrl(ollamaParamsBlob.digest) : null; |
| 172 | + if (ollamaParamsUrl) { |
| 173 | + console.log(" --> Got params"); |
| 174 | + record.ollama.params = await (await fetch(ollamaParamsUrl)).json(); |
| 175 | + } |
| 176 | + output.push(record); |
| 177 | + if (DEBUG) appendFileSync("ollama_tmp.jsonl", JSON.stringify(record) + "\n"); |
| 178 | + } else { |
| 179 | + console.log(" --> [X] No GGUF template"); |
| 180 | + continue; |
| 181 | + } |
| 182 | + //console.log({modelUrl, ggufData}); |
| 183 | + //break; |
| 184 | + } |
| 185 | + }; |
| 186 | + |
| 187 | + await Promise.all( |
| 188 | + Array(N_WORKERS) |
| 189 | + .fill(null) |
| 190 | + .map(() => workerGetTemplate()) |
| 191 | + ); |
| 192 | + |
| 193 | + console.log("DONE"); |
| 194 | + output.sort((a, b) => a.model.localeCompare(b.model)); |
| 195 | + |
| 196 | + writeFileSync( |
| 197 | + OUTPUT_FILE, |
| 198 | + ` |
| 199 | +// This file is auto generated, please do not modify manually |
| 200 | +// To update it, run "pnpm run build:automap" |
| 201 | +
|
| 202 | +import { OllamaChatTemplateMapEntry } from "./types"; |
| 203 | +
|
| 204 | +export const OLLAMA_CHAT_TEMPLATE_MAPPING: OllamaChatTemplateMapEntry[] = ${JSON.stringify(output, null, "\t")}; |
| 205 | + `.trim() |
| 206 | + ); |
| 207 | +})(); |
0 commit comments