@fgv/ts-extras-ollama 5.1.0-34
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/.rush/temp/b70e5f6b6ada97ea70c5583027ea2b58b27bef46.tar.log +54 -0
- package/.rush/temp/chunked-rush-logs/ts-extras-ollama.build.chunks.jsonl +9 -0
- package/.rush/temp/operation/build/all.log +9 -0
- package/.rush/temp/operation/build/log-chunks.jsonl +9 -0
- package/.rush/temp/operation/build/state.json +3 -0
- package/.rush/temp/shrinkwrap-deps.json +681 -0
- package/CHANGELOG.json +4 -0
- package/README.md +105 -0
- package/config/api-extractor.json +38 -0
- package/config/jest.config.json +13 -0
- package/config/rig.json +6 -0
- package/dist/index.js +388 -0
- package/dist/index.js.map +1 -0
- package/dist/test/unit/chatStructured.test.js +287 -0
- package/dist/test/unit/chatStructured.test.js.map +1 -0
- package/dist/test/unit/fixtures/wireFixtures.js +90 -0
- package/dist/test/unit/fixtures/wireFixtures.js.map +1 -0
- package/dist/test/unit/modelManagement.test.js +118 -0
- package/dist/test/unit/modelManagement.test.js.map +1 -0
- package/dist/test/unit/ollamaClient.test.js +38 -0
- package/dist/test/unit/ollamaClient.test.js.map +1 -0
- package/dist/test/unit/pullModel.test.js +202 -0
- package/dist/test/unit/pullModel.test.js.map +1 -0
- package/dist/ts-extras-ollama.d.ts +365 -0
- package/dist/tsdoc-metadata.json +11 -0
- package/eslint.config.js +15 -0
- package/etc/ts-extras-ollama.api.md +139 -0
- package/lib/index.d.ts +341 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +397 -0
- package/lib/index.js.map +1 -0
- package/lib/test/unit/chatStructured.test.d.ts +2 -0
- package/lib/test/unit/chatStructured.test.d.ts.map +1 -0
- package/lib/test/unit/chatStructured.test.js +289 -0
- package/lib/test/unit/chatStructured.test.js.map +1 -0
- package/lib/test/unit/fixtures/wireFixtures.d.ts +19 -0
- package/lib/test/unit/fixtures/wireFixtures.d.ts.map +1 -0
- package/lib/test/unit/fixtures/wireFixtures.js +93 -0
- package/lib/test/unit/fixtures/wireFixtures.js.map +1 -0
- package/lib/test/unit/modelManagement.test.d.ts +2 -0
- package/lib/test/unit/modelManagement.test.d.ts.map +1 -0
- package/lib/test/unit/modelManagement.test.js +120 -0
- package/lib/test/unit/modelManagement.test.js.map +1 -0
- package/lib/test/unit/ollamaClient.test.d.ts +2 -0
- package/lib/test/unit/ollamaClient.test.d.ts.map +1 -0
- package/lib/test/unit/ollamaClient.test.js +40 -0
- package/lib/test/unit/ollamaClient.test.js.map +1 -0
- package/lib/test/unit/pullModel.test.d.ts +2 -0
- package/lib/test/unit/pullModel.test.d.ts.map +1 -0
- package/lib/test/unit/pullModel.test.js +204 -0
- package/lib/test/unit/pullModel.test.js.map +1 -0
- package/package.json +83 -0
- package/rush-logs/ts-extras-ollama.build.cache.log +3 -0
- package/rush-logs/ts-extras-ollama.build.log +9 -0
- package/src/index.ts +655 -0
- package/src/test/unit/chatStructured.test.ts +330 -0
- package/src/test/unit/fixtures/wireFixtures.ts +95 -0
- package/src/test/unit/modelManagement.test.ts +128 -0
- package/src/test/unit/ollamaClient.test.ts +44 -0
- package/src/test/unit/pullModel.test.ts +220 -0
- package/temp/build/lint/_eslint-5eVG3S6w.json +30 -0
- package/temp/build/typescript/ts_8nwakTlr.json +1 -0
- package/temp/ts-extras-ollama.api.json +2528 -0
- package/temp/ts-extras-ollama.api.md +139 -0
- package/tsconfig.json +8 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@fgv/ts-extras-ollama` — Result-integration boundary over the official `ollama` JS library
|
|
3
|
+
* (Node-side).
|
|
4
|
+
*
|
|
5
|
+
* A thin facade that wraps the `ollama` client's native-API calls in `Result<T>` from
|
|
6
|
+
* `@fgv/ts-utils`, mirroring the discipline established by `@fgv/ts-extras-webauthn` and
|
|
7
|
+
* `@fgv/ts-extras-transformers`: one-line `captureResult` / `captureAsyncResult` wrappers around
|
|
8
|
+
* upstream primitives with **no opinionated orchestration** above the boundary.
|
|
9
|
+
*
|
|
10
|
+
* This package owns **exactly and only** the native-Ollama surface that the OpenAI-compatible
|
|
11
|
+
* `/v1` endpoint cannot express: model management (`/api/tags`, `/api/show`, `/api/ps`,
|
|
12
|
+
* `/api/delete`), streamed model pulls (`/api/pull`), and grammar-constrained structured output
|
|
13
|
+
* (`/api/chat` with a full-JSON-schema `format`). The text-completion / streaming / tool-use path
|
|
14
|
+
* is **not** duplicated here — `@fgv/ts-extras/ai-assist` owns it via the `/v1` compat layer
|
|
15
|
+
* (point a provider descriptor's `endpoint` at `http://localhost:11434/v1`).
|
|
16
|
+
*
|
|
17
|
+
* **Explicitly NOT in scope:**
|
|
18
|
+
* - Text completion / free-text chat / streaming chat (ai-assist owns it via `/v1`).
|
|
19
|
+
* - Browser / CORS path (Node-only at v0.1; a future `@fgv/ts-web-extras-ollama` is its home).
|
|
20
|
+
* - Model authoring / publishing (`push`, `create`, `copy`) — use the `ollama` lib directly.
|
|
21
|
+
* - `keep_alive` / model-lifecycle policy — pass-through only, no policy applied.
|
|
22
|
+
* - Pull-progress UI / rendering — `onProgress` hands raw chunks to the consumer.
|
|
23
|
+
* - Multi-host orchestration / connection pooling / retries / backoff — one client = one host.
|
|
24
|
+
*
|
|
25
|
+
* For any of the above, use the `ollama` library directly (with `captureAsyncResult` for your own
|
|
26
|
+
* Result wrapping); the opaque client handle returned by {@link createOllamaClient} is the
|
|
27
|
+
* upstream instance, so nothing this boundary omits is hidden from you.
|
|
28
|
+
*
|
|
29
|
+
* @packageDocumentation
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import {
|
|
33
|
+
Ollama,
|
|
34
|
+
type ChatRequest,
|
|
35
|
+
type ListResponse,
|
|
36
|
+
type Message,
|
|
37
|
+
type ModelResponse,
|
|
38
|
+
type ModelDetails,
|
|
39
|
+
type Options,
|
|
40
|
+
type ProgressResponse,
|
|
41
|
+
type ShowResponse
|
|
42
|
+
} from 'ollama';
|
|
43
|
+
import { captureAsyncResult, captureResult, succeed, type Result } from '@fgv/ts-utils';
|
|
44
|
+
import { type JsonObject, type JsonValue, type JsonSchema } from '@fgv/ts-json-base';
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Construction parameters for an Ollama client. All optional; defaults match the `ollama` JS
|
|
48
|
+
* library (host `http://127.0.0.1:11434`).
|
|
49
|
+
* @public
|
|
50
|
+
*/
|
|
51
|
+
export interface ICreateOllamaClientParams {
|
|
52
|
+
/** Server address. Defaults to `http://127.0.0.1:11434`. */
|
|
53
|
+
readonly host?: string;
|
|
54
|
+
/**
|
|
55
|
+
* Custom `fetch` implementation. Injecting a fetch is the primary unit-test seam and the hook
|
|
56
|
+
* for a future proxy / browser path.
|
|
57
|
+
*/
|
|
58
|
+
readonly fetch?: typeof fetch;
|
|
59
|
+
/** Custom headers included on every request (e.g. an auth token for a guarded sidecar). */
|
|
60
|
+
readonly headers?: Record<string, string>;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Opaque client handle. Re-export of the upstream `ollama` `Ollama` instance type — consumers
|
|
65
|
+
* retain full access to the upstream API for anything this boundary does not wrap.
|
|
66
|
+
* @public
|
|
67
|
+
*/
|
|
68
|
+
export type IOllamaClient = Ollama;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Constructs an Ollama client. Synchronous (the constructor performs no I/O), so returns
|
|
72
|
+
* `Result<IOllamaClient>` rather than a promise. A malformed `host` (which the upstream
|
|
73
|
+
* constructor rejects) surfaces as `Result.fail`.
|
|
74
|
+
*
|
|
75
|
+
* @param params - Optional {@link ICreateOllamaClientParams}. Omitted fields fall back to the
|
|
76
|
+
* `ollama` library defaults.
|
|
77
|
+
* @returns `Result<IOllamaClient>` wrapping the upstream `Ollama` instance.
|
|
78
|
+
* @public
|
|
79
|
+
*/
|
|
80
|
+
export function createOllamaClient(params?: ICreateOllamaClientParams): Result<IOllamaClient> {
|
|
81
|
+
// The upstream `Ollama` constructor reads each config field with `?? <default>`, so omitted or
|
|
82
|
+
// `undefined` fields fall back to the library defaults — no per-field guarding needed.
|
|
83
|
+
return captureResult(() => new Ollama(params ?? {}));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ─── Shared normalized model types (§3.2) ───────────────────────────────────────
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* GGUF / model detail block, common to `/api/tags`, `/api/ps`, and `/api/show`. All fields
|
|
90
|
+
* optional — Ollama omits any it cannot determine.
|
|
91
|
+
* @public
|
|
92
|
+
*/
|
|
93
|
+
export interface IOllamaModelDetail {
|
|
94
|
+
/** Storage format, e.g. `'gguf'`. */
|
|
95
|
+
readonly format?: string;
|
|
96
|
+
/** Primary architecture family, e.g. `'llama'`. */
|
|
97
|
+
readonly family?: string;
|
|
98
|
+
/** All architecture families this model belongs to. */
|
|
99
|
+
readonly families?: ReadonlyArray<string>;
|
|
100
|
+
/** Human-readable parameter count, e.g. `'8.0B'`. */
|
|
101
|
+
readonly parameterSize?: string;
|
|
102
|
+
/** Quantization level, e.g. `'Q4_0'`. */
|
|
103
|
+
readonly quantizationLevel?: string;
|
|
104
|
+
/** Parent model for fine-tunes / derived models. */
|
|
105
|
+
readonly parentModel?: string;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Fields common to a locally-stored model and a running model.
|
|
110
|
+
* @public
|
|
111
|
+
*/
|
|
112
|
+
export interface IOllamaModelBase {
|
|
113
|
+
/** Tagged name, e.g. `'llama3.1:8b'`. */
|
|
114
|
+
readonly name: string;
|
|
115
|
+
/** Underlying model id (often equal to `name`). */
|
|
116
|
+
readonly model: string;
|
|
117
|
+
/** On-disk size in bytes. */
|
|
118
|
+
readonly size: number;
|
|
119
|
+
/** SHA-256 manifest digest. */
|
|
120
|
+
readonly digest: string;
|
|
121
|
+
/** GGUF / architecture detail. */
|
|
122
|
+
readonly details: IOllamaModelDetail;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* A model present in the local store (`/api/tags`).
|
|
127
|
+
* @public
|
|
128
|
+
*/
|
|
129
|
+
export interface IOllamaModel extends IOllamaModelBase {
|
|
130
|
+
/** Last-modified timestamp, parsed from the RFC3339 wire value. */
|
|
131
|
+
readonly modifiedAt: Date;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* A model currently loaded into memory (`/api/ps`). Note `/api/ps` does NOT return
|
|
136
|
+
* `modified_at`, so this does not extend {@link IOllamaModel}.
|
|
137
|
+
* @public
|
|
138
|
+
*/
|
|
139
|
+
export interface IOllamaRunningModel extends IOllamaModelBase {
|
|
140
|
+
/** When the model will be unloaded, parsed from the RFC3339 wire value. */
|
|
141
|
+
readonly expiresAt: Date;
|
|
142
|
+
/** Bytes resident in VRAM (0 when fully on CPU). */
|
|
143
|
+
readonly sizeVram: number;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Full model detail, capabilities, parameters, and template (`POST /api/show`).
|
|
148
|
+
* @public
|
|
149
|
+
*/
|
|
150
|
+
export interface IOllamaModelInfo {
|
|
151
|
+
/** The Modelfile source, when returned. */
|
|
152
|
+
readonly modelfile?: string;
|
|
153
|
+
/** Default parameters string. */
|
|
154
|
+
readonly parameters?: string;
|
|
155
|
+
/** The prompt template. */
|
|
156
|
+
readonly template?: string;
|
|
157
|
+
/** GGUF / architecture detail. */
|
|
158
|
+
readonly details: IOllamaModelDetail;
|
|
159
|
+
/** Low-level model metadata key-value map (`model_info`). */
|
|
160
|
+
readonly modelInfo?: Readonly<Record<string, JsonValue>>;
|
|
161
|
+
/** Declared capabilities, e.g. `['completion', 'tools', 'vision', 'thinking']`. */
|
|
162
|
+
readonly capabilities?: ReadonlyArray<string>;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Result of a delete. Returns a meaningful value rather than `Result<void>` (per repo standards —
|
|
167
|
+
* `Result<void>` is an anti-pattern).
|
|
168
|
+
* @public
|
|
169
|
+
*/
|
|
170
|
+
export interface IOllamaDeleteResult {
|
|
171
|
+
/** The model that was deleted. */
|
|
172
|
+
readonly model: string;
|
|
173
|
+
/** Always `true` — a failed delete surfaces as `Result.fail`, never `deleted: false`. */
|
|
174
|
+
readonly deleted: true;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ─── Wire → fgv normalization (§6.3, Appendix) ──────────────────────────────────
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Maps the upstream snake_case `ModelDetails` to the normalized camelCase {@link IOllamaModelDetail}.
|
|
181
|
+
* Upstream types every field as a required `string`, but Ollama omits fields it cannot determine,
|
|
182
|
+
* so individual values may be `undefined` at runtime — the normalized type reflects that by making
|
|
183
|
+
* every field optional.
|
|
184
|
+
*/
|
|
185
|
+
function normalizeModelDetail(d: ModelDetails): IOllamaModelDetail {
|
|
186
|
+
return {
|
|
187
|
+
format: d.format,
|
|
188
|
+
family: d.family,
|
|
189
|
+
families: d.families,
|
|
190
|
+
parameterSize: d.parameter_size,
|
|
191
|
+
quantizationLevel: d.quantization_level,
|
|
192
|
+
parentModel: d.parent_model
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Maps a `/api/tags` `ModelResponse` to {@link IOllamaModel}. `modified_at` is normalized to a
|
|
198
|
+
* `Date` via the `Date` constructor, which accepts both the RFC3339 string the wire actually
|
|
199
|
+
* delivers and the `Date` the upstream type (inaccurately) claims.
|
|
200
|
+
*/
|
|
201
|
+
function normalizeModel(m: ModelResponse): IOllamaModel {
|
|
202
|
+
return {
|
|
203
|
+
name: m.name,
|
|
204
|
+
model: m.model,
|
|
205
|
+
size: m.size,
|
|
206
|
+
digest: m.digest,
|
|
207
|
+
details: normalizeModelDetail(m.details),
|
|
208
|
+
modifiedAt: new Date(m.modified_at)
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Maps a `/api/ps` `ModelResponse` to {@link IOllamaRunningModel}. `/api/ps` returns `expires_at`
|
|
214
|
+
* and `size_vram` in place of `modified_at`.
|
|
215
|
+
*/
|
|
216
|
+
function normalizeRunningModel(m: ModelResponse): IOllamaRunningModel {
|
|
217
|
+
return {
|
|
218
|
+
name: m.name,
|
|
219
|
+
model: m.model,
|
|
220
|
+
size: m.size,
|
|
221
|
+
digest: m.digest,
|
|
222
|
+
details: normalizeModelDetail(m.details),
|
|
223
|
+
expiresAt: new Date(m.expires_at),
|
|
224
|
+
sizeVram: m.size_vram
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Normalizes the `model_info` metadata bag. The upstream type annotates it as `Map<string, any>`,
|
|
230
|
+
* but the lib returns `response.json()` verbatim, so the wire delivers a plain JSON object (or
|
|
231
|
+
* omits the field). The single `as unknown as` bridge reconciles the inaccurate upstream annotation
|
|
232
|
+
* with the actual JSON shape — there is no untyped input to validate here.
|
|
233
|
+
*/
|
|
234
|
+
function normalizeModelInfo(
|
|
235
|
+
raw: ShowResponse['model_info']
|
|
236
|
+
): Readonly<Record<string, JsonValue>> | undefined {
|
|
237
|
+
if (raw === undefined) {
|
|
238
|
+
return undefined;
|
|
239
|
+
}
|
|
240
|
+
return raw as unknown as Readonly<Record<string, JsonValue>>;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Maps a `/api/show` `ShowResponse` to {@link IOllamaModelInfo}. The remaining `ShowResponse`
|
|
245
|
+
* fields (`license`, `system`, `messages`, `modified_at`, `projector_info`) are intentionally not
|
|
246
|
+
* carried through — they are out of scope for the v0.1 surface.
|
|
247
|
+
*/
|
|
248
|
+
function normalizeShowResponse(r: ShowResponse): IOllamaModelInfo {
|
|
249
|
+
return {
|
|
250
|
+
modelfile: r.modelfile,
|
|
251
|
+
parameters: r.parameters,
|
|
252
|
+
template: r.template,
|
|
253
|
+
details: normalizeModelDetail(r.details),
|
|
254
|
+
modelInfo: normalizeModelInfo(r.model_info),
|
|
255
|
+
capabilities: r.capabilities
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// ─── Model management primitives (§3.3) ─────────────────────────────────────────
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Lists models in the local store (`GET /api/tags`). Each entry is normalized to
|
|
263
|
+
* {@link IOllamaModel} (camelCase, `modifiedAt` as a `Date`).
|
|
264
|
+
*
|
|
265
|
+
* @param client - A client from {@link createOllamaClient}.
|
|
266
|
+
* @returns `Promise<Result<ReadonlyArray<IOllamaModel>>>`; upstream / transport errors are captured
|
|
267
|
+
* as `Failure`.
|
|
268
|
+
* @public
|
|
269
|
+
*/
|
|
270
|
+
export async function listModels(client: IOllamaClient): Promise<Result<ReadonlyArray<IOllamaModel>>> {
|
|
271
|
+
return captureAsyncResult(async () => {
|
|
272
|
+
const response: ListResponse = await client.list();
|
|
273
|
+
return response.models.map(normalizeModel);
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Lists models currently loaded into memory (`GET /api/ps`). Each entry is normalized to
|
|
279
|
+
* {@link IOllamaRunningModel} (camelCase, `expiresAt` as a `Date`, `sizeVram` in bytes).
|
|
280
|
+
*
|
|
281
|
+
* @param client - A client from {@link createOllamaClient}.
|
|
282
|
+
* @returns `Promise<Result<ReadonlyArray<IOllamaRunningModel>>>`; upstream / transport errors are
|
|
283
|
+
* captured as `Failure`.
|
|
284
|
+
* @public
|
|
285
|
+
*/
|
|
286
|
+
export async function listRunning(
|
|
287
|
+
client: IOllamaClient
|
|
288
|
+
): Promise<Result<ReadonlyArray<IOllamaRunningModel>>> {
|
|
289
|
+
return captureAsyncResult(async () => {
|
|
290
|
+
const response: ListResponse = await client.ps();
|
|
291
|
+
return response.models.map(normalizeRunningModel);
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Full model detail, capabilities, parameters, and template (`POST /api/show`), normalized to
|
|
297
|
+
* {@link IOllamaModelInfo}.
|
|
298
|
+
*
|
|
299
|
+
* @param client - A client from {@link createOllamaClient}.
|
|
300
|
+
* @param model - The model name to inspect, e.g. `'llama3.1:8b'`.
|
|
301
|
+
* @param options - Optional flags. `verbose: true` requests the full low-level `model_info` block.
|
|
302
|
+
* @returns `Promise<Result<IOllamaModelInfo>>`; upstream / transport errors (e.g. unknown model)
|
|
303
|
+
* are captured as `Failure`.
|
|
304
|
+
* @public
|
|
305
|
+
*/
|
|
306
|
+
export async function showModel(
|
|
307
|
+
client: IOllamaClient,
|
|
308
|
+
model: string,
|
|
309
|
+
options?: { readonly verbose?: boolean }
|
|
310
|
+
): Promise<Result<IOllamaModelInfo>> {
|
|
311
|
+
return captureAsyncResult(async () => {
|
|
312
|
+
// `verbose` is a valid `/api/show` body field that the lib forwards verbatim, but the upstream
|
|
313
|
+
// `ShowRequest` type omits it; building it as a non-literal object passes it through without a
|
|
314
|
+
// cast (and omits the key entirely when no flag was supplied).
|
|
315
|
+
const request = { model, ...(options?.verbose !== undefined && { verbose: options.verbose }) };
|
|
316
|
+
const response: ShowResponse = await client.show(request);
|
|
317
|
+
return normalizeShowResponse(response);
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Deletes a model from the local store (`DELETE /api/delete`). Returns a meaningful
|
|
323
|
+
* {@link IOllamaDeleteResult} rather than `Result<void>`.
|
|
324
|
+
*
|
|
325
|
+
* @param client - A client from {@link createOllamaClient}.
|
|
326
|
+
* @param model - The model name to delete.
|
|
327
|
+
* @returns `Promise<Result<IOllamaDeleteResult>>`; a missing model or transport error surfaces as
|
|
328
|
+
* `Failure`.
|
|
329
|
+
* @public
|
|
330
|
+
*/
|
|
331
|
+
export async function deleteModel(
|
|
332
|
+
client: IOllamaClient,
|
|
333
|
+
model: string
|
|
334
|
+
): Promise<Result<IOllamaDeleteResult>> {
|
|
335
|
+
return captureAsyncResult(async () => {
|
|
336
|
+
await client.delete({ model });
|
|
337
|
+
return { model, deleted: true };
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// ─── Pull with streamed progress (§3.4, §5) ─────────────────────────────────────
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* A single progress chunk from a streamed pull (`/api/pull`). Ollama emits a JSON-lines stream;
|
|
345
|
+
* each line is one of these. Fields map 1:1 from the upstream `ProgressResponse`; the layer fields
|
|
346
|
+
* (`digest`/`total`/`completed`) are `undefined` on the manifest / verify / write phases.
|
|
347
|
+
* @public
|
|
348
|
+
*/
|
|
349
|
+
export interface IOllamaPullProgress {
|
|
350
|
+
/**
|
|
351
|
+
* Phase string, e.g. `'pulling manifest'`, `'pulling <digest>'`, `'verifying sha256 digest'`,
|
|
352
|
+
* `'writing manifest'`, `'success'`.
|
|
353
|
+
*/
|
|
354
|
+
readonly status: string;
|
|
355
|
+
/** Layer digest being transferred (present during `'pulling <digest>'` phases). */
|
|
356
|
+
readonly digest?: string;
|
|
357
|
+
/** Total bytes for the current layer, when known. */
|
|
358
|
+
readonly total?: number;
|
|
359
|
+
/** Bytes transferred so far for the current layer, when known. */
|
|
360
|
+
readonly completed?: number;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Terminal result of a completed pull. Returns a meaningful value (not `Result<void>`): the final
|
|
365
|
+
* status plus a count of progress chunks observed.
|
|
366
|
+
* @public
|
|
367
|
+
*/
|
|
368
|
+
export interface IOllamaPullResult {
|
|
369
|
+
/** The model that was pulled. */
|
|
370
|
+
readonly model: string;
|
|
371
|
+
/** The `status` of the final chunk, normally `'success'`. */
|
|
372
|
+
readonly finalStatus: string;
|
|
373
|
+
/** Number of progress chunks observed (useful for tests and diagnostics). */
|
|
374
|
+
readonly chunkCount: number;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Parameters for {@link pullModel}.
|
|
379
|
+
* @public
|
|
380
|
+
*/
|
|
381
|
+
export interface IPullModelParams {
|
|
382
|
+
/** Model to pull, e.g. `'llama3.1:8b'`. */
|
|
383
|
+
readonly model: string;
|
|
384
|
+
/** Allow pulling from insecure (non-TLS) registries. */
|
|
385
|
+
readonly insecure?: boolean;
|
|
386
|
+
/**
|
|
387
|
+
* Progress callback, invoked once per JSON-lines chunk as it arrives. The `Result` returned by
|
|
388
|
+
* {@link pullModel} resolves only after the stream terminates; progress is surfaced here in the
|
|
389
|
+
* interim. A throw from this callback fails the whole pull (it runs inside the captured loop).
|
|
390
|
+
*/
|
|
391
|
+
readonly onProgress?: (progress: IOllamaPullProgress) => void;
|
|
392
|
+
/**
|
|
393
|
+
* Abort signal. Cancels the in-flight pull; the upstream stream throws an `AbortError`, which
|
|
394
|
+
* surfaces as `Result.fail`. An already-aborted signal cancels immediately.
|
|
395
|
+
*/
|
|
396
|
+
readonly signal?: AbortSignal;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Maps an upstream `ProgressResponse` chunk to {@link IOllamaPullProgress}. The upstream type marks
|
|
401
|
+
* every field required, but the layer fields are omitted (and thus `undefined` at runtime) on the
|
|
402
|
+
* non-transfer phases — a direct structural copy preserves that, matching the optional fields.
|
|
403
|
+
*/
|
|
404
|
+
function normalizePullProgress(c: ProgressResponse): IOllamaPullProgress {
|
|
405
|
+
return {
|
|
406
|
+
status: c.status,
|
|
407
|
+
digest: c.digest,
|
|
408
|
+
total: c.total,
|
|
409
|
+
completed: c.completed
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Pulls a model with streamed progress (`POST /api/pull`). Drives the upstream JSON-lines stream
|
|
415
|
+
* internally, invoking `params.onProgress` once per chunk, and resolves the `Result` once the
|
|
416
|
+
* stream terminates. Any upstream error — connection drop, registry 404, abort, or a throwing
|
|
417
|
+
* `onProgress` — becomes a single `Failure`; success returns a meaningful {@link IOllamaPullResult}
|
|
418
|
+
* rather than `Result<void>`.
|
|
419
|
+
*
|
|
420
|
+
* @param client - A client from {@link createOllamaClient}.
|
|
421
|
+
* @param params - {@link IPullModelParams} — the model, optional `insecure` flag, optional
|
|
422
|
+
* `onProgress` callback, and optional `AbortSignal`.
|
|
423
|
+
* @returns `Promise<Result<IOllamaPullResult>>`.
|
|
424
|
+
* @public
|
|
425
|
+
*/
|
|
426
|
+
export async function pullModel(
|
|
427
|
+
client: IOllamaClient,
|
|
428
|
+
params: IPullModelParams
|
|
429
|
+
): Promise<Result<IOllamaPullResult>> {
|
|
430
|
+
return captureAsyncResult(async () => {
|
|
431
|
+
const request = {
|
|
432
|
+
model: params.model,
|
|
433
|
+
stream: true as const,
|
|
434
|
+
...(params.insecure !== undefined && { insecure: params.insecure })
|
|
435
|
+
};
|
|
436
|
+
const iterator = await client.pull(request);
|
|
437
|
+
|
|
438
|
+
// Wire the abort signal to the upstream iterator's abort path. An already-aborted signal
|
|
439
|
+
// cancels immediately; otherwise abort on first fire (and clean the listener up in `finally`).
|
|
440
|
+
const abortListener = (): void => iterator.abort();
|
|
441
|
+
if (params.signal !== undefined) {
|
|
442
|
+
if (params.signal.aborted) {
|
|
443
|
+
iterator.abort();
|
|
444
|
+
} else {
|
|
445
|
+
params.signal.addEventListener('abort', abortListener, { once: true });
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
let chunkCount = 0;
|
|
450
|
+
let finalStatus = '';
|
|
451
|
+
try {
|
|
452
|
+
for await (const chunk of iterator) {
|
|
453
|
+
params.onProgress?.(normalizePullProgress(chunk));
|
|
454
|
+
chunkCount += 1;
|
|
455
|
+
finalStatus = chunk.status;
|
|
456
|
+
}
|
|
457
|
+
} finally {
|
|
458
|
+
params.signal?.removeEventListener('abort', abortListener);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
return { model: params.model, finalStatus, chunkCount };
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// ─── Grammar-constrained structured output (§3.5, §4) ───────────────────────────
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* A chat message in Ollama native shape.
|
|
469
|
+
* @public
|
|
470
|
+
*/
|
|
471
|
+
export interface IOllamaChatMessage {
|
|
472
|
+
/** The message role. */
|
|
473
|
+
readonly role: 'system' | 'user' | 'assistant' | 'tool';
|
|
474
|
+
/** The message text. */
|
|
475
|
+
readonly content: string;
|
|
476
|
+
/** Base64 image data for vision models (no `data:` prefix). */
|
|
477
|
+
readonly images?: ReadonlyArray<string>;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Result of a grammar-constrained structured chat. Carries both the validated typed value and the
|
|
482
|
+
* raw JSON text the model emitted, for diagnostics.
|
|
483
|
+
* @public
|
|
484
|
+
*/
|
|
485
|
+
export interface IOllamaChatStructuredResult<T> {
|
|
486
|
+
/** The parsed-and-validated value (validated by the same schema sent on the wire). */
|
|
487
|
+
readonly value: T;
|
|
488
|
+
/** The raw `message.content` JSON string the model emitted (assembled across stream chunks). */
|
|
489
|
+
readonly raw: string;
|
|
490
|
+
/** The model that produced the response. */
|
|
491
|
+
readonly model: string;
|
|
492
|
+
/** Provider-reported finish reason, when present. */
|
|
493
|
+
readonly doneReason?: string;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Parameters for {@link chatStructured}.
|
|
498
|
+
* @public
|
|
499
|
+
*/
|
|
500
|
+
export interface IChatStructuredParams<T> {
|
|
501
|
+
/** The model to chat with, e.g. `'llama3.1:8b'`. */
|
|
502
|
+
readonly model: string;
|
|
503
|
+
/** The conversation so far. */
|
|
504
|
+
readonly messages: ReadonlyArray<IOllamaChatMessage>;
|
|
505
|
+
/**
|
|
506
|
+
* The single source of truth for both the wire schema (`schema.toJson()`, sent as the native
|
|
507
|
+
* `format` field) and the result validator (`schema.validate()`). Author with
|
|
508
|
+
* `JsonSchema.object(...)` from `@fgv/ts-json-base`; `T` is derived via
|
|
509
|
+
* `JsonSchema.Static<typeof schema>`. A runtime-discovered (MCP) schema parsed via
|
|
510
|
+
* `JsonSchema.fromJson(raw)` also works — its `T` is `JsonValue`.
|
|
511
|
+
*/
|
|
512
|
+
readonly schema: JsonSchema.ISchemaValidator<T>;
|
|
513
|
+
/** Native Ollama `options` (temperature, num_ctx, seed, …). Passed verbatim. */
|
|
514
|
+
readonly options?: Readonly<Record<string, JsonValue>>;
|
|
515
|
+
/** Native `keep_alive` (duration string or seconds). Passed verbatim — no policy applied. */
|
|
516
|
+
readonly keepAlive?: string | number;
|
|
517
|
+
/**
|
|
518
|
+
* Abort signal. Cancels the in-flight generation; the upstream stream throws an `AbortError`,
|
|
519
|
+
* which surfaces as `Result.fail`. An already-aborted signal cancels immediately.
|
|
520
|
+
*/
|
|
521
|
+
readonly signal?: AbortSignal;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Recursively removes the JSON-Schema keywords (`$schema`, `additionalProperties`) — *if present*
|
|
526
|
+
* — that Ollama's `format` does not need. `JsonSchema.object(...).toJson()` emits
|
|
527
|
+
* `additionalProperties: false` on object nodes; `$schema` is not added by default but may appear
|
|
528
|
+
* on a runtime-discovered schema (`JsonSchema.fromJson(raw)`). Mirrors the ai-assist Gemini
|
|
529
|
+
* precedent (`toGeminiParameterSchema`): the keywords are removed only where they appear as schema
|
|
530
|
+
* *keywords* (siblings of `type`/`properties`/…). Inside a `properties` map the keys are
|
|
531
|
+
* user-defined property names, not keywords, so they are preserved verbatim while each property's
|
|
532
|
+
* subschema value is still recursively sanitized. Stripping is infallible, so it returns a plain
|
|
533
|
+
* value rather than a `Result`.
|
|
534
|
+
*/
|
|
535
|
+
function sanitizeFormatSchema(schema: JsonValue): JsonValue {
|
|
536
|
+
if (Array.isArray(schema)) {
|
|
537
|
+
return schema.map(sanitizeFormatSchema);
|
|
538
|
+
}
|
|
539
|
+
if (schema !== null && typeof schema === 'object') {
|
|
540
|
+
const out: JsonObject = {};
|
|
541
|
+
for (const [key, value] of Object.entries(schema)) {
|
|
542
|
+
if (key === '$schema' || key === 'additionalProperties') {
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
if (key === 'properties' && value !== null && typeof value === 'object' && !Array.isArray(value)) {
|
|
546
|
+
const properties: JsonObject = {};
|
|
547
|
+
for (const [name, propSchema] of Object.entries(value)) {
|
|
548
|
+
properties[name] = sanitizeFormatSchema(propSchema);
|
|
549
|
+
}
|
|
550
|
+
out[key] = properties;
|
|
551
|
+
} else {
|
|
552
|
+
out[key] = sanitizeFormatSchema(value);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
return out;
|
|
556
|
+
}
|
|
557
|
+
return schema;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* Maps an {@link IOllamaChatMessage} to the upstream `Message` wire shape, copying the optional
|
|
562
|
+
* base64 `images` array only when present.
|
|
563
|
+
*/
|
|
564
|
+
function toWireMessage(message: IOllamaChatMessage): Message {
|
|
565
|
+
return {
|
|
566
|
+
role: message.role,
|
|
567
|
+
content: message.content,
|
|
568
|
+
...(message.images !== undefined && { images: [...message.images] })
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Single-turn grammar-constrained structured chat (`POST /api/chat` with `format` = full JSON
|
|
574
|
+
* schema). The fidelity win over ai-assist's prompt-and-parse path is **grammar-constrained
|
|
575
|
+
* sampling**: Ollama restricts the token sampler to the supplied schema, so the response is
|
|
576
|
+
* structurally guaranteed to match.
|
|
577
|
+
*
|
|
578
|
+
* The schema is the single source of truth: `schema.toJson()` (draft-07-sanitized) is sent as the
|
|
579
|
+
* wire `format`, and the same `schema.validate()` checks the reply — they cannot drift. `T` flows
|
|
580
|
+
* end-to-end from `JsonSchema.Static<typeof schema>`; no caller-supplied `T`, no cast.
|
|
581
|
+
*
|
|
582
|
+
* Runs over the streaming chat path internally, assembling the full document from the stream
|
|
583
|
+
* chunks and validating it whole — partial JSON has no validation value. (The design §4 sketch
|
|
584
|
+
* said `stream: false`, but the locked OQ-3 amendment requires an `AbortSignal`, and the `ollama`
|
|
585
|
+
* lib only threads a signal on the streaming path — its non-streaming request has no signal
|
|
586
|
+
* plumbing. The streaming `AbortableAsyncIterator.abort()` is "the mechanism that already exists
|
|
587
|
+
* for `pullModel`".) Any upstream error, abort, parse failure, or validation failure surfaces as a
|
|
588
|
+
* single `Failure` with context.
|
|
589
|
+
*
|
|
590
|
+
* @param client - A client from {@link createOllamaClient}.
|
|
591
|
+
* @param params - {@link IChatStructuredParams} — model, messages, the `JsonSchema` schema, and
|
|
592
|
+
* optional `options` / `keepAlive` / `signal`.
|
|
593
|
+
* @returns `Promise<Result<IOllamaChatStructuredResult<T>>>`.
|
|
594
|
+
* @public
|
|
595
|
+
*/
|
|
596
|
+
export async function chatStructured<T>(
|
|
597
|
+
client: IOllamaClient,
|
|
598
|
+
params: IChatStructuredParams<T>
|
|
599
|
+
): Promise<Result<IOllamaChatStructuredResult<T>>> {
|
|
600
|
+
const accumulated = await captureAsyncResult(async () => {
|
|
601
|
+
const wireFormat = sanitizeFormatSchema(params.schema.toJson());
|
|
602
|
+
const request: ChatRequest & { stream: true } = {
|
|
603
|
+
model: params.model,
|
|
604
|
+
messages: params.messages.map(toWireMessage),
|
|
605
|
+
// The wire schema accepts a plain object; the lib types `format` as `string | object`.
|
|
606
|
+
format: wireFormat as object,
|
|
607
|
+
stream: true,
|
|
608
|
+
// The lib types `options` narrowly as `Partial<Options>`, but the native API accepts an
|
|
609
|
+
// arbitrary option bag forwarded verbatim — bridge the (overly narrow) upstream type.
|
|
610
|
+
...(params.options !== undefined && { options: params.options as unknown as Partial<Options> }),
|
|
611
|
+
...(params.keepAlive !== undefined && { keep_alive: params.keepAlive })
|
|
612
|
+
};
|
|
613
|
+
const iterator = await client.chat(request);
|
|
614
|
+
|
|
615
|
+
const abortListener = (): void => iterator.abort();
|
|
616
|
+
if (params.signal !== undefined) {
|
|
617
|
+
if (params.signal.aborted) {
|
|
618
|
+
iterator.abort();
|
|
619
|
+
} else {
|
|
620
|
+
params.signal.addEventListener('abort', abortListener, { once: true });
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
let raw = '';
|
|
625
|
+
let model = params.model;
|
|
626
|
+
let doneReason: string | undefined;
|
|
627
|
+
try {
|
|
628
|
+
for await (const chunk of iterator) {
|
|
629
|
+
raw += chunk.message.content;
|
|
630
|
+
model = chunk.model;
|
|
631
|
+
if (chunk.done) {
|
|
632
|
+
doneReason = chunk.done_reason;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
} finally {
|
|
636
|
+
params.signal?.removeEventListener('abort', abortListener);
|
|
637
|
+
}
|
|
638
|
+
return { raw, model, doneReason };
|
|
639
|
+
});
|
|
640
|
+
|
|
641
|
+
return accumulated.onSuccess(({ raw, model, doneReason }) =>
|
|
642
|
+
captureResult(() => JSON.parse(raw) as unknown)
|
|
643
|
+
.withErrorFormat(
|
|
644
|
+
(message) => `chatStructured(${params.model}): response was not valid JSON: ${message}`
|
|
645
|
+
)
|
|
646
|
+
.onSuccess((parsed) =>
|
|
647
|
+
params.schema
|
|
648
|
+
.validate(parsed)
|
|
649
|
+
.withErrorFormat(
|
|
650
|
+
(message) => `chatStructured(${params.model}): response failed schema validation: ${message}`
|
|
651
|
+
)
|
|
652
|
+
.onSuccess((value) => succeed({ value, raw, model, doneReason }))
|
|
653
|
+
)
|
|
654
|
+
);
|
|
655
|
+
}
|