@orkestrel/ollama 0.0.14 → 0.0.16
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/README.md +32 -14
- package/dist/src/core/index.cjs +362 -0
- package/dist/src/core/index.cjs.map +1 -0
- package/dist/src/core/index.d.cts +351 -0
- package/dist/src/core/index.d.ts +351 -0
- package/dist/src/core/index.js +351 -0
- package/dist/src/core/index.js.map +1 -0
- package/package.json +35 -36
- package/dist/src/server/index.cjs +0 -629
- package/dist/src/server/index.cjs.map +0 -1
- package/dist/src/server/index.d.cts +0 -542
- package/dist/src/server/index.d.ts +0 -542
- package/dist/src/server/index.js +0 -612
- package/dist/src/server/index.js.map +0 -1
package/dist/src/server/index.js
DELETED
|
@@ -1,612 +0,0 @@
|
|
|
1
|
-
import { isNumber, isRecord, isString, parseJSONAs } from "@orkestrel/contract";
|
|
2
|
-
import { ProviderAbortError, createThinkSplitter } from "@orkestrel/agent";
|
|
3
|
-
import { createNDJSONParser } from "@orkestrel/ndjson";
|
|
4
|
-
import { Timeout } from "@orkestrel/timeout";
|
|
5
|
-
//#region src/server/constants.ts
|
|
6
|
-
/** Names the local Ollama daemon base URL assumed when `OllamaOptions.url` is omitted. */
|
|
7
|
-
var DEFAULT_OLLAMA_URL = "http://localhost:11434";
|
|
8
|
-
/**
|
|
9
|
-
* Names how long the model stays resident after a call when `OllamaOptions.keepAlive` is
|
|
10
|
-
* omitted — Ollama's own `keep_alive` default, expressed as a duration string.
|
|
11
|
-
*
|
|
12
|
-
* @remarks
|
|
13
|
-
* The name mirrors the Ollama `/api/chat` `keep_alive` field this value is sent as, so
|
|
14
|
-
* the constant, the `OllamaOptions.keepAlive` key, and the wire member read as one term.
|
|
15
|
-
*/
|
|
16
|
-
var DEFAULT_KEEP_ALIVE = "5m";
|
|
17
|
-
/**
|
|
18
|
-
* Names the per-call deadline in milliseconds when `OllamaOptions.timeout` is omitted —
|
|
19
|
-
* generous enough that a cold model load does not trip it.
|
|
20
|
-
*/
|
|
21
|
-
var DEFAULT_PROVIDER_TIMEOUT = 12e4;
|
|
22
|
-
/**
|
|
23
|
-
* Names the cap, in characters, on how much of a non-OK response body is
|
|
24
|
-
* incorporated into a thrown {@link OllamaHTTPError}'s message.
|
|
25
|
-
*
|
|
26
|
-
* @remarks
|
|
27
|
-
* Bounds the excerpt so a defensive proxy or a misbehaving daemon handing
|
|
28
|
-
* back an unbounded response body cannot inflate the thrown error's message
|
|
29
|
-
* without limit. `2048` characters is generous enough to carry a
|
|
30
|
-
* useful diagnostic snippet while staying well short of any practical size
|
|
31
|
-
* concern.
|
|
32
|
-
*/
|
|
33
|
-
var MAX_ERROR_BODY_LENGTH = 2048;
|
|
34
|
-
//#endregion
|
|
35
|
-
//#region src/server/errors.ts
|
|
36
|
-
/**
|
|
37
|
-
* Represents an error thrown when the Ollama `/api/chat` HTTP transport fails.
|
|
38
|
-
*
|
|
39
|
-
* @remarks
|
|
40
|
-
* Carries the machine-readable `code` `'HTTP'` and the response `status` (0 when no
|
|
41
|
-
* HTTP response was received at all, for example a `null` body). Thrown by
|
|
42
|
-
* {@link OllamaProvider} at its HTTP failure sites — the non-OK status branch and the
|
|
43
|
-
* null-body branch — so a caller can branch on `error.code` and read `error.status`
|
|
44
|
-
* for the HTTP number instead of parsing the message. Narrow a caught value with
|
|
45
|
-
* {@link isOllamaHTTPError}.
|
|
46
|
-
*
|
|
47
|
-
* @example
|
|
48
|
-
* ```ts
|
|
49
|
-
* try {
|
|
50
|
-
* await provider.generate(messages, signal)
|
|
51
|
-
* } catch (error) {
|
|
52
|
-
* if (isOllamaHTTPError(error) && error.status === 404) {
|
|
53
|
-
* // the configured model isn't pulled
|
|
54
|
-
* }
|
|
55
|
-
* }
|
|
56
|
-
* ```
|
|
57
|
-
*/
|
|
58
|
-
var OllamaHTTPError = class extends Error {
|
|
59
|
-
/**
|
|
60
|
-
* Names the machine-readable condition this error reports — `'HTTP'`: an `/api/chat`
|
|
61
|
-
* transport, status, or body failure.
|
|
62
|
-
*/
|
|
63
|
-
code = "HTTP";
|
|
64
|
-
status;
|
|
65
|
-
constructor(message, status, options) {
|
|
66
|
-
super(message, options);
|
|
67
|
-
this.name = "OllamaHTTPError";
|
|
68
|
-
this.status = status;
|
|
69
|
-
}
|
|
70
|
-
};
|
|
71
|
-
/**
|
|
72
|
-
* Checks whether a value is an {@link OllamaHTTPError}.
|
|
73
|
-
*
|
|
74
|
-
* @param value - The value to test
|
|
75
|
-
* @returns True if `value` is an `OllamaHTTPError`; false otherwise
|
|
76
|
-
*/
|
|
77
|
-
function isOllamaHTTPError(value) {
|
|
78
|
-
return value instanceof OllamaHTTPError;
|
|
79
|
-
}
|
|
80
|
-
//#endregion
|
|
81
|
-
//#region src/server/helpers.ts
|
|
82
|
-
/**
|
|
83
|
-
* Maps conversation turns onto the `/api/chat` wire's minimal message shape.
|
|
84
|
-
*
|
|
85
|
-
* @remarks
|
|
86
|
-
* `tool_calls` is emitted only on a turn that replays them and `images` only on a
|
|
87
|
-
* multimodal turn, so an empty optional never reaches the wire.
|
|
88
|
-
*
|
|
89
|
-
* @param messages - The conversation turns to send
|
|
90
|
-
* @returns The wire `messages` array, one entry per turn, in order
|
|
91
|
-
*
|
|
92
|
-
* @example
|
|
93
|
-
* ```ts
|
|
94
|
-
* mapMessages([{ id: '1', role: 'user', content: 'Say hello.' }])
|
|
95
|
-
* // [{ role: 'user', content: 'Say hello.' }]
|
|
96
|
-
* ```
|
|
97
|
-
*/
|
|
98
|
-
function mapMessages(messages) {
|
|
99
|
-
return messages.map((message) => ({
|
|
100
|
-
role: message.role,
|
|
101
|
-
content: message.content,
|
|
102
|
-
...message.calls !== void 0 && message.calls.length > 0 ? { tool_calls: message.calls.map((call) => ({ function: {
|
|
103
|
-
name: call.name,
|
|
104
|
-
arguments: call.arguments
|
|
105
|
-
} })) } : {},
|
|
106
|
-
...message.images !== void 0 && message.images.length > 0 ? { images: [...message.images] } : {}
|
|
107
|
-
}));
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
|
-
* Builds a provider result from a turn's content, reasoning, tool calls, and usage.
|
|
111
|
-
*
|
|
112
|
-
* @remarks
|
|
113
|
-
* Only the present optionals are set: no empty `thinking`, no empty `tools`, and no
|
|
114
|
-
* `usage` unless the wire reported one.
|
|
115
|
-
*
|
|
116
|
-
* @param content - The clean assistant content the splitter accumulated
|
|
117
|
-
* @param thinking - The joined reasoning, empty when the turn produced none
|
|
118
|
-
* @param tools - The tool calls collected across the turn
|
|
119
|
-
* @param usage - The token usage, or `undefined` when the wire reported none
|
|
120
|
-
* @returns The result carrying only its populated fields
|
|
121
|
-
*
|
|
122
|
-
* @example
|
|
123
|
-
* ```ts
|
|
124
|
-
* buildResult('ok', '', [], undefined) // { content: 'ok' }
|
|
125
|
-
* ```
|
|
126
|
-
*/
|
|
127
|
-
function buildResult(content, thinking, tools, usage) {
|
|
128
|
-
const result = { content };
|
|
129
|
-
if (thinking.length > 0) result.thinking = thinking;
|
|
130
|
-
if (tools.length > 0) result.tools = tools;
|
|
131
|
-
if (usage !== void 0) result.usage = usage;
|
|
132
|
-
return result;
|
|
133
|
-
}
|
|
134
|
-
/**
|
|
135
|
-
* Extracts the assistant text of one wire record.
|
|
136
|
-
*
|
|
137
|
-
* @param record - One parsed `/api/chat` record — a non-stream body or an NDJSON line
|
|
138
|
-
* @returns The record's `message.content` when it is a string, else `''`
|
|
139
|
-
*
|
|
140
|
-
* @example
|
|
141
|
-
* ```ts
|
|
142
|
-
* extractContent({ message: { content: 'ok' } }) // 'ok'
|
|
143
|
-
* ```
|
|
144
|
-
*/
|
|
145
|
-
function extractContent(record) {
|
|
146
|
-
const message = Reflect.get(record, "message");
|
|
147
|
-
if (!isRecord(message)) return "";
|
|
148
|
-
const content = Reflect.get(message, "content");
|
|
149
|
-
return isString(content) ? content : "";
|
|
150
|
-
}
|
|
151
|
-
/**
|
|
152
|
-
* Extracts the daemon-side reasoning of one wire record.
|
|
153
|
-
*
|
|
154
|
-
* @remarks
|
|
155
|
-
* `message.thinking` is the `think: true` wire shape. It is read whatever the configured
|
|
156
|
-
* flag says, because a daemon may separate reasoning on its own.
|
|
157
|
-
*
|
|
158
|
-
* @param record - One parsed `/api/chat` record — a non-stream body or an NDJSON line
|
|
159
|
-
* @returns The record's `message.thinking` when it is a string, else `''`
|
|
160
|
-
*
|
|
161
|
-
* @example
|
|
162
|
-
* ```ts
|
|
163
|
-
* extractThinking({ message: { thinking: 'weighing it' } }) // 'weighing it'
|
|
164
|
-
* ```
|
|
165
|
-
*/
|
|
166
|
-
function extractThinking(record) {
|
|
167
|
-
const message = Reflect.get(record, "message");
|
|
168
|
-
if (!isRecord(message)) return "";
|
|
169
|
-
const thinking = Reflect.get(message, "thinking");
|
|
170
|
-
return isString(thinking) ? thinking : "";
|
|
171
|
-
}
|
|
172
|
-
/**
|
|
173
|
-
* Joins a call's two reasoning carriers into the result's `thinking`.
|
|
174
|
-
*
|
|
175
|
-
* @param splitter - The per-call splitter holding the separated in-content spans
|
|
176
|
-
* @param wired - The accumulated wire-side `message.thinking` text
|
|
177
|
-
* @returns The two carriers separated by a blank line, or whichever one is non-empty
|
|
178
|
-
*
|
|
179
|
-
* @example
|
|
180
|
-
* ```ts
|
|
181
|
-
* joinThinking(createThinkSplitter(), 'from the wire') // 'from the wire'
|
|
182
|
-
* ```
|
|
183
|
-
*/
|
|
184
|
-
function joinThinking(splitter, wired) {
|
|
185
|
-
if (splitter.thinking.length === 0) return wired;
|
|
186
|
-
if (wired.length === 0) return splitter.thinking;
|
|
187
|
-
return `${splitter.thinking}\n\n${wired}`;
|
|
188
|
-
}
|
|
189
|
-
/**
|
|
190
|
-
* Extracts the token usage of one wire record.
|
|
191
|
-
*
|
|
192
|
-
* @remarks
|
|
193
|
-
* Both counts must be numbers, which is true of the non-stream body and the stream's
|
|
194
|
-
* `done: true` line. A delta line carries neither, so it yields `undefined`.
|
|
195
|
-
*
|
|
196
|
-
* @param record - One parsed `/api/chat` record — a non-stream body or an NDJSON line
|
|
197
|
-
* @returns The `TokenUsage` shape, or `undefined` when either count is absent
|
|
198
|
-
*
|
|
199
|
-
* @example
|
|
200
|
-
* ```ts
|
|
201
|
-
* extractUsage({ prompt_eval_count: 3, eval_count: 4 })
|
|
202
|
-
* // { prompt: 3, completion: 4, total: 7 }
|
|
203
|
-
* ```
|
|
204
|
-
*/
|
|
205
|
-
function extractUsage(record) {
|
|
206
|
-
const prompt = Reflect.get(record, "prompt_eval_count");
|
|
207
|
-
const completion = Reflect.get(record, "eval_count");
|
|
208
|
-
if (!isNumber(prompt) || !isNumber(completion)) return void 0;
|
|
209
|
-
return {
|
|
210
|
-
prompt,
|
|
211
|
-
completion,
|
|
212
|
-
total: prompt + completion
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
/**
|
|
216
|
-
* Extracts the tool calls of one wire record's `message.tool_calls`.
|
|
217
|
-
*
|
|
218
|
-
* @remarks
|
|
219
|
-
* Each entry narrows to `{ id, name, arguments }`: the entry and its `function` must be
|
|
220
|
-
* records and `name` a string, else the entry is dropped. An id is minted when the wire
|
|
221
|
-
* omits one.
|
|
222
|
-
*
|
|
223
|
-
* @param record - One parsed `/api/chat` record — a non-stream body or an NDJSON line
|
|
224
|
-
* @returns The narrowed tool calls, empty when the record carries none
|
|
225
|
-
*
|
|
226
|
-
* @example
|
|
227
|
-
* ```ts
|
|
228
|
-
* extractTools({ message: { tool_calls: [{ function: { name: 'weather' } }] } })
|
|
229
|
-
* // [{ id: '…', name: 'weather', arguments: {} }]
|
|
230
|
-
* ```
|
|
231
|
-
*/
|
|
232
|
-
function extractTools(record) {
|
|
233
|
-
const message = Reflect.get(record, "message");
|
|
234
|
-
if (!isRecord(message)) return [];
|
|
235
|
-
const calls = Reflect.get(message, "tool_calls");
|
|
236
|
-
if (!Array.isArray(calls)) return [];
|
|
237
|
-
const out = [];
|
|
238
|
-
for (const entry of calls) {
|
|
239
|
-
if (!isRecord(entry)) continue;
|
|
240
|
-
const callable = Reflect.get(entry, "function");
|
|
241
|
-
if (!isRecord(callable)) continue;
|
|
242
|
-
const name = Reflect.get(callable, "name");
|
|
243
|
-
if (!isString(name)) continue;
|
|
244
|
-
const id = Reflect.get(entry, "id");
|
|
245
|
-
out.push({
|
|
246
|
-
id: isString(id) ? id : crypto.randomUUID(),
|
|
247
|
-
name,
|
|
248
|
-
arguments: extractArguments(Reflect.get(callable, "arguments"))
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
return out;
|
|
252
|
-
}
|
|
253
|
-
/**
|
|
254
|
-
* Extracts a wire `arguments` value as a record.
|
|
255
|
-
*
|
|
256
|
-
* @remarks
|
|
257
|
-
* Total: an object passes through, a JSON string is parsed when it yields a record, and
|
|
258
|
-
* a malformed string yields `{}` rather than throwing.
|
|
259
|
-
*
|
|
260
|
-
* @param value - The wire's `function.arguments` value, of unknown shape
|
|
261
|
-
* @returns The argument record, or `{}` when the value carries none
|
|
262
|
-
*
|
|
263
|
-
* @example
|
|
264
|
-
* ```ts
|
|
265
|
-
* extractArguments('{"city":"Oslo"}') // { city: 'Oslo' }
|
|
266
|
-
* ```
|
|
267
|
-
*/
|
|
268
|
-
function extractArguments(value) {
|
|
269
|
-
if (isRecord(value)) return value;
|
|
270
|
-
if (isString(value)) return parseJSONAs(value, isRecord) ?? {};
|
|
271
|
-
return {};
|
|
272
|
-
}
|
|
273
|
-
//#endregion
|
|
274
|
-
//#region src/server/parsers.ts
|
|
275
|
-
/**
|
|
276
|
-
* Parses a non-stream `/api/chat` response body into a wire record.
|
|
277
|
-
*
|
|
278
|
-
* @remarks
|
|
279
|
-
* Total by construction: an empty body, a body that is not JSON, and a body whose JSON is
|
|
280
|
-
* not an object all yield `undefined`, so a malformed daemon response never escapes as a
|
|
281
|
-
* `SyntaxError`. The call site supplies the empty-record default that reads as empty
|
|
282
|
-
* content and no usage.
|
|
283
|
-
*
|
|
284
|
-
* @param response - The 200-OK `/api/chat` response whose body is read as text
|
|
285
|
-
* @returns The parsed record, or `undefined` when the body is empty or malformed
|
|
286
|
-
*
|
|
287
|
-
* @example
|
|
288
|
-
* ```ts
|
|
289
|
-
* await parseBody(new Response('{"message":{"content":"ok"}}'))
|
|
290
|
-
* // { message: { content: 'ok' } }
|
|
291
|
-
* ```
|
|
292
|
-
*/
|
|
293
|
-
async function parseBody(response) {
|
|
294
|
-
return parseJSONAs(await response.text(), isRecord);
|
|
295
|
-
}
|
|
296
|
-
//#endregion
|
|
297
|
-
//#region src/server/OllamaProvider.ts
|
|
298
|
-
/**
|
|
299
|
-
* Implements the local Ollama inference boundary — a {@link ProviderInterface} over Ollama's
|
|
300
|
-
* `POST /api/chat`, both non-streaming (`generate`) and streaming NDJSON (`stream`).
|
|
301
|
-
*
|
|
302
|
-
* @remarks
|
|
303
|
-
* - **Wire protocol.** Posts `{ model, messages, stream, keep_alive, think }` plus
|
|
304
|
-
* passthrough sampling `options` and mapped function `tools`. The `think` flag is
|
|
305
|
-
* CONFIGURABLE through {@link OllamaOptions.think} (default `false`). Non-stream parses
|
|
306
|
-
* one JSON body; stream consumes NDJSON (one JSON object per `\n`-terminated line) —
|
|
307
|
-
* deltas carry `message.content`, the final `done: true` line carries the token usage.
|
|
308
|
-
* - **Think separation.** The wire `think` flag is configurable
|
|
309
|
-
* ({@link OllamaOptions.think}, default `false`). With `think: true` a thinking model's
|
|
310
|
-
* daemon separates reasoning NATIVELY — returning it on the distinct `message.thinking`
|
|
311
|
-
* channel (read here through `extractThinking`) instead of inline in `message.content`. EITHER
|
|
312
|
-
* way the per-call {@link ThinkSplitterInterface} is the defensive guarantee: a daemon
|
|
313
|
-
* may ignore `think: false` for a thinking model and inline `<think>` tags, so every
|
|
314
|
-
* content delta routes through the splitter, only CLEAN content is yielded / assembled,
|
|
315
|
-
* and the separated reasoning (plus any daemon-side `message.thinking` deltas) lands on
|
|
316
|
-
* `ProviderResult.thinking`, never in the conversation.
|
|
317
|
-
* - **Boundary narrowing.** Every wire value arrives as `unknown` and is
|
|
318
|
-
* narrowed through guards (`isRecord` / `isString` / `isNumber`) — never `as`. A
|
|
319
|
-
* missing / malformed field degrades to a sensible default (empty content, no
|
|
320
|
-
* usage, `{}` arguments), never a throw.
|
|
321
|
-
* - **Bounded.** Each call arms a {@link Timeout} for `OllamaOptions.timeout` and
|
|
322
|
-
* passes `AbortSignal.any([timeout.signal, signal])` to `fetch`, so the caller's
|
|
323
|
-
* signal AND the deadline both cancel the request. The timeout is always cleared —
|
|
324
|
-
* in `#fetch` if the request fails/aborts, otherwise in the consuming call's `finally`.
|
|
325
|
-
* - **Abort recovers partial.** A `stream` cancelled mid-flight throws a
|
|
326
|
-
* `ProviderAbortError` carrying the partial result assembled so far; pairing the
|
|
327
|
-
* `TextDecoder({ stream: true })` with the {@link NDJSONParser} parser keeps multi-byte
|
|
328
|
-
* UTF-8 splits and partial lines honest.
|
|
329
|
-
* - **Event-free.** A pure functional boundary — no Emitter, no events.
|
|
330
|
-
* - **Transport seam.** {@link OllamaOptions.fetch} swaps the transport (default
|
|
331
|
-
* `globalThis.fetch`) and {@link OllamaOptions.headers} is a per-request, possibly
|
|
332
|
-
* async header injector merged over the base `Content-Type` — so a browser runtime
|
|
333
|
-
* can route through the developer's own server with an obfuscated bearer token,
|
|
334
|
-
* without this library ever handling a real API key. Both omitted ⇒ the global `fetch`
|
|
335
|
-
* and only a JSON content type.
|
|
336
|
-
* Orthogonal to the deadline: the hook is awaited inside `#fetch`'s try, so a hook
|
|
337
|
-
* rejection clears the armed timer like any other request failure.
|
|
338
|
-
*
|
|
339
|
-
* @example
|
|
340
|
-
* ```ts
|
|
341
|
-
* const provider = new OllamaProvider({ model: 'qwen3.5:2b-q4_K_M' })
|
|
342
|
-
* const result = await provider.generate(messages, abort.signal)
|
|
343
|
-
* ```
|
|
344
|
-
*/
|
|
345
|
-
var OllamaProvider = class {
|
|
346
|
-
name = "ollama";
|
|
347
|
-
#id;
|
|
348
|
-
#model;
|
|
349
|
-
#url;
|
|
350
|
-
#keepAlive;
|
|
351
|
-
#timeout;
|
|
352
|
-
#think;
|
|
353
|
-
#options;
|
|
354
|
-
#transport;
|
|
355
|
-
#headers;
|
|
356
|
-
#format;
|
|
357
|
-
constructor(options) {
|
|
358
|
-
this.#id = crypto.randomUUID();
|
|
359
|
-
this.#model = options.model;
|
|
360
|
-
this.#url = options.url ?? "http://localhost:11434";
|
|
361
|
-
this.#keepAlive = options.keepAlive ?? "5m";
|
|
362
|
-
this.#timeout = options.timeout ?? 12e4;
|
|
363
|
-
this.#think = options.think ?? false;
|
|
364
|
-
this.#options = options.options;
|
|
365
|
-
this.#transport = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
366
|
-
this.#headers = options.headers;
|
|
367
|
-
this.#format = options.format;
|
|
368
|
-
}
|
|
369
|
-
/**
|
|
370
|
-
* Exposes this instance's identity — a fresh `crypto.randomUUID()` minted at
|
|
371
|
-
* construction, satisfying the {@link ProviderInterface.id} contract member. A second
|
|
372
|
-
* provider built from identical options carries a distinct id.
|
|
373
|
-
*
|
|
374
|
-
* @returns The instance's minted identifier
|
|
375
|
-
*/
|
|
376
|
-
get id() {
|
|
377
|
-
return this.#id;
|
|
378
|
-
}
|
|
379
|
-
/**
|
|
380
|
-
* Exposes the provider's context-framing default — the PROVIDER-DEFAULT level of
|
|
381
|
-
* {@link import('@orkestrel/agent').AgentContextInterface.build}'s format cascade (it BEATS
|
|
382
|
-
* the managers' built-in framing, is BEATEN by a manager-options or per-item override).
|
|
383
|
-
* Satisfies the OPTIONAL {@link ProviderInterface.format} contract member: `undefined`
|
|
384
|
-
* when {@link OllamaOptions.format} was omitted (the framing-agnostic default ⇒ core's
|
|
385
|
-
* built-in framing applies unchanged), else the exact configured framing the Agent
|
|
386
|
-
* threads into `build()`.
|
|
387
|
-
*
|
|
388
|
-
* @remarks
|
|
389
|
-
* EXPOSE-ONLY — read by the Agent loop and consumed by core's cascade; it is NEVER sent
|
|
390
|
-
* on the `/api/chat` wire (it is absent from `#body` / the request). This is NOT Ollama's
|
|
391
|
-
* structured-output `format` wire parameter — that one IS sent in `#body`, but only when
|
|
392
|
-
* a per-call `ProviderStreamOptions.schema` is supplied; only the word collides.
|
|
393
|
-
*
|
|
394
|
-
* @returns The configured {@link ContextFormat}, or `undefined` when none
|
|
395
|
-
*/
|
|
396
|
-
get format() {
|
|
397
|
-
return this.#format;
|
|
398
|
-
}
|
|
399
|
-
async generate(messages, signal, tools, options) {
|
|
400
|
-
const { response, timeout } = await this.#fetch(messages, false, signal, tools, options);
|
|
401
|
-
try {
|
|
402
|
-
const record = await parseBody(response) ?? {};
|
|
403
|
-
const splitter = createThinkSplitter();
|
|
404
|
-
splitter.split(extractContent(record));
|
|
405
|
-
splitter.flush();
|
|
406
|
-
const thinking = joinThinking(splitter, extractThinking(record));
|
|
407
|
-
return buildResult(splitter.content, thinking, extractTools(record), extractUsage(record));
|
|
408
|
-
} finally {
|
|
409
|
-
timeout.clear();
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
async *stream(messages, signal, tools, options) {
|
|
413
|
-
const { response, timeout, combined } = await this.#fetch(messages, true, signal, tools, options);
|
|
414
|
-
const body = response.body;
|
|
415
|
-
if (body === null) {
|
|
416
|
-
timeout.clear();
|
|
417
|
-
throw new OllamaHTTPError("Ollama API error: no response body", 0);
|
|
418
|
-
}
|
|
419
|
-
const reader = body.getReader();
|
|
420
|
-
const decoder = new TextDecoder();
|
|
421
|
-
const parser = createNDJSONParser();
|
|
422
|
-
const splitter = createThinkSplitter();
|
|
423
|
-
let wired = "";
|
|
424
|
-
const calls = [];
|
|
425
|
-
let usage;
|
|
426
|
-
try {
|
|
427
|
-
for (;;) {
|
|
428
|
-
const { value, done } = await reader.read();
|
|
429
|
-
if (done) break;
|
|
430
|
-
for (const record of parser.parse(decoder.decode(value, { stream: true }))) {
|
|
431
|
-
const increment = yield* this.#deltas(record, splitter, usage);
|
|
432
|
-
wired += increment.thinking;
|
|
433
|
-
calls.push(...increment.calls);
|
|
434
|
-
usage = increment.usage;
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
const decoderTail = decoder.decode();
|
|
438
|
-
for (const record of parser.parse(decoderTail.length > 0 ? `${decoderTail}\n` : "\n")) {
|
|
439
|
-
const increment = yield* this.#deltas(record, splitter, usage);
|
|
440
|
-
wired += increment.thinking;
|
|
441
|
-
calls.push(...increment.calls);
|
|
442
|
-
usage = increment.usage;
|
|
443
|
-
}
|
|
444
|
-
const tail = splitter.flush();
|
|
445
|
-
if (tail.length > 0) yield {
|
|
446
|
-
channel: "content",
|
|
447
|
-
text: tail
|
|
448
|
-
};
|
|
449
|
-
} catch (error) {
|
|
450
|
-
if (combined.aborted) {
|
|
451
|
-
splitter.flush();
|
|
452
|
-
throw new ProviderAbortError(buildResult(splitter.content, joinThinking(splitter, wired), calls, usage));
|
|
453
|
-
}
|
|
454
|
-
throw error;
|
|
455
|
-
} finally {
|
|
456
|
-
try {
|
|
457
|
-
await reader.cancel();
|
|
458
|
-
} catch {}
|
|
459
|
-
parser.clear();
|
|
460
|
-
timeout.clear();
|
|
461
|
-
}
|
|
462
|
-
return buildResult(splitter.content, joinThinking(splitter, wired), calls, usage);
|
|
463
|
-
}
|
|
464
|
-
*#deltas(record, splitter, usage) {
|
|
465
|
-
const delta = splitter.split(extractContent(record));
|
|
466
|
-
if (delta.length > 0) yield {
|
|
467
|
-
channel: "content",
|
|
468
|
-
text: delta
|
|
469
|
-
};
|
|
470
|
-
const thinking = extractThinking(record);
|
|
471
|
-
if (thinking.length > 0) yield {
|
|
472
|
-
channel: "thinking",
|
|
473
|
-
text: thinking
|
|
474
|
-
};
|
|
475
|
-
return {
|
|
476
|
-
thinking,
|
|
477
|
-
calls: extractTools(record),
|
|
478
|
-
usage: Reflect.get(record, "done") === true ? extractUsage(record) : usage
|
|
479
|
-
};
|
|
480
|
-
}
|
|
481
|
-
async #fetch(messages, stream, signal, tools, options) {
|
|
482
|
-
const timeout = new Timeout({ ms: this.#timeout });
|
|
483
|
-
timeout.start();
|
|
484
|
-
const combined = AbortSignal.any([timeout.signal, signal]);
|
|
485
|
-
try {
|
|
486
|
-
const response = await this.#transport(`${this.#url}/api/chat`, {
|
|
487
|
-
method: "POST",
|
|
488
|
-
headers: await this.#requestHeaders(),
|
|
489
|
-
body: JSON.stringify(this.#body(messages, stream, tools, options)),
|
|
490
|
-
signal: combined
|
|
491
|
-
});
|
|
492
|
-
if (!response.ok) {
|
|
493
|
-
let detail;
|
|
494
|
-
try {
|
|
495
|
-
const text = await response.text();
|
|
496
|
-
detail = text.length > 2048 ? text.slice(0, MAX_ERROR_BODY_LENGTH) : text;
|
|
497
|
-
} catch (cause) {
|
|
498
|
-
throw new OllamaHTTPError(`Ollama API error: ${response.status} - (error body unavailable)`, response.status, { cause });
|
|
499
|
-
}
|
|
500
|
-
throw new OllamaHTTPError(`Ollama API error: ${response.status} - ${detail}`, response.status);
|
|
501
|
-
}
|
|
502
|
-
return {
|
|
503
|
-
response,
|
|
504
|
-
timeout,
|
|
505
|
-
combined
|
|
506
|
-
};
|
|
507
|
-
} catch (error) {
|
|
508
|
-
timeout.clear();
|
|
509
|
-
throw error;
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
async #requestHeaders() {
|
|
513
|
-
const headers = { "Content-Type": "application/json" };
|
|
514
|
-
if (this.#headers !== void 0) for (const [key, value] of Object.entries(await this.#headers())) headers[key] = value;
|
|
515
|
-
return headers;
|
|
516
|
-
}
|
|
517
|
-
#body(messages, stream, tools, options) {
|
|
518
|
-
return {
|
|
519
|
-
model: this.#model,
|
|
520
|
-
messages: mapMessages(messages),
|
|
521
|
-
stream,
|
|
522
|
-
keep_alive: this.#keepAlive,
|
|
523
|
-
think: options?.think ?? this.#think,
|
|
524
|
-
...this.#options !== void 0 ? { options: this.#options } : {},
|
|
525
|
-
...options?.schema !== void 0 ? { format: options.schema } : {},
|
|
526
|
-
...tools !== void 0 && tools.length > 0 ? { tools: tools.map((tool) => ({
|
|
527
|
-
type: "function",
|
|
528
|
-
function: {
|
|
529
|
-
name: tool.name,
|
|
530
|
-
...tool.description === void 0 ? {} : { description: tool.description },
|
|
531
|
-
...tool.parameters === void 0 ? {} : { parameters: tool.parameters }
|
|
532
|
-
}
|
|
533
|
-
})) } : {}
|
|
534
|
-
};
|
|
535
|
-
}
|
|
536
|
-
};
|
|
537
|
-
//#endregion
|
|
538
|
-
//#region src/server/factories.ts
|
|
539
|
-
/**
|
|
540
|
-
* Creates a local Ollama inference provider — a {@link ProviderInterface} over the
|
|
541
|
-
* daemon's `POST /api/chat`, supporting non-streaming `generate` and streaming
|
|
542
|
-
* `stream`.
|
|
543
|
-
*
|
|
544
|
-
* @remarks
|
|
545
|
-
* Only `model` is required; `url` defaults to the local daemon, `keepAlive` to `'5m'`,
|
|
546
|
-
* `timeout` to `120_000`ms, and `options` is forwarded verbatim as sampling
|
|
547
|
-
* parameters (`temperature`, `seed`, and `num_predict`). Both calls take an
|
|
548
|
-
* `AbortSignal` to bound the request; a `stream` cancelled mid-flight throws a
|
|
549
|
-
* `ProviderAbortError` carrying the partial result.
|
|
550
|
-
*
|
|
551
|
-
* The optional `fetch` + `headers` form a transport seam (see {@link OllamaOptions}):
|
|
552
|
-
* point `url` at your own server, inject a custom `fetch`, and have `headers` attach a
|
|
553
|
-
* generated/obfuscated bearer token your server validates — so a browser runtime
|
|
554
|
-
* reaches the LLM through your middleware WITHOUT this library ever handling the real API
|
|
555
|
-
* key. Both omitted ⇒ the global `fetch` and only a JSON content type.
|
|
556
|
-
*
|
|
557
|
-
* The optional `format` is the provider's context-framing default — the PROVIDER-DEFAULT
|
|
558
|
-
* level of `AgentContext`'s format cascade (beaten by a manager-options or per-item
|
|
559
|
-
* override, beating the managers' built-in framing), declaring how this
|
|
560
|
-
* provider's models prefer context sections framed (for example XML group wrappers vs. Markdown
|
|
561
|
-
* headers). It is EXPOSED on the provider for the Agent's `build()` and is NOT Ollama's
|
|
562
|
-
* `/api/chat` `format` wire parameter (structured output) — the two are unrelated despite
|
|
563
|
-
* the shared word. Omitted ⇒ the provider is framing-agnostic (core's built-in defaults).
|
|
564
|
-
*
|
|
565
|
-
* @param options - `model` (required), and optional `url` / `keepAlive` / `timeout` /
|
|
566
|
-
* `options` / `fetch` / `headers` / `format` (see {@link OllamaOptions})
|
|
567
|
-
* @returns A working {@link ProviderInterface} backed by Ollama
|
|
568
|
-
*
|
|
569
|
-
* @example
|
|
570
|
-
* ```ts
|
|
571
|
-
* import { createAbort } from '@orkestrel/abort'
|
|
572
|
-
* import { createOllama } from '@orkestrel/ollama'
|
|
573
|
-
*
|
|
574
|
-
* const provider = createOllama({ model: 'qwen3.5:2b-q4_K_M' })
|
|
575
|
-
* const abort = createAbort()
|
|
576
|
-
* const result = await provider.generate(messages, abort.signal)
|
|
577
|
-
* ```
|
|
578
|
-
*
|
|
579
|
-
* @example
|
|
580
|
-
* Route through your own server with an obfuscated token:
|
|
581
|
-
* ```ts
|
|
582
|
-
* const provider = createOllama({
|
|
583
|
-
* model: 'qwen3.5:2b-q4_K_M',
|
|
584
|
-
* url: 'https://my-app.example.com/llm', // your server, not the daemon
|
|
585
|
-
* fetch: myFetch, // optional custom transport
|
|
586
|
-
* headers: () => ({ authorization: `Bearer ${myToken}` }), // your server validates this
|
|
587
|
-
* })
|
|
588
|
-
* ```
|
|
589
|
-
*
|
|
590
|
-
* @example
|
|
591
|
-
* Declare a context-framing default — wrap the instructions section in an XML group (the
|
|
592
|
-
* provider-default level of `AgentContext`'s cascade; NOT the wire `format`):
|
|
593
|
-
* ```ts
|
|
594
|
-
* const provider = createOllama({
|
|
595
|
-
* model: 'qwen3.5:2b-q4_K_M',
|
|
596
|
-
* format: {
|
|
597
|
-
* instructions: {
|
|
598
|
-
* open: '<instructions>',
|
|
599
|
-
* render: (i) => `<instruction>${i.content}</instruction>`,
|
|
600
|
-
* close: '</instructions>',
|
|
601
|
-
* },
|
|
602
|
-
* },
|
|
603
|
-
* })
|
|
604
|
-
* ```
|
|
605
|
-
*/
|
|
606
|
-
function createOllama(options) {
|
|
607
|
-
return new OllamaProvider(options);
|
|
608
|
-
}
|
|
609
|
-
//#endregion
|
|
610
|
-
export { DEFAULT_KEEP_ALIVE, DEFAULT_OLLAMA_URL, DEFAULT_PROVIDER_TIMEOUT, MAX_ERROR_BODY_LENGTH, OllamaHTTPError, OllamaProvider, buildResult, createOllama, extractArguments, extractContent, extractThinking, extractTools, extractUsage, isOllamaHTTPError, joinThinking, mapMessages, parseBody };
|
|
611
|
-
|
|
612
|
-
//# sourceMappingURL=index.js.map
|