UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

291 lines (290 loc) • 11.5 kB
import { s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs"; import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as jsonResult } from "./tool-results-CcV0sxnb.mjs"; import { m as readToolStringParam, s as readFiniteNumberParam, u as readPositiveIntegerParam } from "./common-njQNtpnW.mjs"; import { _ as readResponseTextLimited, h as readProviderJsonResponse } from "./provider-http-errors-Dtgw3x-5.mjs"; import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import "./ssrf-runtime-B6q6NM4E.mjs"; import "./error-runtime-BM740gJj.mjs"; import { t as expectDefined } from "./expect-runtime-DT3P17Ul.mjs"; import "./channel-actions-DxuDuzvg.mjs"; import "./provider-http-LcawLneq.mjs"; import "./param-readers-CVZN1591.mjs"; import { o as OLLAMA_DEFAULT_BASE_URL } from "./defaults-DreqJ3YB.mjs"; import { b as resolveOllamaApiBase, c as enrichOllamaModelsWithContext, l as fetchLoadedOllamaModelNames, m as isOllamaRemoteModel, n as buildOllamaBaseUrlSsrFPolicy, s as enrichOllamaCompletionModels, u as fetchOllamaModels, x as throwIfOllamaRequestAborted } from "./provider-models-_SPbqcl8.mjs"; import { a as MAX_SYSTEM_PROMPT_CHARS, c as OLLAMA_MODELS_COMMAND, f as ollamaNodeInferenceToolDefinition, i as MAX_PROMPT_CHARS, l as OLLAMA_NODE_INFERENCE_CAPABILITY, n as DISCOVERY_TRANSPORT_TIMEOUT_MS, o as MAX_TOKENS, r as MAX_INFERENCE_TIMEOUT_MS, s as OLLAMA_CHAT_COMMAND, t as DEFAULT_INFERENCE_TIMEOUT_MS } from "./node-inference-contract-CysyFh_l.mjs"; //#region extensions/ollama/src/node-inference.ts const MAX_ERROR_BODY_BYTES = 500; function readNodeCommandParams(e) { if (!e) return {}; const t = asNullableRecord(JSON.parse(e)); if (!t) throw new Error("node inference params must be a JSON object"); return t; } function durationMs(e) { if (typeof e !== "number" || !Number.isFinite(e) || e < 0) return; return Math.round(e / 1e6 * 100) / 100; } async function discoverOllamaNodeModels(e = OLLAMA_DEFAULT_BASE_URL, t) { const n = resolveOllamaApiBase(e); const r = await fetchOllamaModels(n, t ? { signal: t } : void 0); if (!r.reachable) throw new Error(`Ollama is not running at ${n}`); const i = r.models.filter((e) => !isOllamaRemoteModel(e)); const a = await fetchLoadedOllamaModelNames(n, t ? { signal: t } : void 0); const o = new Set(a.models); const s = i.toSorted((e, t) => Number(o.has(t.name)) - Number(o.has(e.name))); return { provider: "ollama", models: (await enrichOllamaCompletionModels(n, s, { requireCompletionCapability: true, ...t ? { signal: t } : {} })).map((e) => { const t = e.details; const n = { name: e.name, loaded: o.has(e.name) }; if (typeof e.size === "number") n.size = e.size; if (typeof e.modified_at === "string") n.modifiedAt = e.modified_at; if (t?.family) n.family = t.family; if (t?.parameter_size) n.parameterSize = t.parameter_size; if (t?.quantization_level) n.quantization = t.quantization_level; if (typeof e.contextWindow === "number") n.contextWindow = e.contextWindow; if (e.capabilities) n.capabilities = e.capabilities; return n; }).toSorted((e, t) => { if (e.loaded !== t.loaded) return e.loaded ? -1 : 1; return (e.size ?? Number.MAX_SAFE_INTEGER) - (t.size ?? Number.MAX_SAFE_INTEGER) || e.name.localeCompare(t.name); }) }; } function createOllamaNodeHostCommands(e) { const t = e?.baseUrl ?? "http://127.0.0.1:11434"; return [{ command: OLLAMA_MODELS_COMMAND, cap: OLLAMA_NODE_INFERENCE_CAPABILITY, hasActiveWork: () => false, handle: async (e, n, r) => JSON.stringify(await discoverOllamaNodeModels(t, r?.signal)) }, { command: OLLAMA_CHAT_COMMAND, cap: OLLAMA_NODE_INFERENCE_CAPABILITY, hasActiveWork: () => false, handle: async (e, n, r) => { const i = readNodeCommandParams(e); const a = readToolStringParam(i, "model", { required: true }); const o = readToolStringParam(i, "prompt", { required: true, trim: false }); const s = readToolStringParam(i, "system", { trim: false }); const c = readPositiveIntegerParam(i, "maxTokens", { max: 8192, message: `maxTokens must be an integer between 1 and ${8192}` }) ?? 512; const l = readPositiveIntegerParam(i, "timeoutMs", { max: 6e5, message: `timeoutMs must be an integer between 1 and ${6e5}` }) ?? 12e4; const u = readFiniteNumberParam(i, "temperature", { min: 0, max: 2, message: "temperature must be between 0 and 2" }); if (o.length > 128e3) throw new Error(`prompt exceeds ${MAX_PROMPT_CHARS} characters`); if (s && s.length > 32e3) throw new Error(`system exceeds ${MAX_SYSTEM_PROMPT_CHARS} characters`); const d = r?.signal; const f = resolveOllamaApiBase(t); const p = performance.now() + l; const remainingTimeoutMs = () => { const e = Math.ceil(p - performance.now()); if (e <= 0) throw new Error(`Ollama node inference timed out after ${l}ms`); return e; }; const m = await fetchOllamaModels(f, { timeoutMs: remainingTimeoutMs(), ...d ? { signal: d } : {} }); const h = m.models.find((e) => e.name === a && !isOllamaRemoteModel(e)); const [g] = h ? await enrichOllamaModelsWithContext(f, [h], { timeoutMs: remainingTimeoutMs(), ...d ? { signal: d } : {} }) : []; if (!m.reachable || g?.capabilities?.includes("completion") !== true) { remainingTimeoutMs(); throw new Error(`Ollama model ${JSON.stringify(a)} is not a local chat model; discover models first`); } const _ = [...s ? [{ role: "system", content: s }] : [], { role: "user", content: o }]; const v = remainingTimeoutMs(); const y = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: a, messages: _, stream: false, think: false, options: { num_predict: c, ...u !== void 0 && { temperature: u } } }) }; let b; let x; try { const e = await fetchWithSsrFGuard({ url: `${f}/api/chat`, init: y, timeoutMs: v, ...d ? { signal: d } : {}, policy: buildOllamaBaseUrlSsrFPolicy(f), auditContext: "ollama-node-inference/api/chat" }); b = e.response; x = e.release; } catch (e) { throwIfOllamaRequestAborted(d); throw new Error(`Ollama is unavailable at ${f}: ${formatErrorMessage(e)}`, { cause: e }); } let S; try { if (!b.ok) { const e = (await readResponseTextLimited(b, MAX_ERROR_BODY_BYTES)).trim(); let t = e; try { const n = asNullableRecord(JSON.parse(e)); t = typeof n?.error === "string" ? n.error : e; } catch {} throw new Error(`Ollama /api/chat failed (HTTP ${b.status})${t ? `: ${t}` : ""}`); } S = await readProviderJsonResponse(b, "ollama-node-inference/api/chat"); } finally { await x(); } const C = typeof S.message?.content === "string" ? S.message.content : void 0; if (C === void 0) throw new Error("Ollama /api/chat response did not contain message.content"); if (S.done_reason === "length") throw new Error(`Ollama stopped after reaching maxTokens (${c}); retry with a larger maxTokens value`); const w = asFiniteNumber(S.prompt_eval_count); const T = asFiniteNumber(S.eval_count); const E = durationMs(S.load_duration); const D = durationMs(S.total_duration); return JSON.stringify({ provider: "ollama", model: typeof S.model === "string" && S.model.trim() ? S.model : a, response: C, ...w !== void 0 || T !== void 0 ? { usage: { promptTokens: w, completionTokens: T } } : {}, ...E !== void 0 || D !== void 0 ? { timings: { loadMs: E, totalMs: D } } : {} }); } }]; } function findNode(e, t) { const n = t.trim().toLowerCase(); const r = e.filter((e) => e.nodeId.toLowerCase() === n || e.displayName?.toLowerCase() === n); if (r.length === 0) throw new Error(`node ${JSON.stringify(t)} is not connected with Ollama inference support`); if (r.length > 1) throw new Error(`node ${JSON.stringify(t)} is ambiguous; use its nodeId`); return expectDefined(r[0], "single matching Ollama inference node"); } function parseInvokePayload(e) { const t = asNullableRecord(e); let n = asNullableRecord(t?.payload); if (!n && typeof t?.payloadJSON === "string") n = asNullableRecord(JSON.parse(t.payloadJSON)); if (!n) throw new Error("node returned an invalid Ollama inference payload"); return n; } async function invokeNode(e, t, n, r, i, a) { throwIfOllamaRequestAborted(a); return parseInvokePayload(await e.runtime.nodes.invoke({ nodeId: t, command: n, params: r, timeoutMs: i, scopes: ["operator.write"], ...a ? { signal: a } : {} })); } function createOllamaNodeInferenceTool(e) { return { ...ollamaNodeInferenceToolDefinition, execute: async (t, n, r) => { throwIfOllamaRequestAborted(r); const i = asNullableRecord(n) ?? {}; const a = readToolStringParam(i, "action", { required: true }); const o = readToolStringParam(i, "node"); const s = (await e.runtime.nodes.list({ connected: true })).nodes.filter((e) => (e.invocableCommands ?? e.commands)?.includes(OLLAMA_MODELS_COMMAND)); if (a === "discover") { const t = o ? [findNode(s, o)] : s; const n = await Promise.all(t.map(async (t) => { try { const n = await invokeNode(e, t.nodeId, OLLAMA_MODELS_COMMAND, {}, DISCOVERY_TRANSPORT_TIMEOUT_MS, r); const i = { nodeId: t.nodeId, ok: true }; if (t.displayName) i.displayName = t.displayName; return Object.assign(i, n); } catch (e) { throwIfOllamaRequestAborted(r); const n = { nodeId: t.nodeId, ok: false, error: formatErrorMessage(e) }; if (t.displayName) n.displayName = t.displayName; return n; } })); return jsonResult({ nodes: n, ...s.length === 0 && { hint: "No connected node advertises Ollama inference. Start Ollama and `openclaw node run` on the target machine, then approve any request shown by `openclaw nodes pending`." } }); } if (a !== "run") throw new Error("action must be discover or run"); const c = s.filter((e) => (e.invocableCommands ?? e.commands)?.includes(OLLAMA_CHAT_COMMAND)); const l = o ? findNode(c, o) : c.length === 1 ? c[0] : void 0; if (!l) throw new Error(c.length === 0 ? "no connected node advertises Ollama inference" : "multiple nodes advertise Ollama inference; specify node"); const u = readToolStringParam(i, "model", { required: true }); const d = readToolStringParam(i, "prompt", { required: true, trim: false }); const f = readPositiveIntegerParam(i, "maxTokens", { max: 8192 }) ?? 512; const p = readPositiveIntegerParam(i, "timeoutMs", { max: 6e5 }) ?? 12e4; const m = readToolStringParam(i, "system", { trim: false }); const h = readFiniteNumberParam(i, "temperature", { min: 0, max: 2 }); const g = { model: u, prompt: d, maxTokens: f, timeoutMs: p }; if (m !== void 0) g.system = m; if (h !== void 0) g.temperature = h; const _ = await invokeNode(e, l.nodeId, OLLAMA_CHAT_COMMAND, g, p, r); return jsonResult({ nodeId: l.nodeId, ...l.displayName && { displayName: l.displayName }, ..._ }); } }; } //#endregion export { createOllamaNodeHostCommands, createOllamaNodeInferenceTool };