@agentic-kit/ollama 1.0.3 → 1.2.0

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/index.js CHANGED
@@ -1,145 +1,482 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- const cross_fetch_1 = __importDefault(require("cross-fetch"));
7
- // ─── Client ───────────────────────────────────────────────────────────────────
3
+ exports.OllamaAdapter = exports.OllamaClient = exports.OLLAMA_MODELS = void 0;
4
+ const fetch = globalThis.fetch.bind(globalThis);
5
+ class EventStream {
6
+ isTerminal;
7
+ extractResult;
8
+ queue = [];
9
+ waiting = [];
10
+ done = false;
11
+ finalResultPromise;
12
+ resolveFinalResult;
13
+ constructor(isTerminal, extractResult) {
14
+ this.isTerminal = isTerminal;
15
+ this.extractResult = extractResult;
16
+ this.finalResultPromise = new Promise((resolve) => {
17
+ this.resolveFinalResult = resolve;
18
+ });
19
+ }
20
+ push(event) {
21
+ if (this.done) {
22
+ return;
23
+ }
24
+ if (this.isTerminal(event)) {
25
+ this.done = true;
26
+ this.resolveFinalResult(this.extractResult(event));
27
+ }
28
+ const waiter = this.waiting.shift();
29
+ if (waiter) {
30
+ waiter({ value: event, done: false });
31
+ return;
32
+ }
33
+ this.queue.push(event);
34
+ }
35
+ end(result) {
36
+ this.done = true;
37
+ if (result !== undefined) {
38
+ this.resolveFinalResult(result);
39
+ }
40
+ while (this.waiting.length > 0) {
41
+ this.waiting.shift()({ value: undefined, done: true });
42
+ }
43
+ }
44
+ async *[Symbol.asyncIterator]() {
45
+ while (true) {
46
+ if (this.queue.length > 0) {
47
+ yield this.queue.shift();
48
+ continue;
49
+ }
50
+ if (this.done) {
51
+ return;
52
+ }
53
+ const next = await new Promise((resolve) => {
54
+ this.waiting.push(resolve);
55
+ });
56
+ if (next.done) {
57
+ return;
58
+ }
59
+ yield next.value;
60
+ }
61
+ }
62
+ result() {
63
+ return this.finalResultPromise;
64
+ }
65
+ }
66
+ class DefaultAssistantMessageEventStream extends EventStream {
67
+ constructor() {
68
+ super((event) => event.type === 'done' || event.type === 'error', (event) => {
69
+ if (event.type === 'done') {
70
+ return event.message;
71
+ }
72
+ if (event.type === 'error') {
73
+ return event.error;
74
+ }
75
+ throw new Error('Unexpected terminal event');
76
+ });
77
+ }
78
+ }
79
+ exports.OLLAMA_MODELS = [];
8
80
  class OllamaClient {
9
81
  baseUrl;
10
82
  constructor(baseUrl = 'http://localhost:11434') {
11
83
  this.baseUrl = baseUrl;
12
84
  }
13
- // ── Models ──────────────────────────────────────────────────────────────────
14
85
  async listModels() {
15
- const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/tags`);
16
- if (!res.ok) {
17
- throw new Error(`listModels failed: ${res.status} ${res.statusText}`);
86
+ const response = await fetch(`${this.baseUrl}/api/tags`);
87
+ if (!response.ok) {
88
+ throw new Error(`listModels failed: ${response.status} ${response.statusText}`);
18
89
  }
19
- const data = await res.json();
20
- if (data.models?.length)
21
- return data.models.map((m) => m.name);
22
- if (data.tags?.length)
23
- return data.tags;
24
- return [];
90
+ const payload = (await response.json());
91
+ return payload.models?.map((model) => model.name) ?? [];
92
+ }
93
+ async showModel(model) {
94
+ const response = await fetch(`${this.baseUrl}/api/show`, {
95
+ method: 'POST',
96
+ headers: { 'Content-Type': 'application/json' },
97
+ body: JSON.stringify({ model }),
98
+ });
99
+ if (!response.ok)
100
+ return null;
101
+ return (await response.json());
25
102
  }
26
103
  async pullModel(model) {
27
- const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/pull`, {
104
+ const response = await fetch(`${this.baseUrl}/api/pull`, {
28
105
  method: 'POST',
29
106
  headers: { 'Content-Type': 'application/json' },
30
107
  body: JSON.stringify({ name: model }),
31
108
  });
32
- if (!res.ok) {
33
- throw new Error(`pullModel failed: ${res.status} ${res.statusText}`);
109
+ if (!response.ok) {
110
+ throw new Error(`pullModel failed: ${response.status} ${response.statusText}`);
34
111
  }
35
112
  }
36
113
  async deleteModel(model) {
37
- const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/delete`, {
114
+ const response = await fetch(`${this.baseUrl}/api/delete`, {
38
115
  method: 'DELETE',
39
116
  headers: { 'Content-Type': 'application/json' },
40
117
  body: JSON.stringify({ name: model }),
41
118
  });
42
- if (!res.ok) {
43
- throw new Error(`deleteModel failed: ${res.status} ${res.statusText}`);
44
- }
45
- }
46
- async generate(input, onChunk) {
47
- if (input.messages) {
48
- return this._chat(input, onChunk);
119
+ if (!response.ok) {
120
+ throw new Error(`deleteModel failed: ${response.status} ${response.statusText}`);
49
121
  }
50
- return this._generate(input, onChunk);
51
122
  }
52
- // ── Embeddings ──────────────────────────────────────────────────────────────
53
123
  async generateEmbedding(text, model = 'nomic-embed-text') {
54
- const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/embeddings`, {
124
+ const response = await fetch(`${this.baseUrl}/api/embeddings`, {
55
125
  method: 'POST',
56
126
  headers: { 'Content-Type': 'application/json' },
57
127
  body: JSON.stringify({ model, prompt: text }),
58
128
  });
59
- if (!res.ok) {
60
- throw new Error(`generateEmbedding failed: ${res.status} ${res.statusText}`);
129
+ if (!response.ok) {
130
+ throw new Error(`generateEmbedding failed: ${response.status} ${response.statusText}`);
61
131
  }
62
- const data = await res.json();
63
- return data.embedding;
64
- }
65
- // ── Private: /api/generate ──────────────────────────────────────────────────
66
- async _generate(input, onChunk) {
67
- const body = {
68
- model: input.model,
69
- prompt: input.prompt ?? '',
70
- stream: !!onChunk,
132
+ const payload = (await response.json());
133
+ return payload.embedding;
134
+ }
135
+ async generate(input, onChunk) {
136
+ const context = legacyInputToContext(input);
137
+ const model = {
138
+ id: input.model,
139
+ name: input.model,
140
+ api: 'ollama-native',
141
+ provider: 'ollama',
142
+ baseUrl: this.baseUrl,
143
+ input: ['text', 'image'],
144
+ reasoning: false,
145
+ tools: false,
146
+ maxOutputTokens: input.maxTokens,
71
147
  };
72
- if (input.system)
73
- body.system = input.system;
74
- if (input.temperature !== undefined)
75
- body.temperature = input.temperature;
76
- const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/generate`, {
77
- method: 'POST',
78
- headers: { 'Content-Type': 'application/json' },
79
- body: JSON.stringify(body),
148
+ const adapter = new OllamaAdapter(this.baseUrl);
149
+ const response = adapter.stream(model, context, {
150
+ maxTokens: input.maxTokens,
151
+ signal: undefined,
152
+ temperature: input.temperature,
80
153
  });
81
- if (!res.ok) {
82
- const text = await res.text().catch(() => '');
83
- throw new Error(`generate failed: ${res.status} ${res.statusText} — ${text}`);
154
+ if (onChunk || input.stream) {
155
+ for await (const event of response) {
156
+ if (event.type === 'text_delta') {
157
+ onChunk?.(event.delta);
158
+ }
159
+ }
160
+ return;
84
161
  }
85
- if (onChunk) {
86
- return this._streamResponse(res, (data) => data.response, onChunk);
162
+ const message = await response.result();
163
+ return message.content
164
+ .filter((block) => block.type === 'text')
165
+ .map((block) => block.text)
166
+ .join('');
167
+ }
168
+ }
169
+ exports.OllamaClient = OllamaClient;
170
+ class OllamaAdapter {
171
+ api = 'ollama-native';
172
+ provider = 'ollama';
173
+ name = 'ollama';
174
+ client;
175
+ baseUrl;
176
+ constructor(baseUrl) {
177
+ this.baseUrl = baseUrl ?? 'http://localhost:11434';
178
+ this.client = new OllamaClient(this.baseUrl);
179
+ }
180
+ createModel(modelId, overrides) {
181
+ return {
182
+ id: modelId,
183
+ name: modelId,
184
+ api: this.api,
185
+ provider: this.provider,
186
+ baseUrl: this.baseUrl,
187
+ input: ['text', 'image'],
188
+ reasoning: false,
189
+ tools: false,
190
+ ...overrides,
191
+ };
192
+ }
193
+ async listModels() {
194
+ return this.client.listModels();
195
+ }
196
+ stream(model, context, options) {
197
+ const stream = new DefaultAssistantMessageEventStream();
198
+ const output = createAssistantMessage(model);
199
+ void (async () => {
200
+ const body = {
201
+ model: model.id,
202
+ stream: true,
203
+ messages: toOllamaMessages(context),
204
+ options: {
205
+ temperature: options?.temperature,
206
+ num_predict: options?.maxTokens,
207
+ },
208
+ };
209
+ if (model.reasoning)
210
+ body.think = true;
211
+ try {
212
+ const response = await fetch(`${model.baseUrl}/api/chat`, {
213
+ method: 'POST',
214
+ headers: { 'Content-Type': 'application/json' },
215
+ body: JSON.stringify(body),
216
+ signal: options?.signal,
217
+ });
218
+ if (!response.ok) {
219
+ const text = await response.text().catch(() => '');
220
+ throw new Error(`Ollama error ${response.status}: ${text}`);
221
+ }
222
+ stream.push({ type: 'start', partial: clone(output) });
223
+ if (!response.body) {
224
+ throw new Error('No response body');
225
+ }
226
+ const decoder = new TextDecoder();
227
+ let buffer = '';
228
+ let textIndex;
229
+ let thinkingIndex;
230
+ let finished = false;
231
+ const processPayload = (payload) => {
232
+ const thinking = payload.message?.thinking ?? '';
233
+ if (thinking) {
234
+ if (thinkingIndex === undefined) {
235
+ thinkingIndex = output.content.push({ type: 'thinking', thinking: '' }) - 1;
236
+ stream.push({
237
+ type: 'thinking_start',
238
+ contentIndex: thinkingIndex,
239
+ partial: clone(output),
240
+ });
241
+ }
242
+ const block = output.content[thinkingIndex];
243
+ block.thinking += thinking;
244
+ stream.push({
245
+ type: 'thinking_delta',
246
+ contentIndex: thinkingIndex,
247
+ delta: thinking,
248
+ partial: clone(output),
249
+ });
250
+ }
251
+ const text = payload.message?.content ?? payload.response ?? '';
252
+ if (text) {
253
+ if (textIndex === undefined) {
254
+ textIndex = output.content.push({ type: 'text', text: '' }) - 1;
255
+ stream.push({ type: 'text_start', contentIndex: textIndex, partial: clone(output) });
256
+ }
257
+ const block = output.content[textIndex];
258
+ block.text += text;
259
+ stream.push({
260
+ type: 'text_delta',
261
+ contentIndex: textIndex,
262
+ delta: text,
263
+ partial: clone(output),
264
+ });
265
+ }
266
+ if (!payload.done) {
267
+ return false;
268
+ }
269
+ output.usage.input = payload.prompt_eval_count ?? output.usage.input;
270
+ output.usage.output = payload.eval_count ?? output.usage.output;
271
+ output.usage.totalTokens = output.usage.input + output.usage.output;
272
+ output.stopReason = payload.done_reason === 'length' ? 'length' : 'stop';
273
+ if (thinkingIndex !== undefined) {
274
+ stream.push({
275
+ type: 'thinking_end',
276
+ contentIndex: thinkingIndex,
277
+ content: output.content[thinkingIndex].thinking,
278
+ partial: clone(output),
279
+ });
280
+ }
281
+ if (textIndex !== undefined) {
282
+ stream.push({
283
+ type: 'text_end',
284
+ contentIndex: textIndex,
285
+ content: output.content[textIndex].text,
286
+ partial: clone(output),
287
+ });
288
+ }
289
+ stream.push({
290
+ type: 'done',
291
+ reason: output.stopReason === 'length' ? 'length' : 'stop',
292
+ message: clone(output),
293
+ });
294
+ stream.end(output);
295
+ finished = true;
296
+ return true;
297
+ };
298
+ for await (const chunk of iterateResponseBody(response.body)) {
299
+ buffer += decoder.decode(chunk, { stream: true });
300
+ const lines = buffer.split('\n');
301
+ buffer = lines.pop() ?? '';
302
+ for (const line of lines) {
303
+ const trimmed = line.trim();
304
+ if (!trimmed) {
305
+ continue;
306
+ }
307
+ const payload = JSON.parse(trimmed);
308
+ if (processPayload(payload)) {
309
+ return;
310
+ }
311
+ }
312
+ }
313
+ const trailing = buffer.trim();
314
+ if (!finished && trailing) {
315
+ const payload = JSON.parse(trailing);
316
+ if (processPayload(payload)) {
317
+ return;
318
+ }
319
+ }
320
+ if (thinkingIndex !== undefined) {
321
+ stream.push({
322
+ type: 'thinking_end',
323
+ contentIndex: thinkingIndex,
324
+ content: output.content[thinkingIndex].thinking,
325
+ partial: clone(output),
326
+ });
327
+ }
328
+ if (textIndex !== undefined) {
329
+ stream.push({
330
+ type: 'text_end',
331
+ contentIndex: textIndex,
332
+ content: output.content[textIndex].text,
333
+ partial: clone(output),
334
+ });
335
+ }
336
+ stream.push({
337
+ type: 'done',
338
+ reason: output.stopReason === 'length' ? 'length' : 'stop',
339
+ message: clone(output),
340
+ });
341
+ stream.end(output);
342
+ }
343
+ catch (error) {
344
+ output.stopReason = options?.signal?.aborted ? 'aborted' : 'error';
345
+ output.errorMessage = error instanceof Error ? error.message : String(error);
346
+ stream.push({
347
+ type: 'error',
348
+ reason: output.stopReason === 'aborted' ? 'aborted' : 'error',
349
+ error: clone(output),
350
+ });
351
+ stream.end(output);
352
+ }
353
+ })();
354
+ return stream;
355
+ }
356
+ }
357
+ exports.OllamaAdapter = OllamaAdapter;
358
+ function toOllamaMessages(context) {
359
+ const messages = context.messages.map((message) => {
360
+ if (message.role === 'user') {
361
+ if (typeof message.content === 'string') {
362
+ return { role: 'user', content: message.content };
363
+ }
364
+ return {
365
+ role: 'user',
366
+ content: message.content
367
+ .filter((block) => block.type === 'text')
368
+ .map((block) => block.text)
369
+ .join('\n'),
370
+ images: message.content
371
+ .filter((block) => block.type === 'image')
372
+ .map((block) => block.data),
373
+ };
87
374
  }
88
- const data = await res.json();
89
- return data.response;
90
- }
91
- // ── Private: /api/chat ──────────────────────────────────────────────────────
92
- async _chat(input, onChunk) {
93
- const messages = [];
94
- if (input.system) {
95
- messages.push({ role: 'system', content: input.system });
375
+ if (message.role === 'toolResult') {
376
+ return {
377
+ role: 'user',
378
+ content: message.content
379
+ .map((block) => block.type === 'text' ? block.text : `[image:${block.mimeType};bytes=${block.data.length}]`)
380
+ .join('\n'),
381
+ };
96
382
  }
97
- messages.push(...(input.messages ?? []));
98
- const body = {
99
- model: input.model,
100
- messages,
101
- stream: !!onChunk,
383
+ return {
384
+ role: 'assistant',
385
+ content: message.content
386
+ .map((block) => {
387
+ if (block.type === 'text') {
388
+ return block.text;
389
+ }
390
+ if (block.type === 'thinking') {
391
+ return `<thinking>${block.thinking}</thinking>`;
392
+ }
393
+ return `<tool-call name="${block.name}">${JSON.stringify(block.arguments)}</tool-call>`;
394
+ })
395
+ .join('\n'),
102
396
  };
103
- if (input.temperature !== undefined)
104
- body.temperature = input.temperature;
105
- const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/api/chat`, {
106
- method: 'POST',
107
- headers: { 'Content-Type': 'application/json' },
108
- body: JSON.stringify(body),
397
+ });
398
+ if (context.systemPrompt) {
399
+ messages.unshift({
400
+ role: 'system',
401
+ content: context.systemPrompt,
109
402
  });
110
- if (!res.ok) {
111
- const text = await res.text().catch(() => '');
112
- throw new Error(`chat failed: ${res.status} ${res.statusText} — ${text}`);
113
- }
114
- if (onChunk) {
115
- return this._streamResponse(res, (data) => data.message?.content ?? '', onChunk);
116
- }
117
- const data = await res.json();
118
- return data.message?.content ?? '';
119
- }
120
- // ── Private: streaming reader ───────────────────────────────────────────────
121
- async _streamResponse(res, extract, onChunk) {
122
- const reader = res.body?.getReader();
123
- if (!reader)
124
- throw new Error('No response body reader');
125
- const decoder = new TextDecoder();
403
+ }
404
+ return messages;
405
+ }
406
+ function createAssistantMessage(model) {
407
+ return {
408
+ role: 'assistant',
409
+ api: model.api,
410
+ provider: model.provider,
411
+ model: model.id,
412
+ content: [],
413
+ usage: {
414
+ input: 0,
415
+ output: 0,
416
+ cacheRead: 0,
417
+ cacheWrite: 0,
418
+ totalTokens: 0,
419
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
420
+ },
421
+ stopReason: 'stop',
422
+ timestamp: Date.now(),
423
+ };
424
+ }
425
+ function legacyInputToContext(input) {
426
+ const messages = input.messages
427
+ ? input.messages
428
+ .filter((message) => message.role !== 'system')
429
+ .map((message) => message.role === 'assistant'
430
+ ? {
431
+ role: 'assistant',
432
+ api: 'ollama-native',
433
+ provider: 'ollama',
434
+ model: input.model,
435
+ content: [{ type: 'text', text: message.content }],
436
+ usage: {
437
+ input: 0,
438
+ output: 0,
439
+ cacheRead: 0,
440
+ cacheWrite: 0,
441
+ totalTokens: 0,
442
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
443
+ },
444
+ stopReason: 'stop',
445
+ timestamp: Date.now(),
446
+ }
447
+ : {
448
+ role: 'user',
449
+ content: message.content,
450
+ timestamp: Date.now(),
451
+ })
452
+ : [{ role: 'user', content: input.prompt ?? '', timestamp: Date.now() }];
453
+ return {
454
+ systemPrompt: input.system ?? input.messages?.find((message) => message.role === 'system')?.content,
455
+ messages,
456
+ };
457
+ }
458
+ function clone(value) {
459
+ return JSON.parse(JSON.stringify(value));
460
+ }
461
+ async function* iterateResponseBody(body) {
462
+ if ('getReader' in body && typeof body.getReader === 'function') {
463
+ const reader = body.getReader();
126
464
  while (true) {
127
465
  const { done, value } = await reader.read();
128
- if (done)
129
- break;
130
- const lines = decoder.decode(value).split('\n').filter(Boolean);
131
- for (const line of lines) {
132
- try {
133
- const data = JSON.parse(line);
134
- const chunk = extract(data);
135
- if (chunk)
136
- onChunk(chunk);
137
- }
138
- catch {
139
- // partial line — skip
140
- }
466
+ if (done) {
467
+ return;
468
+ }
469
+ if (value) {
470
+ yield value;
141
471
  }
142
472
  }
143
473
  }
474
+ for await (const chunk of body) {
475
+ if (typeof chunk === 'string') {
476
+ yield new TextEncoder().encode(chunk);
477
+ continue;
478
+ }
479
+ yield chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
480
+ }
144
481
  }
145
482
  exports.default = OllamaClient;
package/package.json CHANGED
@@ -1,11 +1,18 @@
1
1
  {
2
2
  "name": "@agentic-kit/ollama",
3
- "version": "1.0.3",
3
+ "version": "1.2.0",
4
4
  "author": "Dan Lynch <pyramation@gmail.com>",
5
5
  "description": "Ollama",
6
6
  "main": "index.js",
7
7
  "module": "esm/index.js",
8
8
  "types": "index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./index.d.ts",
12
+ "import": "./esm/index.js",
13
+ "require": "./index.js"
14
+ }
15
+ },
9
16
  "homepage": "https://github.com/constructive-io/agentic-kit",
10
17
  "license": "SEE LICENSE IN LICENSE",
11
18
  "publishConfig": {
@@ -23,14 +30,15 @@
23
30
  "clean": "makage clean",
24
31
  "prepack": "npm run build",
25
32
  "build": "makage build",
33
+ "postbuild": "node ../../scripts/write-esm-package-json.js",
26
34
  "build:dev": "makage build --dev",
27
35
  "lint": "eslint . --fix",
28
36
  "test": "jest",
37
+ "test:live": "node ./scripts/run-live-tests.js smoke",
38
+ "test:live:smoke": "node ./scripts/run-live-tests.js smoke",
39
+ "test:live:extended": "node ./scripts/run-live-tests.js extended",
29
40
  "test:watch": "jest --watch"
30
41
  },
31
42
  "keywords": [],
32
- "dependencies": {
33
- "cross-fetch": "^4.1.0"
34
- },
35
- "gitHead": "cbd1f7833d4a107f6fcc897ac7d0df9041cabbdd"
43
+ "gitHead": "d4f3f660be621267efe12671c22db202ccdb3f0b"
36
44
  }