@agentic-kit/ollama 1.0.3 → 1.2.1
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 +47 -12
- package/esm/index.js +448 -99
- package/esm/package.json +1 -0
- package/index.d.ts +169 -9
- package/index.js +449 -101
- package/package.json +13 -5
package/README.md
CHANGED
|
@@ -12,7 +12,9 @@
|
|
|
12
12
|
<a href="https://www.npmjs.com/package/@agentic-kit/ollama"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/agentic-kit?filename=packages%2Follama%2Fpackage.json"/></a>
|
|
13
13
|
</p>
|
|
14
14
|
|
|
15
|
-
A JavaScript/TypeScript client for the Ollama
|
|
15
|
+
A JavaScript/TypeScript client and provider adapter for the Ollama API,
|
|
16
|
+
supporting model listing, structured streaming text generation, embeddings, and
|
|
17
|
+
model management.
|
|
16
18
|
|
|
17
19
|
## Installation
|
|
18
20
|
|
|
@@ -52,13 +54,6 @@ await client.pullModel('mistral');
|
|
|
52
54
|
const embedding = await client.generateEmbedding('Compute embeddings');
|
|
53
55
|
console.log('Embedding vector length:', embedding.length);
|
|
54
56
|
|
|
55
|
-
// Generate a conversational response with context
|
|
56
|
-
const response = await client.generateResponse(
|
|
57
|
-
'What is the capital of France?',
|
|
58
|
-
'Geography trivia'
|
|
59
|
-
);
|
|
60
|
-
console.log(response);
|
|
61
|
-
|
|
62
57
|
// Delete a pulled model when done
|
|
63
58
|
await client.deleteModel('mistral');
|
|
64
59
|
```
|
|
@@ -67,23 +62,63 @@ await client.deleteModel('mistral');
|
|
|
67
62
|
|
|
68
63
|
- `new OllamaClient(baseUrl?: string)` – defaults to `http://localhost:11434`
|
|
69
64
|
- `.listModels(): Promise<string[]>`
|
|
65
|
+
- `.showModel(model: string): Promise<{ capabilities?: string[] } | null>`
|
|
70
66
|
- `.generate(input: GenerateInput, onChunk?: (chunk: string) => void): Promise<string | void>`
|
|
71
|
-
- `.
|
|
72
|
-
- `.generateEmbedding(text: string): Promise<number[]>`
|
|
73
|
-
- `.generateResponse(prompt: string, context?: string): Promise<string>`
|
|
67
|
+
- `.generateEmbedding(text: string, model?: string): Promise<number[]>` — defaults to `nomic-embed-text`
|
|
74
68
|
- `.pullModel(model: string): Promise<void>`
|
|
75
69
|
- `.deleteModel(model: string): Promise<void>`
|
|
76
70
|
|
|
71
|
+
## Provider Adapter
|
|
72
|
+
|
|
73
|
+
```typescript
|
|
74
|
+
import { OllamaAdapter } from '@agentic-kit/ollama';
|
|
75
|
+
|
|
76
|
+
const provider = new OllamaAdapter('http://localhost:11434');
|
|
77
|
+
const model = provider.createModel('llama3');
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Local Live Tests
|
|
81
|
+
|
|
82
|
+
The package includes a local-only live lane that never talks to hosted
|
|
83
|
+
providers.
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
OLLAMA_LIVE_MODEL=qwen3.5:4b pnpm --filter @agentic-kit/ollama test:live
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
That default command runs the fast smoke tier. Run the broader suite explicitly
|
|
90
|
+
when you want slower behavioral coverage:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
OLLAMA_LIVE_MODEL=qwen3.5:4b pnpm --filter @agentic-kit/ollama test:live:extended
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Notes:
|
|
97
|
+
|
|
98
|
+
- The preflight checks `OLLAMA_BASE_URL` first and defaults to `http://127.0.0.1:11434`.
|
|
99
|
+
- The default live model is `qwen3.5:4b`; override `OLLAMA_LIVE_MODEL` only if you want a different local model.
|
|
100
|
+
- If `nomic-embed-text:latest` is installed, the live lane also covers local embeddings. Override it with `OLLAMA_LIVE_EMBED_MODEL` if needed.
|
|
101
|
+
- `smoke` covers fast adapter invariants; `extended` runs the smoke tier plus slower behavioral checks such as reasoning metadata, legacy generate, short multi-turn context, and embeddings.
|
|
102
|
+
- If Ollama is not running, or the configured model is not installed, the live
|
|
103
|
+
script exits cleanly with a skip message.
|
|
104
|
+
- Normal `pnpm test` runs do not include the live lane.
|
|
105
|
+
|
|
77
106
|
## GenerateInput type
|
|
78
107
|
|
|
79
108
|
```ts
|
|
80
109
|
interface GenerateInput {
|
|
81
110
|
model: string;
|
|
82
|
-
prompt
|
|
111
|
+
prompt?: string;
|
|
112
|
+
messages?: ChatMessage[];
|
|
113
|
+
system?: string;
|
|
83
114
|
stream?: boolean;
|
|
115
|
+
temperature?: number;
|
|
116
|
+
maxTokens?: number;
|
|
84
117
|
}
|
|
85
118
|
```
|
|
86
119
|
|
|
120
|
+
Either `prompt` (single-turn) or `messages` (multi-turn) must be set.
|
|
121
|
+
|
|
87
122
|
## Contributing
|
|
88
123
|
|
|
89
124
|
Please open issues or pull requests on [GitHub](https://github.com/constructive-io/agentic-kit).
|
package/esm/index.js
CHANGED
|
@@ -1,139 +1,488 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
const fetch = globalThis.fetch.bind(globalThis);
|
|
2
|
+
class EventStream {
|
|
3
|
+
isTerminal;
|
|
4
|
+
extractResult;
|
|
5
|
+
queue = [];
|
|
6
|
+
waiting = [];
|
|
7
|
+
done = false;
|
|
8
|
+
finalResultPromise;
|
|
9
|
+
resolveFinalResult;
|
|
10
|
+
constructor(isTerminal, extractResult) {
|
|
11
|
+
this.isTerminal = isTerminal;
|
|
12
|
+
this.extractResult = extractResult;
|
|
13
|
+
this.finalResultPromise = new Promise((resolve) => {
|
|
14
|
+
this.resolveFinalResult = resolve;
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
push(event) {
|
|
18
|
+
if (this.done) {
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
if (this.isTerminal(event)) {
|
|
22
|
+
this.done = true;
|
|
23
|
+
this.resolveFinalResult(this.extractResult(event));
|
|
24
|
+
}
|
|
25
|
+
const waiter = this.waiting.shift();
|
|
26
|
+
if (waiter) {
|
|
27
|
+
waiter({ value: event, done: false });
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
this.queue.push(event);
|
|
31
|
+
}
|
|
32
|
+
end(result) {
|
|
33
|
+
this.done = true;
|
|
34
|
+
if (result !== undefined) {
|
|
35
|
+
this.resolveFinalResult(result);
|
|
36
|
+
}
|
|
37
|
+
while (this.waiting.length > 0) {
|
|
38
|
+
this.waiting.shift()({ value: undefined, done: true });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async *[Symbol.asyncIterator]() {
|
|
42
|
+
while (true) {
|
|
43
|
+
if (this.queue.length > 0) {
|
|
44
|
+
yield this.queue.shift();
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (this.done) {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const next = await new Promise((resolve) => {
|
|
51
|
+
this.waiting.push(resolve);
|
|
52
|
+
});
|
|
53
|
+
if (next.done) {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
yield next.value;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
result() {
|
|
60
|
+
return this.finalResultPromise;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
class DefaultAssistantMessageEventStream extends EventStream {
|
|
64
|
+
constructor() {
|
|
65
|
+
super((event) => event.type === 'done' || event.type === 'error', (event) => {
|
|
66
|
+
if (event.type === 'done') {
|
|
67
|
+
return event.message;
|
|
68
|
+
}
|
|
69
|
+
if (event.type === 'error') {
|
|
70
|
+
return event.error;
|
|
71
|
+
}
|
|
72
|
+
throw new Error('Unexpected terminal event');
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export const OLLAMA_MODELS = [];
|
|
77
|
+
export class OllamaClient {
|
|
4
78
|
baseUrl;
|
|
5
79
|
constructor(baseUrl = 'http://localhost:11434') {
|
|
6
80
|
this.baseUrl = baseUrl;
|
|
7
81
|
}
|
|
8
|
-
// ── Models ──────────────────────────────────────────────────────────────────
|
|
9
82
|
async listModels() {
|
|
10
|
-
const
|
|
11
|
-
if (!
|
|
12
|
-
throw new Error(`listModels failed: ${
|
|
83
|
+
const response = await fetch(`${this.baseUrl}/api/tags`);
|
|
84
|
+
if (!response.ok) {
|
|
85
|
+
throw new Error(`listModels failed: ${response.status} ${response.statusText}`);
|
|
13
86
|
}
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
87
|
+
const payload = (await response.json());
|
|
88
|
+
return payload.models?.map((model) => model.name) ?? [];
|
|
89
|
+
}
|
|
90
|
+
async showModel(model) {
|
|
91
|
+
const response = await fetch(`${this.baseUrl}/api/show`, {
|
|
92
|
+
method: 'POST',
|
|
93
|
+
headers: { 'Content-Type': 'application/json' },
|
|
94
|
+
body: JSON.stringify({ model }),
|
|
95
|
+
});
|
|
96
|
+
if (!response.ok)
|
|
97
|
+
return null;
|
|
98
|
+
return (await response.json());
|
|
20
99
|
}
|
|
21
100
|
async pullModel(model) {
|
|
22
|
-
const
|
|
101
|
+
const response = await fetch(`${this.baseUrl}/api/pull`, {
|
|
23
102
|
method: 'POST',
|
|
24
103
|
headers: { 'Content-Type': 'application/json' },
|
|
25
104
|
body: JSON.stringify({ name: model }),
|
|
26
105
|
});
|
|
27
|
-
if (!
|
|
28
|
-
throw new Error(`pullModel failed: ${
|
|
106
|
+
if (!response.ok) {
|
|
107
|
+
throw new Error(`pullModel failed: ${response.status} ${response.statusText}`);
|
|
29
108
|
}
|
|
30
109
|
}
|
|
31
110
|
async deleteModel(model) {
|
|
32
|
-
const
|
|
111
|
+
const response = await fetch(`${this.baseUrl}/api/delete`, {
|
|
33
112
|
method: 'DELETE',
|
|
34
113
|
headers: { 'Content-Type': 'application/json' },
|
|
35
114
|
body: JSON.stringify({ name: model }),
|
|
36
115
|
});
|
|
37
|
-
if (!
|
|
38
|
-
throw new Error(`deleteModel failed: ${
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
async generate(input, onChunk) {
|
|
42
|
-
if (input.messages) {
|
|
43
|
-
return this._chat(input, onChunk);
|
|
116
|
+
if (!response.ok) {
|
|
117
|
+
throw new Error(`deleteModel failed: ${response.status} ${response.statusText}`);
|
|
44
118
|
}
|
|
45
|
-
return this._generate(input, onChunk);
|
|
46
119
|
}
|
|
47
|
-
// ── Embeddings ──────────────────────────────────────────────────────────────
|
|
48
120
|
async generateEmbedding(text, model = 'nomic-embed-text') {
|
|
49
|
-
const
|
|
121
|
+
const response = await fetch(`${this.baseUrl}/api/embeddings`, {
|
|
50
122
|
method: 'POST',
|
|
51
123
|
headers: { 'Content-Type': 'application/json' },
|
|
52
124
|
body: JSON.stringify({ model, prompt: text }),
|
|
53
125
|
});
|
|
54
|
-
if (!
|
|
55
|
-
throw new Error(`generateEmbedding failed: ${
|
|
126
|
+
if (!response.ok) {
|
|
127
|
+
throw new Error(`generateEmbedding failed: ${response.status} ${response.statusText}`);
|
|
56
128
|
}
|
|
57
|
-
const
|
|
58
|
-
return
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
129
|
+
const payload = (await response.json());
|
|
130
|
+
return payload.embedding;
|
|
131
|
+
}
|
|
132
|
+
async generate(input, onChunk) {
|
|
133
|
+
const context = legacyInputToContext(input);
|
|
134
|
+
const model = {
|
|
135
|
+
id: input.model,
|
|
136
|
+
name: input.model,
|
|
137
|
+
api: 'ollama-native',
|
|
138
|
+
provider: 'ollama',
|
|
139
|
+
baseUrl: this.baseUrl,
|
|
140
|
+
input: ['text', 'image'],
|
|
141
|
+
reasoning: false,
|
|
142
|
+
tools: false,
|
|
143
|
+
maxOutputTokens: input.maxTokens,
|
|
66
144
|
};
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
method: 'POST',
|
|
73
|
-
headers: { 'Content-Type': 'application/json' },
|
|
74
|
-
body: JSON.stringify(body),
|
|
145
|
+
const adapter = new OllamaAdapter(this.baseUrl);
|
|
146
|
+
const response = adapter.stream(model, context, {
|
|
147
|
+
maxTokens: input.maxTokens,
|
|
148
|
+
signal: undefined,
|
|
149
|
+
temperature: input.temperature,
|
|
75
150
|
});
|
|
76
|
-
if (
|
|
77
|
-
|
|
78
|
-
|
|
151
|
+
if (onChunk || input.stream) {
|
|
152
|
+
for await (const event of response) {
|
|
153
|
+
if (event.type === 'text_delta') {
|
|
154
|
+
onChunk?.(event.delta);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return;
|
|
79
158
|
}
|
|
80
|
-
|
|
81
|
-
|
|
159
|
+
const message = await response.result();
|
|
160
|
+
return message.content
|
|
161
|
+
.filter((block) => block.type === 'text')
|
|
162
|
+
.map((block) => block.text)
|
|
163
|
+
.join('');
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
export class OllamaAdapter {
|
|
167
|
+
api = 'ollama-native';
|
|
168
|
+
provider = 'ollama';
|
|
169
|
+
name = 'ollama';
|
|
170
|
+
client;
|
|
171
|
+
baseUrl;
|
|
172
|
+
constructor(baseUrl) {
|
|
173
|
+
this.baseUrl = baseUrl ?? 'http://localhost:11434';
|
|
174
|
+
this.client = new OllamaClient(this.baseUrl);
|
|
175
|
+
}
|
|
176
|
+
createModel(modelId, overrides) {
|
|
177
|
+
return {
|
|
178
|
+
id: modelId,
|
|
179
|
+
name: modelId,
|
|
180
|
+
api: this.api,
|
|
181
|
+
provider: this.provider,
|
|
182
|
+
baseUrl: this.baseUrl,
|
|
183
|
+
input: ['text', 'image'],
|
|
184
|
+
reasoning: false,
|
|
185
|
+
tools: false,
|
|
186
|
+
...overrides,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
async listModels() {
|
|
190
|
+
return this.client.listModels();
|
|
191
|
+
}
|
|
192
|
+
stream(model, context, options) {
|
|
193
|
+
const stream = new DefaultAssistantMessageEventStream();
|
|
194
|
+
const output = createAssistantMessage(model);
|
|
195
|
+
void (async () => {
|
|
196
|
+
const body = {
|
|
197
|
+
model: model.id,
|
|
198
|
+
stream: true,
|
|
199
|
+
messages: toOllamaMessages(context),
|
|
200
|
+
options: {
|
|
201
|
+
temperature: options?.temperature,
|
|
202
|
+
num_predict: options?.maxTokens,
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
if (model.reasoning)
|
|
206
|
+
body.think = true;
|
|
207
|
+
try {
|
|
208
|
+
const response = await fetch(`${model.baseUrl}/api/chat`, {
|
|
209
|
+
method: 'POST',
|
|
210
|
+
headers: { 'Content-Type': 'application/json' },
|
|
211
|
+
body: JSON.stringify(body),
|
|
212
|
+
signal: options?.signal,
|
|
213
|
+
});
|
|
214
|
+
if (!response.ok) {
|
|
215
|
+
const text = await response.text().catch(() => '');
|
|
216
|
+
throw new Error(`Ollama error ${response.status}: ${text}`);
|
|
217
|
+
}
|
|
218
|
+
stream.push({ type: 'start', partial: clone(output) });
|
|
219
|
+
if (!response.body) {
|
|
220
|
+
throw new Error('No response body');
|
|
221
|
+
}
|
|
222
|
+
const decoder = new TextDecoder();
|
|
223
|
+
let buffer = '';
|
|
224
|
+
let textIndex;
|
|
225
|
+
let thinkingIndex;
|
|
226
|
+
let finished = false;
|
|
227
|
+
const processPayload = (payload) => {
|
|
228
|
+
const thinking = payload.message?.thinking ?? '';
|
|
229
|
+
if (thinking) {
|
|
230
|
+
if (thinkingIndex === undefined) {
|
|
231
|
+
thinkingIndex = output.content.push({ type: 'thinking', thinking: '' }) - 1;
|
|
232
|
+
stream.push({
|
|
233
|
+
type: 'thinking_start',
|
|
234
|
+
contentIndex: thinkingIndex,
|
|
235
|
+
partial: clone(output),
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
const block = output.content[thinkingIndex];
|
|
239
|
+
block.thinking += thinking;
|
|
240
|
+
stream.push({
|
|
241
|
+
type: 'thinking_delta',
|
|
242
|
+
contentIndex: thinkingIndex,
|
|
243
|
+
delta: thinking,
|
|
244
|
+
partial: clone(output),
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
const text = payload.message?.content ?? payload.response ?? '';
|
|
248
|
+
if (text) {
|
|
249
|
+
if (textIndex === undefined) {
|
|
250
|
+
textIndex = output.content.push({ type: 'text', text: '' }) - 1;
|
|
251
|
+
stream.push({ type: 'text_start', contentIndex: textIndex, partial: clone(output) });
|
|
252
|
+
}
|
|
253
|
+
const block = output.content[textIndex];
|
|
254
|
+
block.text += text;
|
|
255
|
+
stream.push({
|
|
256
|
+
type: 'text_delta',
|
|
257
|
+
contentIndex: textIndex,
|
|
258
|
+
delta: text,
|
|
259
|
+
partial: clone(output),
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
if (!payload.done) {
|
|
263
|
+
return false;
|
|
264
|
+
}
|
|
265
|
+
output.usage.input = payload.prompt_eval_count ?? output.usage.input;
|
|
266
|
+
output.usage.output = payload.eval_count ?? output.usage.output;
|
|
267
|
+
output.usage.totalTokens = output.usage.input + output.usage.output;
|
|
268
|
+
calculateUsageCost(model, output.usage);
|
|
269
|
+
output.stopReason = payload.done_reason === 'length' ? 'length' : 'stop';
|
|
270
|
+
if (thinkingIndex !== undefined) {
|
|
271
|
+
stream.push({
|
|
272
|
+
type: 'thinking_end',
|
|
273
|
+
contentIndex: thinkingIndex,
|
|
274
|
+
content: output.content[thinkingIndex].thinking,
|
|
275
|
+
partial: clone(output),
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
if (textIndex !== undefined) {
|
|
279
|
+
stream.push({
|
|
280
|
+
type: 'text_end',
|
|
281
|
+
contentIndex: textIndex,
|
|
282
|
+
content: output.content[textIndex].text,
|
|
283
|
+
partial: clone(output),
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
stream.push({
|
|
287
|
+
type: 'done',
|
|
288
|
+
reason: output.stopReason === 'length' ? 'length' : 'stop',
|
|
289
|
+
message: clone(output),
|
|
290
|
+
});
|
|
291
|
+
stream.end(output);
|
|
292
|
+
finished = true;
|
|
293
|
+
return true;
|
|
294
|
+
};
|
|
295
|
+
for await (const chunk of iterateResponseBody(response.body)) {
|
|
296
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
297
|
+
const lines = buffer.split('\n');
|
|
298
|
+
buffer = lines.pop() ?? '';
|
|
299
|
+
for (const line of lines) {
|
|
300
|
+
const trimmed = line.trim();
|
|
301
|
+
if (!trimmed) {
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
const payload = JSON.parse(trimmed);
|
|
305
|
+
if (processPayload(payload)) {
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
const trailing = buffer.trim();
|
|
311
|
+
if (!finished && trailing) {
|
|
312
|
+
const payload = JSON.parse(trailing);
|
|
313
|
+
if (processPayload(payload)) {
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
if (thinkingIndex !== undefined) {
|
|
318
|
+
stream.push({
|
|
319
|
+
type: 'thinking_end',
|
|
320
|
+
contentIndex: thinkingIndex,
|
|
321
|
+
content: output.content[thinkingIndex].thinking,
|
|
322
|
+
partial: clone(output),
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
if (textIndex !== undefined) {
|
|
326
|
+
stream.push({
|
|
327
|
+
type: 'text_end',
|
|
328
|
+
contentIndex: textIndex,
|
|
329
|
+
content: output.content[textIndex].text,
|
|
330
|
+
partial: clone(output),
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
stream.push({
|
|
334
|
+
type: 'done',
|
|
335
|
+
reason: output.stopReason === 'length' ? 'length' : 'stop',
|
|
336
|
+
message: clone(output),
|
|
337
|
+
});
|
|
338
|
+
stream.end(output);
|
|
339
|
+
}
|
|
340
|
+
catch (error) {
|
|
341
|
+
output.stopReason = options?.signal?.aborted ? 'aborted' : 'error';
|
|
342
|
+
output.errorMessage = error instanceof Error ? error.message : String(error);
|
|
343
|
+
stream.push({
|
|
344
|
+
type: 'error',
|
|
345
|
+
reason: output.stopReason === 'aborted' ? 'aborted' : 'error',
|
|
346
|
+
error: clone(output),
|
|
347
|
+
});
|
|
348
|
+
stream.end(output);
|
|
349
|
+
}
|
|
350
|
+
})();
|
|
351
|
+
return stream;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
function toOllamaMessages(context) {
|
|
355
|
+
const messages = context.messages.map((message) => {
|
|
356
|
+
if (message.role === 'user') {
|
|
357
|
+
if (typeof message.content === 'string') {
|
|
358
|
+
return { role: 'user', content: message.content };
|
|
359
|
+
}
|
|
360
|
+
return {
|
|
361
|
+
role: 'user',
|
|
362
|
+
content: message.content
|
|
363
|
+
.filter((block) => block.type === 'text')
|
|
364
|
+
.map((block) => block.text)
|
|
365
|
+
.join('\n'),
|
|
366
|
+
images: message.content
|
|
367
|
+
.filter((block) => block.type === 'image')
|
|
368
|
+
.map((block) => block.data),
|
|
369
|
+
};
|
|
82
370
|
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
messages.push({ role: 'system', content: input.system });
|
|
371
|
+
if (message.role === 'toolResult') {
|
|
372
|
+
return {
|
|
373
|
+
role: 'user',
|
|
374
|
+
content: message.content
|
|
375
|
+
.map((block) => block.type === 'text' ? block.text : `[image:${block.mimeType};bytes=${block.data.length}]`)
|
|
376
|
+
.join('\n'),
|
|
377
|
+
};
|
|
91
378
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
379
|
+
return {
|
|
380
|
+
role: 'assistant',
|
|
381
|
+
content: message.content
|
|
382
|
+
.map((block) => {
|
|
383
|
+
if (block.type === 'text') {
|
|
384
|
+
return block.text;
|
|
385
|
+
}
|
|
386
|
+
if (block.type === 'thinking') {
|
|
387
|
+
return `<thinking>${block.thinking}</thinking>`;
|
|
388
|
+
}
|
|
389
|
+
return `<tool-call name="${block.name}">${JSON.stringify(block.arguments)}</tool-call>`;
|
|
390
|
+
})
|
|
391
|
+
.join('\n'),
|
|
97
392
|
};
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
body: JSON.stringify(body),
|
|
393
|
+
});
|
|
394
|
+
if (context.systemPrompt) {
|
|
395
|
+
messages.unshift({
|
|
396
|
+
role: 'system',
|
|
397
|
+
content: context.systemPrompt,
|
|
104
398
|
});
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
399
|
+
}
|
|
400
|
+
return messages;
|
|
401
|
+
}
|
|
402
|
+
function createAssistantMessage(model) {
|
|
403
|
+
return {
|
|
404
|
+
role: 'assistant',
|
|
405
|
+
api: model.api,
|
|
406
|
+
provider: model.provider,
|
|
407
|
+
model: model.id,
|
|
408
|
+
content: [],
|
|
409
|
+
usage: {
|
|
410
|
+
input: 0,
|
|
411
|
+
output: 0,
|
|
412
|
+
reasoning: 0,
|
|
413
|
+
cacheRead: 0,
|
|
414
|
+
cacheWrite: 0,
|
|
415
|
+
totalTokens: 0,
|
|
416
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
417
|
+
},
|
|
418
|
+
stopReason: 'stop',
|
|
419
|
+
timestamp: Date.now(),
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
function calculateUsageCost(model, usage) {
|
|
423
|
+
usage.cost.input = ((model.cost?.input ?? 0) / 1_000_000) * usage.input;
|
|
424
|
+
usage.cost.output = ((model.cost?.output ?? 0) / 1_000_000) * usage.output;
|
|
425
|
+
usage.cost.cacheRead = ((model.cost?.cacheRead ?? 0) / 1_000_000) * usage.cacheRead;
|
|
426
|
+
usage.cost.cacheWrite = ((model.cost?.cacheWrite ?? 0) / 1_000_000) * usage.cacheWrite;
|
|
427
|
+
usage.cost.total =
|
|
428
|
+
usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
|
|
429
|
+
}
|
|
430
|
+
function legacyInputToContext(input) {
|
|
431
|
+
const messages = input.messages
|
|
432
|
+
? input.messages
|
|
433
|
+
.filter((message) => message.role !== 'system')
|
|
434
|
+
.map((message) => message.role === 'assistant'
|
|
435
|
+
? {
|
|
436
|
+
role: 'assistant',
|
|
437
|
+
api: 'ollama-native',
|
|
438
|
+
provider: 'ollama',
|
|
439
|
+
model: input.model,
|
|
440
|
+
content: [{ type: 'text', text: message.content }],
|
|
441
|
+
usage: {
|
|
442
|
+
input: 0,
|
|
443
|
+
output: 0,
|
|
444
|
+
reasoning: 0,
|
|
445
|
+
cacheRead: 0,
|
|
446
|
+
cacheWrite: 0,
|
|
447
|
+
totalTokens: 0,
|
|
448
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
449
|
+
},
|
|
450
|
+
stopReason: 'stop',
|
|
451
|
+
timestamp: Date.now(),
|
|
452
|
+
}
|
|
453
|
+
: {
|
|
454
|
+
role: 'user',
|
|
455
|
+
content: message.content,
|
|
456
|
+
timestamp: Date.now(),
|
|
457
|
+
})
|
|
458
|
+
: [{ role: 'user', content: input.prompt ?? '', timestamp: Date.now() }];
|
|
459
|
+
return {
|
|
460
|
+
systemPrompt: input.system ?? input.messages?.find((message) => message.role === 'system')?.content,
|
|
461
|
+
messages,
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
function clone(value) {
|
|
465
|
+
return JSON.parse(JSON.stringify(value));
|
|
466
|
+
}
|
|
467
|
+
async function* iterateResponseBody(body) {
|
|
468
|
+
if ('getReader' in body && typeof body.getReader === 'function') {
|
|
469
|
+
const reader = body.getReader();
|
|
121
470
|
while (true) {
|
|
122
471
|
const { done, value } = await reader.read();
|
|
123
|
-
if (done)
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
const data = JSON.parse(line);
|
|
129
|
-
const chunk = extract(data);
|
|
130
|
-
if (chunk)
|
|
131
|
-
onChunk(chunk);
|
|
132
|
-
}
|
|
133
|
-
catch {
|
|
134
|
-
// partial line — skip
|
|
135
|
-
}
|
|
472
|
+
if (done) {
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
if (value) {
|
|
476
|
+
yield value;
|
|
136
477
|
}
|
|
137
478
|
}
|
|
138
479
|
}
|
|
480
|
+
for await (const chunk of body) {
|
|
481
|
+
if (typeof chunk === 'string') {
|
|
482
|
+
yield new TextEncoder().encode(chunk);
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
yield chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
|
|
486
|
+
}
|
|
139
487
|
}
|
|
488
|
+
export default OllamaClient;
|
package/esm/package.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"module"}
|