@engenty/local-models 0.0.0-stage → 0.20.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +41 -2
- package/dist/clients/chat.d.ts +89 -0
- package/dist/clients/chat.js +22 -0
- package/dist/clients/claude.d.ts +32 -0
- package/dist/clients/claude.js +238 -0
- package/dist/clients/client.d.ts +29 -0
- package/dist/clients/client.js +2 -0
- package/dist/clients/codex.d.ts +35 -0
- package/dist/clients/codex.js +253 -0
- package/dist/clients/cursor.d.ts +33 -0
- package/dist/clients/cursor.js +180 -0
- package/dist/clients/detect.d.ts +18 -0
- package/dist/clients/detect.js +34 -0
- package/dist/clients/env.d.ts +66 -0
- package/dist/clients/env.js +211 -0
- package/dist/clients/failure.d.ts +26 -0
- package/dist/clients/failure.js +35 -0
- package/dist/clients/index.d.ts +14 -0
- package/dist/clients/index.js +16 -0
- package/dist/clients/model.d.ts +126 -0
- package/dist/clients/model.js +225 -0
- package/dist/clients/prompt.d.ts +36 -0
- package/dist/clients/prompt.js +123 -0
- package/dist/clients/run.d.ts +15 -0
- package/dist/clients/run.js +41 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/ollama/api.d.ts +70 -0
- package/dist/ollama/api.js +164 -0
- package/dist/ollama/index.d.ts +2 -0
- package/dist/ollama/index.js +2 -0
- package/dist/ollama/model.d.ts +52 -0
- package/dist/ollama/model.js +302 -0
- package/dist/probe.d.ts +54 -0
- package/dist/probe.js +190 -0
- package/package.json +56 -4
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { LanguageModel } from "ai";
|
|
2
|
+
type V3 = Extract<LanguageModel, {
|
|
3
|
+
specificationVersion: "v3";
|
|
4
|
+
}>;
|
|
5
|
+
type CallOptions = Parameters<V3["doGenerate"]>[0];
|
|
6
|
+
type GenerateResult = Awaited<ReturnType<V3["doGenerate"]>>;
|
|
7
|
+
export type Message = CallOptions["prompt"][number];
|
|
8
|
+
export type Warning = GenerateResult["warnings"][number];
|
|
9
|
+
/** The sentences a client reads besides the call's own messages; a host may word them itself. */
|
|
10
|
+
export interface PromptWords {
|
|
11
|
+
/** Where a saved attachment stood in the prompt. */
|
|
12
|
+
attachedFile(path: string): string;
|
|
13
|
+
/** Added to the system prompt when the client gets a whole thread as one prompt. */
|
|
14
|
+
conversationNote(): string;
|
|
15
|
+
/** For a client without a schema option; `schema` is the JSON Schema, as JSON. */
|
|
16
|
+
jsonInstruction(schema: string): string;
|
|
17
|
+
}
|
|
18
|
+
export declare const DEFAULT_WORDS: PromptWords;
|
|
19
|
+
/** The extension a saved attachment gets, so the client reads it as what it is. */
|
|
20
|
+
export declare function extensionOf(mediaType: string, filename?: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* The conversation as a client takes it: one system prompt and one prompt on stdin. A single
|
|
23
|
+
* user message goes as it is; a longer thread is written out with its speakers, and the client
|
|
24
|
+
* is asked to answer its last message. Attachments are saved to `dir` and named in the prompt.
|
|
25
|
+
*/
|
|
26
|
+
export declare function renderPrompt(messages: Message[], dir?: string, words?: PromptWords): {
|
|
27
|
+
system: string;
|
|
28
|
+
prompt: string;
|
|
29
|
+
files: string[];
|
|
30
|
+
warnings: Warning[];
|
|
31
|
+
};
|
|
32
|
+
/** What a client without a schema option is told so its answer parses. */
|
|
33
|
+
export declare function jsonInstruction(schema: unknown, words?: PromptWords): string;
|
|
34
|
+
/** A client's answer as JSON: the fences and prose some wrap around it are taken off. */
|
|
35
|
+
export declare function parseJsonAnswer(text: string): unknown;
|
|
36
|
+
export {};
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
export const DEFAULT_WORDS = {
|
|
4
|
+
attachedFile: (path) => `[Attached file — open it to read it: ${path}]`,
|
|
5
|
+
conversationNote: () => "The prompt holds the conversation so far, each message headed by its speaker. Answer the last message as the assistant — the answer only, no speaker label.",
|
|
6
|
+
jsonInstruction: (schema) => `Answer with one JSON value only — no prose, no code fence — that matches this JSON Schema:\n${schema}`,
|
|
7
|
+
};
|
|
8
|
+
/** The extension a saved attachment gets, so the client reads it as what it is. */
|
|
9
|
+
export function extensionOf(mediaType, filename) {
|
|
10
|
+
const own = filename?.match(/\.([a-z0-9]{1,5})$/i)?.[1];
|
|
11
|
+
if (own) {
|
|
12
|
+
return own.toLowerCase();
|
|
13
|
+
}
|
|
14
|
+
const sub = mediaType.split("/")[1] ?? "bin";
|
|
15
|
+
return { jpeg: "jpg", "svg+xml": "svg", plain: "txt", markdown: "md" }[sub] ?? sub;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The conversation as a client takes it: one system prompt and one prompt on stdin. A single
|
|
19
|
+
* user message goes as it is; a longer thread is written out with its speakers, and the client
|
|
20
|
+
* is asked to answer its last message. Attachments are saved to `dir` and named in the prompt.
|
|
21
|
+
*/
|
|
22
|
+
export function renderPrompt(messages, dir, words = DEFAULT_WORDS) {
|
|
23
|
+
const warnings = [];
|
|
24
|
+
const files = [];
|
|
25
|
+
const system = [];
|
|
26
|
+
const turns = [];
|
|
27
|
+
const saveFile = (input) => {
|
|
28
|
+
// A file's content comes tagged: { type: "data", data } | { type: "url", url } | { type: "text", text }.
|
|
29
|
+
const tagged = input.data;
|
|
30
|
+
const data = tagged && typeof tagged === "object" && typeof tagged.type === "string"
|
|
31
|
+
? tagged.type === "url"
|
|
32
|
+
? tagged.url
|
|
33
|
+
: tagged.type === "text"
|
|
34
|
+
? Buffer.from(tagged.text ?? "", "utf8")
|
|
35
|
+
: tagged.data
|
|
36
|
+
: input.data;
|
|
37
|
+
const part = { ...input, data };
|
|
38
|
+
if (part.data instanceof URL) {
|
|
39
|
+
return `[Attachment at ${part.data.href} (${part.mediaType})]`;
|
|
40
|
+
}
|
|
41
|
+
if (typeof part.data !== "string" && !(part.data instanceof Uint8Array)) {
|
|
42
|
+
warnings.push({ type: "unsupported", feature: "file parts" });
|
|
43
|
+
return `[Attachment: ${part.filename ?? part.mediaType}]`;
|
|
44
|
+
}
|
|
45
|
+
if (!dir) {
|
|
46
|
+
warnings.push({ type: "unsupported", feature: "file parts" });
|
|
47
|
+
return `[Attachment: ${part.filename ?? part.mediaType}]`;
|
|
48
|
+
}
|
|
49
|
+
const path = join(dir, `${files.length + 1}.${extensionOf(part.mediaType, part.filename)}`);
|
|
50
|
+
const bytes = typeof part.data === "string" ? Buffer.from(part.data, "base64") : part.data;
|
|
51
|
+
writeFileSync(path, bytes);
|
|
52
|
+
files.push(path);
|
|
53
|
+
return words.attachedFile(path);
|
|
54
|
+
};
|
|
55
|
+
for (const m of messages) {
|
|
56
|
+
if (m.role === "system") {
|
|
57
|
+
system.push(m.content);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const text = m.content
|
|
61
|
+
.map((part) => {
|
|
62
|
+
switch (part.type) {
|
|
63
|
+
case "text":
|
|
64
|
+
return part.text;
|
|
65
|
+
case "file":
|
|
66
|
+
return saveFile(part);
|
|
67
|
+
case "reasoning":
|
|
68
|
+
return "";
|
|
69
|
+
case "tool-call":
|
|
70
|
+
return `[Called ${part.toolName} with ${JSON.stringify(part.input)}]`;
|
|
71
|
+
case "tool-result": {
|
|
72
|
+
const out = part.output;
|
|
73
|
+
const value = out.type === "text" || out.type === "error-text"
|
|
74
|
+
? String(out.value)
|
|
75
|
+
: out.type === "json" || out.type === "error-json"
|
|
76
|
+
? JSON.stringify(out.value)
|
|
77
|
+
: out.type === "execution-denied"
|
|
78
|
+
? `denied${out.reason ? `: ${out.reason}` : ""}`
|
|
79
|
+
: JSON.stringify(out.value ?? out);
|
|
80
|
+
return `[Result of ${part.toolName}: ${value}]`;
|
|
81
|
+
}
|
|
82
|
+
default:
|
|
83
|
+
return "";
|
|
84
|
+
}
|
|
85
|
+
})
|
|
86
|
+
.filter(Boolean)
|
|
87
|
+
.join("\n");
|
|
88
|
+
turns.push({ role: m.role, text });
|
|
89
|
+
}
|
|
90
|
+
const request = turns.length === 1 && turns[0].role === "user"
|
|
91
|
+
? turns[0].text
|
|
92
|
+
: turns
|
|
93
|
+
.map((t) => `${t.role === "user" ? "User" : t.role === "tool" ? "Tool" : "Assistant"}:\n${t.text}`)
|
|
94
|
+
.join("\n\n");
|
|
95
|
+
if (turns.length > 1) {
|
|
96
|
+
system.push(words.conversationNote());
|
|
97
|
+
}
|
|
98
|
+
return { system: system.join("\n\n"), prompt: request, files, warnings };
|
|
99
|
+
}
|
|
100
|
+
/** What a client without a schema option is told so its answer parses. */
|
|
101
|
+
export function jsonInstruction(schema, words = DEFAULT_WORDS) {
|
|
102
|
+
return words.jsonInstruction(JSON.stringify(schema ?? { type: "object" }));
|
|
103
|
+
}
|
|
104
|
+
/** A client's answer as JSON: the fences and prose some wrap around it are taken off. */
|
|
105
|
+
export function parseJsonAnswer(text) {
|
|
106
|
+
const trimmed = text.trim();
|
|
107
|
+
const unfenced = trimmed
|
|
108
|
+
.replace(/^\s*```(?:json)?\s*/i, "")
|
|
109
|
+
.replace(/\s*```\s*$/, "")
|
|
110
|
+
.trim();
|
|
111
|
+
try {
|
|
112
|
+
return JSON.parse(unfenced);
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
// Prose around the value: take the outermost object or array.
|
|
116
|
+
const start = unfenced.search(/[{[]/);
|
|
117
|
+
const end = Math.max(unfenced.lastIndexOf("}"), unfenced.lastIndexOf("]"));
|
|
118
|
+
if (start >= 0 && end > start) {
|
|
119
|
+
return JSON.parse(unfenced.slice(start, end + 1));
|
|
120
|
+
}
|
|
121
|
+
throw new Error("The answer is not JSON.");
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** What one run of a client printed, and how it ended. */
|
|
2
|
+
export interface ClientOutput {
|
|
3
|
+
stdout: string;
|
|
4
|
+
stderr: string;
|
|
5
|
+
code: number | null;
|
|
6
|
+
}
|
|
7
|
+
/** Runs a client once with the prompt on stdin; a client that is not there raises ENOENT. */
|
|
8
|
+
export declare function runClient(bin: string, args: string[], opts: {
|
|
9
|
+
cwd: string;
|
|
10
|
+
env: NodeJS.ProcessEnv;
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
stdin?: string;
|
|
13
|
+
}): Promise<ClientOutput>;
|
|
14
|
+
/** The last line of an output that is a JSON object. */
|
|
15
|
+
export declare function lastJson<T>(stdout: string): T | null;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import spawn from "cross-spawn";
|
|
2
|
+
/** Runs a client once with the prompt on stdin; a client that is not there raises ENOENT. */
|
|
3
|
+
export function runClient(bin, args, opts) {
|
|
4
|
+
return new Promise((resolve, reject) => {
|
|
5
|
+
const child = spawn(bin, args, {
|
|
6
|
+
cwd: opts.cwd,
|
|
7
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
8
|
+
signal: opts.signal,
|
|
9
|
+
env: opts.env,
|
|
10
|
+
});
|
|
11
|
+
let stdout = "";
|
|
12
|
+
let stderr = "";
|
|
13
|
+
child.stdout.on("data", (chunk) => {
|
|
14
|
+
stdout += String(chunk);
|
|
15
|
+
});
|
|
16
|
+
child.stderr.on("data", (chunk) => {
|
|
17
|
+
stderr = (stderr + String(chunk)).slice(-4000);
|
|
18
|
+
});
|
|
19
|
+
child.on("error", reject);
|
|
20
|
+
child.on("close", (code) => resolve({ stdout, stderr, code }));
|
|
21
|
+
child.stdin.on("error", () => {
|
|
22
|
+
// The client went away before reading the prompt; `close` reports it.
|
|
23
|
+
});
|
|
24
|
+
child.stdin.end(opts.stdin ?? "");
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
/** The last line of an output that is a JSON object. */
|
|
28
|
+
export function lastJson(stdout) {
|
|
29
|
+
for (const line of stdout.trim().split("\n").reverse()) {
|
|
30
|
+
try {
|
|
31
|
+
const value = JSON.parse(line);
|
|
32
|
+
if (value && typeof value === "object") {
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
// not it
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return null;
|
|
41
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { CLIENT_IDS, CLIENTS, type Client, type ClientId, detectClient } from "./clients/index.js";
|
|
2
|
+
export { fits, type InstalledModel, installedModels, ollamaModel, ollamaRoot, ollamaState, pullModel, } from "./ollama/index.js";
|
|
3
|
+
export { type ProbeResult, type ProbeSource, type ProbeState, probe } from "./probe.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ollama on a computer, through its own API (`/api/…`): whether it runs, the models it holds and
|
|
3
|
+
* what each can do, which of them fits the computer's memory, and downloads.
|
|
4
|
+
*/
|
|
5
|
+
/** Where Ollama answers when nothing names another address. */
|
|
6
|
+
export declare const OLLAMA_DEFAULT = "http://127.0.0.1:11434";
|
|
7
|
+
/**
|
|
8
|
+
* Ollama's root address, from either way it is given: a root as OLLAMA_HOST names it
|
|
9
|
+
* (`http://127.0.0.1:11434`, also `127.0.0.1:11434` or `localhost`), or the OpenAI-compatible
|
|
10
|
+
* address as OLLAMA_URL names it (`http://127.0.0.1:11434/v1`). An address without a scheme is
|
|
11
|
+
* http, and without a port too it is on Ollama's port.
|
|
12
|
+
*/
|
|
13
|
+
export declare function ollamaRoot(url: string): string;
|
|
14
|
+
/** Where Ollama answers for this process: OLLAMA_URL (a root or `…/v1`), else Ollama's default. */
|
|
15
|
+
export declare function ollamaAddress(env?: NodeJS.ProcessEnv): string;
|
|
16
|
+
export interface OllamaRequestOptions {
|
|
17
|
+
/** Another fetch, such as a test's. */
|
|
18
|
+
fetch?: typeof fetch;
|
|
19
|
+
}
|
|
20
|
+
export interface OllamaState {
|
|
21
|
+
/** The version of the Ollama that answers; null where none does. */
|
|
22
|
+
version: string | null;
|
|
23
|
+
/** The names of the models it holds; empty where it does not answer. */
|
|
24
|
+
models: string[];
|
|
25
|
+
}
|
|
26
|
+
/** Whether Ollama answers at `url`, and the models it holds. */
|
|
27
|
+
export declare function ollamaState(url: string, options?: OllamaRequestOptions): Promise<OllamaState>;
|
|
28
|
+
/** A model Ollama holds, as Ollama describes it. */
|
|
29
|
+
export interface InstalledModel {
|
|
30
|
+
name: string;
|
|
31
|
+
/** On disk, in bytes: about the memory it takes while it answers, too. */
|
|
32
|
+
size: number;
|
|
33
|
+
digest: string;
|
|
34
|
+
/** As Ollama says: `completion`, `tools`, `vision`, `thinking`, `audio`, `embedding`, … */
|
|
35
|
+
capabilities: string[];
|
|
36
|
+
/** It writes text. */
|
|
37
|
+
completion: boolean;
|
|
38
|
+
/** It takes tools. */
|
|
39
|
+
tools: boolean;
|
|
40
|
+
/** It takes pictures. */
|
|
41
|
+
vision: boolean;
|
|
42
|
+
/** It can think before it answers. */
|
|
43
|
+
thinking: boolean;
|
|
44
|
+
/** `mlx` or `llamacpp`; null where Ollama does not say. */
|
|
45
|
+
runner: string | null;
|
|
46
|
+
quantization: string | null;
|
|
47
|
+
/** In memory right now. */
|
|
48
|
+
running: boolean;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The models of the Ollama at `url`, each with what it can do and whether it is in memory.
|
|
52
|
+
* Ollama describes them all at once; a model it does not describe in time has no capabilities.
|
|
53
|
+
* Empty where Ollama does not answer.
|
|
54
|
+
*/
|
|
55
|
+
export declare function installedModels(url: string, options?: OllamaRequestOptions): Promise<InstalledModel[]>;
|
|
56
|
+
/**
|
|
57
|
+
* Whether a model fits a computer: it takes at most `share` of the memory, and leaves the rest to
|
|
58
|
+
* everything else that runs there. Size and memory in the same unit; the model's size on disk
|
|
59
|
+
* is about what it takes while it answers.
|
|
60
|
+
*/
|
|
61
|
+
export declare function fits(model: number | {
|
|
62
|
+
size: number;
|
|
63
|
+
}, memory: number, share: number): boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Pulls a model into the Ollama at `url`; `onProgress` hears the bytes so far and in all as they
|
|
66
|
+
* come, summed over the model's parts. Rejects with Ollama's own reason.
|
|
67
|
+
*/
|
|
68
|
+
export declare function pullModel(url: string, model: string, onProgress: (done: number, total: number) => void, options?: OllamaRequestOptions & {
|
|
69
|
+
signal?: AbortSignal;
|
|
70
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ollama on a computer, through its own API (`/api/…`): whether it runs, the models it holds and
|
|
3
|
+
* what each can do, which of them fits the computer's memory, and downloads.
|
|
4
|
+
*/
|
|
5
|
+
/** Where Ollama answers when nothing names another address. */
|
|
6
|
+
export const OLLAMA_DEFAULT = "http://127.0.0.1:11434";
|
|
7
|
+
/** Ollama's own port, for an address given without one. */
|
|
8
|
+
const OLLAMA_PORT = "11434";
|
|
9
|
+
/**
|
|
10
|
+
* Ollama's root address, from either way it is given: a root as OLLAMA_HOST names it
|
|
11
|
+
* (`http://127.0.0.1:11434`, also `127.0.0.1:11434` or `localhost`), or the OpenAI-compatible
|
|
12
|
+
* address as OLLAMA_URL names it (`http://127.0.0.1:11434/v1`). An address without a scheme is
|
|
13
|
+
* http, and without a port too it is on Ollama's port.
|
|
14
|
+
*/
|
|
15
|
+
export function ollamaRoot(url) {
|
|
16
|
+
const root = url.trim().replace(/\/+$/, "").replace(/\/v1$/, "");
|
|
17
|
+
if (!root || /^[a-z][a-z0-9+.-]*:\/\//i.test(root)) {
|
|
18
|
+
return root;
|
|
19
|
+
}
|
|
20
|
+
try {
|
|
21
|
+
const parsed = new URL(`http://${root}`);
|
|
22
|
+
if (!parsed.port) {
|
|
23
|
+
parsed.port = OLLAMA_PORT;
|
|
24
|
+
}
|
|
25
|
+
return `${parsed.origin}${parsed.pathname}`.replace(/\/+$/, "");
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return `http://${root}`;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** Where Ollama answers for this process: OLLAMA_URL (a root or `…/v1`), else Ollama's default. */
|
|
32
|
+
export function ollamaAddress(env = process.env) {
|
|
33
|
+
return ollamaRoot(env.OLLAMA_URL || OLLAMA_DEFAULT);
|
|
34
|
+
}
|
|
35
|
+
async function getJson(doFetch, url, init, timeoutMs = 2000) {
|
|
36
|
+
try {
|
|
37
|
+
const res = await doFetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
|
|
38
|
+
return res.ok ? (await res.json()) : null;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** Whether Ollama answers at `url`, and the models it holds. */
|
|
45
|
+
export async function ollamaState(url, options = {}) {
|
|
46
|
+
const doFetch = options.fetch ?? fetch;
|
|
47
|
+
const root = ollamaRoot(url);
|
|
48
|
+
const version = (await getJson(doFetch, `${root}/api/version`))?.version ?? null;
|
|
49
|
+
const tags = version
|
|
50
|
+
? await getJson(doFetch, `${root}/api/tags`)
|
|
51
|
+
: null;
|
|
52
|
+
return { version, models: (tags?.models ?? []).map((m) => m.name) };
|
|
53
|
+
}
|
|
54
|
+
/** What `/api/show` said about a model, by its digest: it does not change while the digest stays. */
|
|
55
|
+
const shown = new Map();
|
|
56
|
+
/**
|
|
57
|
+
* The models of the Ollama at `url`, each with what it can do and whether it is in memory.
|
|
58
|
+
* Ollama describes them all at once; a model it does not describe in time has no capabilities.
|
|
59
|
+
* Empty where Ollama does not answer.
|
|
60
|
+
*/
|
|
61
|
+
export async function installedModels(url, options = {}) {
|
|
62
|
+
const doFetch = options.fetch ?? fetch;
|
|
63
|
+
const root = ollamaRoot(url);
|
|
64
|
+
const [tags, ps] = await Promise.all([
|
|
65
|
+
getJson(doFetch, `${root}/api/tags`),
|
|
66
|
+
getJson(doFetch, `${root}/api/ps`),
|
|
67
|
+
]);
|
|
68
|
+
const running = new Set((ps?.models ?? []).map((m) => m.name));
|
|
69
|
+
return Promise.all((tags?.models ?? []).map(async (m) => {
|
|
70
|
+
let show = shown.get(m.digest);
|
|
71
|
+
if (!show) {
|
|
72
|
+
const answer = await getJson(doFetch, `${root}/api/show`, {
|
|
73
|
+
method: "POST",
|
|
74
|
+
headers: { "content-type": "application/json" },
|
|
75
|
+
body: JSON.stringify({ model: m.name }),
|
|
76
|
+
}, 5000);
|
|
77
|
+
show = answer ?? {};
|
|
78
|
+
if (answer) {
|
|
79
|
+
shown.set(m.digest, answer);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const capabilities = show.capabilities ?? [];
|
|
83
|
+
return {
|
|
84
|
+
name: m.name,
|
|
85
|
+
size: m.size,
|
|
86
|
+
digest: m.digest,
|
|
87
|
+
capabilities,
|
|
88
|
+
completion: capabilities.includes("completion"),
|
|
89
|
+
tools: capabilities.includes("tools"),
|
|
90
|
+
vision: capabilities.includes("vision"),
|
|
91
|
+
thinking: capabilities.includes("thinking"),
|
|
92
|
+
runner: show.details?.runner || null,
|
|
93
|
+
quantization: show.details?.quantization_level || null,
|
|
94
|
+
running: running.has(m.name),
|
|
95
|
+
};
|
|
96
|
+
}));
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Whether a model fits a computer: it takes at most `share` of the memory, and leaves the rest to
|
|
100
|
+
* everything else that runs there. Size and memory in the same unit; the model's size on disk
|
|
101
|
+
* is about what it takes while it answers.
|
|
102
|
+
*/
|
|
103
|
+
export function fits(model, memory, share) {
|
|
104
|
+
const size = typeof model === "number" ? model : model.size;
|
|
105
|
+
return size <= memory * share;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Pulls a model into the Ollama at `url`; `onProgress` hears the bytes so far and in all as they
|
|
109
|
+
* come, summed over the model's parts. Rejects with Ollama's own reason.
|
|
110
|
+
*/
|
|
111
|
+
export async function pullModel(url, model, onProgress, options = {}) {
|
|
112
|
+
const doFetch = options.fetch ?? fetch;
|
|
113
|
+
const res = await doFetch(`${ollamaRoot(url)}/api/pull`, {
|
|
114
|
+
method: "POST",
|
|
115
|
+
headers: { "content-type": "application/json" },
|
|
116
|
+
body: JSON.stringify({ model, stream: true }),
|
|
117
|
+
signal: options.signal,
|
|
118
|
+
});
|
|
119
|
+
if (!(res.ok && res.body)) {
|
|
120
|
+
throw new Error(`Ollama answered ${res.status}. ${await res.text().catch(() => "")}`.trim());
|
|
121
|
+
}
|
|
122
|
+
// Each part of the model reports on its own; the sum is the download.
|
|
123
|
+
const parts = new Map();
|
|
124
|
+
const reader = res.body.getReader();
|
|
125
|
+
const decoder = new TextDecoder();
|
|
126
|
+
let pending = "";
|
|
127
|
+
let finished = false;
|
|
128
|
+
const read = (line) => {
|
|
129
|
+
if (!line.trim()) {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const event = JSON.parse(line);
|
|
133
|
+
if (event.error) {
|
|
134
|
+
throw new Error(event.error);
|
|
135
|
+
}
|
|
136
|
+
if (event.digest && event.total) {
|
|
137
|
+
parts.set(event.digest, { total: event.total, completed: event.completed ?? 0 });
|
|
138
|
+
let sum = 0;
|
|
139
|
+
let all = 0;
|
|
140
|
+
for (const part of parts.values()) {
|
|
141
|
+
sum += part.completed;
|
|
142
|
+
all += part.total;
|
|
143
|
+
}
|
|
144
|
+
onProgress(sum, all);
|
|
145
|
+
}
|
|
146
|
+
finished ||= event.status === "success";
|
|
147
|
+
};
|
|
148
|
+
for (;;) {
|
|
149
|
+
const { done, value } = await reader.read();
|
|
150
|
+
if (done) {
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
pending += decoder.decode(value, { stream: true });
|
|
154
|
+
const lines = pending.split("\n");
|
|
155
|
+
pending = lines.pop() ?? "";
|
|
156
|
+
for (const line of lines) {
|
|
157
|
+
read(line);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
read(pending);
|
|
161
|
+
if (!finished) {
|
|
162
|
+
throw new Error("The download broke off.");
|
|
163
|
+
}
|
|
164
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { fits, type InstalledModel, installedModels, OLLAMA_DEFAULT, type OllamaRequestOptions, type OllamaState, ollamaAddress, ollamaRoot, ollamaState, pullModel, } from "./api.js";
|
|
2
|
+
export { base64Of, type CallOptions, type ChatModel, type GenerateResult, generateFrom, type OllamaSetup, ollamaMessages, ollamaModel, type StreamPart, type StreamResult, } from "./model.js";
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { LanguageModel } from "ai";
|
|
2
|
+
/**
|
|
3
|
+
* A model of Ollama as an AI SDK language model, on Ollama's own chat API (`/api/chat`). The
|
|
4
|
+
* OpenAI-compatible API cannot set the context length, and Ollama then cuts a long conversation
|
|
5
|
+
* without saying so; here the caller sets it.
|
|
6
|
+
*/
|
|
7
|
+
/** The AI SDK's language model, version 3. */
|
|
8
|
+
export type ChatModel = Extract<LanguageModel, {
|
|
9
|
+
specificationVersion: "v3";
|
|
10
|
+
}>;
|
|
11
|
+
export type CallOptions = Parameters<ChatModel["doStream"]>[0];
|
|
12
|
+
export type StreamResult = Awaited<ReturnType<ChatModel["doStream"]>>;
|
|
13
|
+
export type StreamPart = StreamResult["stream"] extends ReadableStream<infer P> ? P : never;
|
|
14
|
+
export type GenerateResult = Awaited<ReturnType<ChatModel["doGenerate"]>>;
|
|
15
|
+
export interface OllamaSetup {
|
|
16
|
+
/** Ollama's address: its root, or the OpenAI-compatible `…/v1`. */
|
|
17
|
+
url: string;
|
|
18
|
+
model: string;
|
|
19
|
+
/** Tokens the model reads at most (`num_ctx`); left out, Ollama's default. */
|
|
20
|
+
context?: number;
|
|
21
|
+
/** Whether the model gets the call's tools. Without them it only talks. Default: true. */
|
|
22
|
+
tools?: boolean;
|
|
23
|
+
/** Whether the model thinks before it answers; left out, Ollama decides. What it thinks is not part of the answer. */
|
|
24
|
+
thinking?: boolean;
|
|
25
|
+
fetch?: typeof fetch;
|
|
26
|
+
}
|
|
27
|
+
interface OllamaMessage {
|
|
28
|
+
role: "system" | "user" | "assistant" | "tool";
|
|
29
|
+
content: string;
|
|
30
|
+
/** Pictures of the message, base64. */
|
|
31
|
+
images?: string[];
|
|
32
|
+
tool_calls?: {
|
|
33
|
+
function: {
|
|
34
|
+
name: string;
|
|
35
|
+
arguments: unknown;
|
|
36
|
+
};
|
|
37
|
+
}[];
|
|
38
|
+
tool_name?: string;
|
|
39
|
+
}
|
|
40
|
+
/** A file part's bytes as base64, however the AI SDK hands them over. */
|
|
41
|
+
export declare function base64Of(data: unknown): string | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* The AI SDK's prompt as Ollama's messages. Pictures go along with the newest message of the
|
|
44
|
+
* person and what tools showed after it; an older message names its pictures instead, so they
|
|
45
|
+
* are not sent again each turn.
|
|
46
|
+
*/
|
|
47
|
+
export declare function ollamaMessages(prompt: CallOptions["prompt"]): OllamaMessage[];
|
|
48
|
+
/** A model of the Ollama at `setup.url`, streaming its answer, its tool calls and the usage. */
|
|
49
|
+
export declare function ollamaModel(setup: OllamaSetup): ChatModel;
|
|
50
|
+
/** A whole answer from a model that streams. */
|
|
51
|
+
export declare function generateFrom(doStream: (options: CallOptions) => Promise<StreamResult>, options: CallOptions): Promise<GenerateResult>;
|
|
52
|
+
export {};
|