|
| 1 | +import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime"; |
| 2 | +import { readProviderJsonResponse } from "openclaw/plugin-sdk/provider-http"; |
| 3 | +import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime"; |
| 4 | +import { OLLAMA_CLOUD_DEFAULT_MODELS } from "./defaults.js"; |
| 5 | +import { |
| 6 | + buildDefaultOllamaCloudModelDefinition, |
| 7 | + buildOllamaBaseUrlSsrFPolicy, |
| 8 | + buildOllamaModelDefinition, |
| 9 | + enrichOllamaModelsWithContext, |
| 10 | + fetchOllamaModels, |
| 11 | + resolveOllamaApiBase, |
| 12 | + type OllamaModelWithContext, |
| 13 | +} from "./provider-models.js"; |
| 14 | + |
| 15 | +const OLLAMA_CONTEXT_ENRICH_LIMIT = 200; |
| 16 | +const OLLAMA_TOOLS_SCAN_CONCURRENCY = 8; |
| 17 | + |
| 18 | +type OllamaCloudDefaultModel = (typeof OLLAMA_CLOUD_DEFAULT_MODELS)[number]; |
| 19 | + |
| 20 | +export function normalizeOllamaModelName(value: string | undefined): string | undefined { |
| 21 | + const trimmed = value?.trim(); |
| 22 | + if (!trimmed) { |
| 23 | + return undefined; |
| 24 | + } |
| 25 | + return trimmed.toLowerCase().startsWith("ollama/") |
| 26 | + ? trimmed.slice("ollama/".length).trim() || undefined |
| 27 | + : trimmed; |
| 28 | +} |
| 29 | + |
| 30 | +function getOllamaLatestDedupeKey(name: string): string { |
| 31 | + const normalized = name.trim().toLowerCase(); |
| 32 | + return normalized.endsWith(":latest") ? normalized.slice(0, -":latest".length) : normalized; |
| 33 | +} |
| 34 | + |
| 35 | +export function mergeUniqueModelNames(...groups: string[][]): string[] { |
| 36 | + const mergedByKey = new Map<string, string>(); |
| 37 | + for (const group of groups) { |
| 38 | + for (const name of group) { |
| 39 | + const key = getOllamaLatestDedupeKey(name); |
| 40 | + const existing = mergedByKey.get(key); |
| 41 | + if ( |
| 42 | + existing === undefined || |
| 43 | + (!existing.trim().toLowerCase().endsWith(":latest") && |
| 44 | + name.trim().toLowerCase().endsWith(":latest")) |
| 45 | + ) { |
| 46 | + mergedByKey.set(key, name); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + return [...mergedByKey.values()]; |
| 51 | +} |
| 52 | + |
| 53 | +export function findAvailableOllamaModelName( |
| 54 | + modelName: string, |
| 55 | + availableModelNames: Iterable<string>, |
| 56 | +): string | undefined { |
| 57 | + const wantedKey = getOllamaLatestDedupeKey(modelName); |
| 58 | + for (const available of availableModelNames) { |
| 59 | + if (getOllamaLatestDedupeKey(available) === wantedKey) { |
| 60 | + return available; |
| 61 | + } |
| 62 | + } |
| 63 | + return undefined; |
| 64 | +} |
| 65 | + |
| 66 | +export function buildOllamaModelsConfig( |
| 67 | + modelNames: string[], |
| 68 | + discoveredModelsByName?: Map<string, OllamaModelWithContext>, |
| 69 | + defaultModels: readonly OllamaCloudDefaultModel[] = [], |
| 70 | +) { |
| 71 | + return modelNames.map((name) => { |
| 72 | + const discovered = discoveredModelsByName?.get(name); |
| 73 | + const defaultModel = defaultModels.find((model) => model.id === name); |
| 74 | + if (defaultModel && !discovered) { |
| 75 | + return buildDefaultOllamaCloudModelDefinition(defaultModel); |
| 76 | + } |
| 77 | + const capabilities = |
| 78 | + discovered?.capabilities ?? (defaultModel ? [...defaultModel.capabilities] : undefined); |
| 79 | + return buildOllamaModelDefinition( |
| 80 | + name, |
| 81 | + discovered?.contextWindow ?? defaultModel?.contextWindow, |
| 82 | + capabilities, |
| 83 | + ); |
| 84 | + }); |
| 85 | +} |
| 86 | + |
| 87 | +function parseOllamaSetupShowInfo(data: { |
| 88 | + model_info?: Record<string, unknown>; |
| 89 | + capabilities?: unknown; |
| 90 | + parameters?: unknown; |
| 91 | +}): Pick<OllamaModelWithContext, "contextWindow" | "capabilities"> { |
| 92 | + let contextWindow: number | undefined; |
| 93 | + for (const [key, value] of Object.entries(data.model_info ?? {})) { |
| 94 | + if (key.endsWith(".context_length") && typeof value === "number" && value > 0) { |
| 95 | + contextWindow = Math.floor(value); |
| 96 | + break; |
| 97 | + } |
| 98 | + } |
| 99 | + if (typeof data.parameters === "string") { |
| 100 | + for (const line of data.parameters.split(/\r?\n/)) { |
| 101 | + const match = line.trim().match(/^num_ctx\s+(-?\d+)\b/); |
| 102 | + const parsed = match?.[1] ? Number.parseInt(match[1], 10) : undefined; |
| 103 | + if (parsed && parsed > 0 && (contextWindow === undefined || parsed > contextWindow)) { |
| 104 | + contextWindow = parsed; |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | + const capabilities = Array.isArray(data.capabilities) |
| 109 | + ? data.capabilities.filter((value): value is string => typeof value === "string") |
| 110 | + : undefined; |
| 111 | + return { contextWindow, capabilities }; |
| 112 | +} |
| 113 | + |
| 114 | +export async function inspectOllamaModelsForSetup( |
| 115 | + baseUrl: string, |
| 116 | + models: OllamaModelWithContext[], |
| 117 | + signal?: AbortSignal, |
| 118 | +): Promise<{ inspected: OllamaModelWithContext[]; inspectionFailures: string[] }> { |
| 119 | + const apiBase = resolveOllamaApiBase(baseUrl); |
| 120 | + const inspected: OllamaModelWithContext[] = []; |
| 121 | + const inspectionFailures: string[] = []; |
| 122 | + for (let index = 0; index < models.length; index += OLLAMA_TOOLS_SCAN_CONCURRENCY) { |
| 123 | + signal?.throwIfAborted(); |
| 124 | + const batch = models.slice(index, index + OLLAMA_TOOLS_SCAN_CONCURRENCY); |
| 125 | + const results = await Promise.all( |
| 126 | + batch.map(async (model) => { |
| 127 | + try { |
| 128 | + const requestSignal = signal |
| 129 | + ? AbortSignal.any([AbortSignal.timeout(3000), signal]) |
| 130 | + : AbortSignal.timeout(3000); |
| 131 | + const { response, release } = await fetchWithSsrFGuard({ |
| 132 | + url: `${apiBase}/api/show`, |
| 133 | + init: { |
| 134 | + method: "POST", |
| 135 | + headers: { "Content-Type": "application/json" }, |
| 136 | + body: JSON.stringify({ name: model.name }), |
| 137 | + signal: requestSignal, |
| 138 | + }, |
| 139 | + signal: requestSignal, |
| 140 | + policy: buildOllamaBaseUrlSsrFPolicy(apiBase), |
| 141 | + auditContext: "ollama-setup.tools-scan", |
| 142 | + }); |
| 143 | + try { |
| 144 | + if (!response.ok) { |
| 145 | + throw new Error(`Ollama model inspection failed with HTTP ${response.status}`); |
| 146 | + } |
| 147 | + const data = await readProviderJsonResponse<{ |
| 148 | + model_info?: Record<string, unknown>; |
| 149 | + capabilities?: unknown; |
| 150 | + parameters?: unknown; |
| 151 | + }>(response, "ollama-setup.tools-scan"); |
| 152 | + return Object.assign({}, model, parseOllamaSetupShowInfo(data)); |
| 153 | + } finally { |
| 154 | + await release(); |
| 155 | + } |
| 156 | + } catch (error) { |
| 157 | + signal?.throwIfAborted(); |
| 158 | + // A failed inspection must not inherit the optimistic tools default |
| 159 | + // reserved for models that were never inspected. |
| 160 | + inspectionFailures.push(`${model.name}: ${formatErrorMessage(error)}`); |
| 161 | + return Object.assign({}, model, { capabilities: [] as string[] }); |
| 162 | + } |
| 163 | + }), |
| 164 | + ); |
| 165 | + inspected.push(...results); |
| 166 | + } |
| 167 | + return { inspected, inspectionFailures }; |
| 168 | +} |
| 169 | + |
| 170 | +export async function discoverOllamaModelsForSetup(params: { |
| 171 | + baseUrl: string; |
| 172 | + inspectTools?: boolean; |
| 173 | + signal?: AbortSignal; |
| 174 | +}) { |
| 175 | + const { reachable, models } = await fetchOllamaModels(params.baseUrl); |
| 176 | + const firstModels = models.slice(0, OLLAMA_CONTEXT_ENRICH_LIMIT); |
| 177 | + const inspection: { inspected: OllamaModelWithContext[]; inspectionFailures: string[] } = |
| 178 | + !reachable |
| 179 | + ? { inspected: [], inspectionFailures: [] } |
| 180 | + : params.inspectTools |
| 181 | + ? await inspectOllamaModelsForSetup(params.baseUrl, firstModels, params.signal) |
| 182 | + : { |
| 183 | + inspected: await enrichOllamaModelsWithContext(params.baseUrl, firstModels), |
| 184 | + inspectionFailures: [], |
| 185 | + }; |
| 186 | + if ( |
| 187 | + params.inspectTools && |
| 188 | + !inspection.inspected.some((model) => model.capabilities?.includes("tools")) && |
| 189 | + models.length > OLLAMA_CONTEXT_ENRICH_LIMIT |
| 190 | + ) { |
| 191 | + const remainingScan = await inspectOllamaModelsForSetup( |
| 192 | + params.baseUrl, |
| 193 | + models.slice(OLLAMA_CONTEXT_ENRICH_LIMIT), |
| 194 | + params.signal, |
| 195 | + ); |
| 196 | + inspection.inspected.push(...remainingScan.inspected); |
| 197 | + inspection.inspectionFailures.push(...remainingScan.inspectionFailures); |
| 198 | + } |
| 199 | + return { |
| 200 | + reachable, |
| 201 | + models, |
| 202 | + inspectedModels: inspection.inspected, |
| 203 | + discoveredModelsByName: new Map(inspection.inspected.map((model) => [model.name, model])), |
| 204 | + inspectionFailures: inspection.inspectionFailures, |
| 205 | + hasToolsCapableModel: inspection.inspected.some((model) => |
| 206 | + model.capabilities?.includes("tools"), |
| 207 | + ), |
| 208 | + }; |
| 209 | +} |
0 commit comments