@agentic-kit/ollama 1.0.0 → 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.d.ts ADDED
@@ -0,0 +1,182 @@
1
+ type JsonPrimitive = string | number | boolean | null;
2
+ type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
3
+ interface JsonObject {
4
+ [key: string]: JsonValue | undefined;
5
+ }
6
+ interface ModelDescriptor {
7
+ id: string;
8
+ name: string;
9
+ api: string;
10
+ provider: string;
11
+ baseUrl: string;
12
+ input: Array<'text' | 'image'>;
13
+ reasoning: boolean;
14
+ tools?: boolean;
15
+ contextWindow?: number;
16
+ maxOutputTokens?: number;
17
+ headers?: Record<string, string>;
18
+ }
19
+ interface TextContent {
20
+ type: 'text';
21
+ text: string;
22
+ }
23
+ interface ImageContent {
24
+ type: 'image';
25
+ data: string;
26
+ mimeType: string;
27
+ }
28
+ interface ThinkingContent {
29
+ type: 'thinking';
30
+ thinking: string;
31
+ }
32
+ interface ToolCallContent {
33
+ type: 'toolCall';
34
+ id: string;
35
+ name: string;
36
+ arguments: Record<string, JsonValue | undefined>;
37
+ }
38
+ interface Usage {
39
+ input: number;
40
+ output: number;
41
+ cacheRead: number;
42
+ cacheWrite: number;
43
+ totalTokens: number;
44
+ cost: {
45
+ input: number;
46
+ output: number;
47
+ cacheRead: number;
48
+ cacheWrite: number;
49
+ total: number;
50
+ };
51
+ }
52
+ type Message = {
53
+ role: 'user';
54
+ content: string | Array<TextContent | ImageContent>;
55
+ timestamp: number;
56
+ } | {
57
+ role: 'assistant';
58
+ content: Array<TextContent | ThinkingContent | ToolCallContent>;
59
+ api: string;
60
+ provider: string;
61
+ model: string;
62
+ usage: Usage;
63
+ stopReason: 'stop' | 'length' | 'toolUse' | 'error' | 'aborted';
64
+ errorMessage?: string;
65
+ timestamp: number;
66
+ } | {
67
+ role: 'toolResult';
68
+ toolCallId: string;
69
+ toolName: string;
70
+ content: Array<TextContent | ImageContent>;
71
+ isError: boolean;
72
+ details?: unknown;
73
+ timestamp: number;
74
+ };
75
+ interface Context {
76
+ systemPrompt?: string;
77
+ messages: Message[];
78
+ }
79
+ interface StreamOptions {
80
+ maxTokens?: number;
81
+ signal?: AbortSignal;
82
+ temperature?: number;
83
+ }
84
+ type AssistantMessage = Extract<Message, {
85
+ role: 'assistant';
86
+ }>;
87
+ type AssistantMessageEvent = {
88
+ type: 'start';
89
+ partial: AssistantMessage;
90
+ } | {
91
+ type: 'text_start';
92
+ contentIndex: number;
93
+ partial: AssistantMessage;
94
+ } | {
95
+ type: 'text_delta';
96
+ contentIndex: number;
97
+ delta: string;
98
+ partial: AssistantMessage;
99
+ } | {
100
+ type: 'text_end';
101
+ contentIndex: number;
102
+ content: string;
103
+ partial: AssistantMessage;
104
+ } | {
105
+ type: 'thinking_start';
106
+ contentIndex: number;
107
+ partial: AssistantMessage;
108
+ } | {
109
+ type: 'thinking_delta';
110
+ contentIndex: number;
111
+ delta: string;
112
+ partial: AssistantMessage;
113
+ } | {
114
+ type: 'thinking_end';
115
+ contentIndex: number;
116
+ content: string;
117
+ partial: AssistantMessage;
118
+ } | {
119
+ type: 'toolcall_start';
120
+ contentIndex: number;
121
+ partial: AssistantMessage;
122
+ } | {
123
+ type: 'toolcall_delta';
124
+ contentIndex: number;
125
+ delta: string;
126
+ partial: AssistantMessage;
127
+ } | {
128
+ type: 'toolcall_end';
129
+ contentIndex: number;
130
+ toolCall: ToolCallContent;
131
+ partial: AssistantMessage;
132
+ } | {
133
+ type: 'done';
134
+ reason: 'stop' | 'length' | 'toolUse';
135
+ message: AssistantMessage;
136
+ } | {
137
+ type: 'error';
138
+ reason: 'error' | 'aborted';
139
+ error: AssistantMessage;
140
+ };
141
+ interface AssistantMessageEventStream extends AsyncIterable<AssistantMessageEvent> {
142
+ result(): Promise<AssistantMessage>;
143
+ }
144
+ export interface ChatMessage {
145
+ role: 'system' | 'user' | 'assistant';
146
+ content: string;
147
+ }
148
+ export interface GenerateInput {
149
+ model: string;
150
+ prompt?: string;
151
+ messages?: ChatMessage[];
152
+ system?: string;
153
+ stream?: boolean;
154
+ temperature?: number;
155
+ maxTokens?: number;
156
+ }
157
+ export declare const OLLAMA_MODELS: ModelDescriptor[];
158
+ export declare class OllamaClient {
159
+ private readonly baseUrl;
160
+ constructor(baseUrl?: string);
161
+ listModels(): Promise<string[]>;
162
+ showModel(model: string): Promise<{
163
+ capabilities?: string[];
164
+ } | null>;
165
+ pullModel(model: string): Promise<void>;
166
+ deleteModel(model: string): Promise<void>;
167
+ generateEmbedding(text: string, model?: string): Promise<number[]>;
168
+ generate(input: GenerateInput): Promise<string>;
169
+ generate(input: GenerateInput, onChunk: (chunk: string) => void): Promise<void>;
170
+ }
171
+ export declare class OllamaAdapter {
172
+ readonly api = "ollama-native";
173
+ readonly provider = "ollama";
174
+ readonly name = "ollama";
175
+ private readonly client;
176
+ private readonly baseUrl;
177
+ constructor(baseUrl?: string);
178
+ createModel(modelId: string, overrides?: Partial<ModelDescriptor>): ModelDescriptor;
179
+ listModels(): Promise<Array<ModelDescriptor | string>>;
180
+ stream(model: ModelDescriptor, context: Context, options?: StreamOptions): AssistantMessageEventStream;
181
+ }
182
+ export default OllamaClient;
package/index.js ADDED
@@ -0,0 +1,482 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
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 = [];
80
+ class OllamaClient {
81
+ baseUrl;
82
+ constructor(baseUrl = 'http://localhost:11434') {
83
+ this.baseUrl = baseUrl;
84
+ }
85
+ async listModels() {
86
+ const response = await fetch(`${this.baseUrl}/api/tags`);
87
+ if (!response.ok) {
88
+ throw new Error(`listModels failed: ${response.status} ${response.statusText}`);
89
+ }
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());
102
+ }
103
+ async pullModel(model) {
104
+ const response = await fetch(`${this.baseUrl}/api/pull`, {
105
+ method: 'POST',
106
+ headers: { 'Content-Type': 'application/json' },
107
+ body: JSON.stringify({ name: model }),
108
+ });
109
+ if (!response.ok) {
110
+ throw new Error(`pullModel failed: ${response.status} ${response.statusText}`);
111
+ }
112
+ }
113
+ async deleteModel(model) {
114
+ const response = await fetch(`${this.baseUrl}/api/delete`, {
115
+ method: 'DELETE',
116
+ headers: { 'Content-Type': 'application/json' },
117
+ body: JSON.stringify({ name: model }),
118
+ });
119
+ if (!response.ok) {
120
+ throw new Error(`deleteModel failed: ${response.status} ${response.statusText}`);
121
+ }
122
+ }
123
+ async generateEmbedding(text, model = 'nomic-embed-text') {
124
+ const response = await fetch(`${this.baseUrl}/api/embeddings`, {
125
+ method: 'POST',
126
+ headers: { 'Content-Type': 'application/json' },
127
+ body: JSON.stringify({ model, prompt: text }),
128
+ });
129
+ if (!response.ok) {
130
+ throw new Error(`generateEmbedding failed: ${response.status} ${response.statusText}`);
131
+ }
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,
147
+ };
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,
153
+ });
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;
161
+ }
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
+ };
374
+ }
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
+ };
382
+ }
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'),
396
+ };
397
+ });
398
+ if (context.systemPrompt) {
399
+ messages.unshift({
400
+ role: 'system',
401
+ content: context.systemPrompt,
402
+ });
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();
464
+ while (true) {
465
+ const { done, value } = await reader.read();
466
+ if (done) {
467
+ return;
468
+ }
469
+ if (value) {
470
+ yield value;
471
+ }
472
+ }
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
+ }
481
+ }
482
+ exports.default = OllamaClient;
package/package.json CHANGED
@@ -1,11 +1,18 @@
1
1
  {
2
2
  "name": "@agentic-kit/ollama",
3
- "version": "1.0.0",
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": {
@@ -21,14 +28,17 @@
21
28
  },
22
29
  "scripts": {
23
30
  "clean": "makage clean",
31
+ "prepack": "npm run build",
24
32
  "build": "makage build",
33
+ "postbuild": "node ../../scripts/write-esm-package-json.js",
25
34
  "build:dev": "makage build --dev",
26
35
  "lint": "eslint . --fix",
27
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",
28
40
  "test:watch": "jest --watch"
29
41
  },
30
42
  "keywords": [],
31
- "dependencies": {
32
- "cross-fetch": "^4.1.0"
33
- }
43
+ "gitHead": "d4f3f660be621267efe12671c22db202ccdb3f0b"
34
44
  }