@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/LICENSE +22 -0
- package/README.md +83 -12
- package/esm/index.js +477 -0
- package/esm/package.json +1 -0
- package/index.d.ts +182 -0
- package/index.js +482 -0
- package/package.json +14 -4
- package/CHANGELOG.md +0 -28
- package/__tests__/first.test.ts +0 -188
- package/dist/README.md +0 -123
- package/dist/esm/index.js +0 -139
- package/dist/index.d.ts +0 -29
- package/dist/index.js +0 -145
- package/dist/package.json +0 -34
- package/jest.config.js +0 -19
- package/jest.setup.js +0 -4
- package/src/index.ts +0 -224
- package/tsconfig.esm.json +0 -9
- package/tsconfig.json +0 -9
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
|
|
4
|
+
Copyright (c) 2025 Constructive <developers@constructive.io>
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
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
|
|
|
@@ -20,6 +22,7 @@ A JavaScript/TypeScript client for the Ollama LLM server, supporting model listi
|
|
|
20
22
|
npm install @agentic-kit/ollama
|
|
21
23
|
```
|
|
22
24
|
|
|
25
|
+
|
|
23
26
|
## Usage
|
|
24
27
|
|
|
25
28
|
```typescript
|
|
@@ -51,13 +54,6 @@ await client.pullModel('mistral');
|
|
|
51
54
|
const embedding = await client.generateEmbedding('Compute embeddings');
|
|
52
55
|
console.log('Embedding vector length:', embedding.length);
|
|
53
56
|
|
|
54
|
-
// Generate a conversational response with context
|
|
55
|
-
const response = await client.generateResponse(
|
|
56
|
-
'What is the capital of France?',
|
|
57
|
-
'Geography trivia'
|
|
58
|
-
);
|
|
59
|
-
console.log(response);
|
|
60
|
-
|
|
61
57
|
// Delete a pulled model when done
|
|
62
58
|
await client.deleteModel('mistral');
|
|
63
59
|
```
|
|
@@ -66,23 +62,98 @@ await client.deleteModel('mistral');
|
|
|
66
62
|
|
|
67
63
|
- `new OllamaClient(baseUrl?: string)` – defaults to `http://localhost:11434`
|
|
68
64
|
- `.listModels(): Promise<string[]>`
|
|
65
|
+
- `.showModel(model: string): Promise<{ capabilities?: string[] } | null>`
|
|
69
66
|
- `.generate(input: GenerateInput, onChunk?: (chunk: string) => void): Promise<string | void>`
|
|
70
|
-
- `.
|
|
71
|
-
- `.generateEmbedding(text: string): Promise<number[]>`
|
|
72
|
-
- `.generateResponse(prompt: string, context?: string): Promise<string>`
|
|
67
|
+
- `.generateEmbedding(text: string, model?: string): Promise<number[]>` — defaults to `nomic-embed-text`
|
|
73
68
|
- `.pullModel(model: string): Promise<void>`
|
|
74
69
|
- `.deleteModel(model: string): Promise<void>`
|
|
75
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
|
+
|
|
76
106
|
## GenerateInput type
|
|
77
107
|
|
|
78
108
|
```ts
|
|
79
109
|
interface GenerateInput {
|
|
80
110
|
model: string;
|
|
81
|
-
prompt
|
|
111
|
+
prompt?: string;
|
|
112
|
+
messages?: ChatMessage[];
|
|
113
|
+
system?: string;
|
|
82
114
|
stream?: boolean;
|
|
115
|
+
temperature?: number;
|
|
116
|
+
maxTokens?: number;
|
|
83
117
|
}
|
|
84
118
|
```
|
|
85
119
|
|
|
120
|
+
Either `prompt` (single-turn) or `messages` (multi-turn) must be set.
|
|
121
|
+
|
|
86
122
|
## Contributing
|
|
87
123
|
|
|
88
124
|
Please open issues or pull requests on [GitHub](https://github.com/constructive-io/agentic-kit).
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## Related Constructive Tooling
|
|
129
|
+
|
|
130
|
+
### 🤖 AI & Agent Development
|
|
131
|
+
|
|
132
|
+
* [agentic-kit](https://github.com/constructive-io/agentic-kit): **🧰 Provider-agnostic LLM adapter** with streaming and multi-turn support. Swap between Anthropic, OpenAI, Ollama, and any OpenAI-compatible endpoint.
|
|
133
|
+
|
|
134
|
+
### 📦 Package Management
|
|
135
|
+
|
|
136
|
+
* [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
|
|
137
|
+
|
|
138
|
+
### 🧪 Testing
|
|
139
|
+
|
|
140
|
+
* [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
|
|
141
|
+
* [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
|
|
142
|
+
* [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
|
|
143
|
+
|
|
144
|
+
### 🧠 Parsing & AST
|
|
145
|
+
|
|
146
|
+
* [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
|
|
147
|
+
* [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
|
|
148
|
+
* [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
|
|
149
|
+
* [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
|
|
150
|
+
|
|
151
|
+
## Credits
|
|
152
|
+
|
|
153
|
+
**🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
|
|
154
|
+
|
|
155
|
+
## Disclaimer
|
|
156
|
+
|
|
157
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
158
|
+
|
|
159
|
+
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
|
package/esm/index.js
ADDED
|
@@ -0,0 +1,477 @@
|
|
|
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 {
|
|
78
|
+
baseUrl;
|
|
79
|
+
constructor(baseUrl = 'http://localhost:11434') {
|
|
80
|
+
this.baseUrl = baseUrl;
|
|
81
|
+
}
|
|
82
|
+
async listModels() {
|
|
83
|
+
const response = await fetch(`${this.baseUrl}/api/tags`);
|
|
84
|
+
if (!response.ok) {
|
|
85
|
+
throw new Error(`listModels failed: ${response.status} ${response.statusText}`);
|
|
86
|
+
}
|
|
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());
|
|
99
|
+
}
|
|
100
|
+
async pullModel(model) {
|
|
101
|
+
const response = await fetch(`${this.baseUrl}/api/pull`, {
|
|
102
|
+
method: 'POST',
|
|
103
|
+
headers: { 'Content-Type': 'application/json' },
|
|
104
|
+
body: JSON.stringify({ name: model }),
|
|
105
|
+
});
|
|
106
|
+
if (!response.ok) {
|
|
107
|
+
throw new Error(`pullModel failed: ${response.status} ${response.statusText}`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async deleteModel(model) {
|
|
111
|
+
const response = await fetch(`${this.baseUrl}/api/delete`, {
|
|
112
|
+
method: 'DELETE',
|
|
113
|
+
headers: { 'Content-Type': 'application/json' },
|
|
114
|
+
body: JSON.stringify({ name: model }),
|
|
115
|
+
});
|
|
116
|
+
if (!response.ok) {
|
|
117
|
+
throw new Error(`deleteModel failed: ${response.status} ${response.statusText}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
async generateEmbedding(text, model = 'nomic-embed-text') {
|
|
121
|
+
const response = await fetch(`${this.baseUrl}/api/embeddings`, {
|
|
122
|
+
method: 'POST',
|
|
123
|
+
headers: { 'Content-Type': 'application/json' },
|
|
124
|
+
body: JSON.stringify({ model, prompt: text }),
|
|
125
|
+
});
|
|
126
|
+
if (!response.ok) {
|
|
127
|
+
throw new Error(`generateEmbedding failed: ${response.status} ${response.statusText}`);
|
|
128
|
+
}
|
|
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,
|
|
144
|
+
};
|
|
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,
|
|
150
|
+
});
|
|
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;
|
|
158
|
+
}
|
|
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
|
+
output.stopReason = payload.done_reason === 'length' ? 'length' : 'stop';
|
|
269
|
+
if (thinkingIndex !== undefined) {
|
|
270
|
+
stream.push({
|
|
271
|
+
type: 'thinking_end',
|
|
272
|
+
contentIndex: thinkingIndex,
|
|
273
|
+
content: output.content[thinkingIndex].thinking,
|
|
274
|
+
partial: clone(output),
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
if (textIndex !== undefined) {
|
|
278
|
+
stream.push({
|
|
279
|
+
type: 'text_end',
|
|
280
|
+
contentIndex: textIndex,
|
|
281
|
+
content: output.content[textIndex].text,
|
|
282
|
+
partial: clone(output),
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
stream.push({
|
|
286
|
+
type: 'done',
|
|
287
|
+
reason: output.stopReason === 'length' ? 'length' : 'stop',
|
|
288
|
+
message: clone(output),
|
|
289
|
+
});
|
|
290
|
+
stream.end(output);
|
|
291
|
+
finished = true;
|
|
292
|
+
return true;
|
|
293
|
+
};
|
|
294
|
+
for await (const chunk of iterateResponseBody(response.body)) {
|
|
295
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
296
|
+
const lines = buffer.split('\n');
|
|
297
|
+
buffer = lines.pop() ?? '';
|
|
298
|
+
for (const line of lines) {
|
|
299
|
+
const trimmed = line.trim();
|
|
300
|
+
if (!trimmed) {
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
const payload = JSON.parse(trimmed);
|
|
304
|
+
if (processPayload(payload)) {
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
const trailing = buffer.trim();
|
|
310
|
+
if (!finished && trailing) {
|
|
311
|
+
const payload = JSON.parse(trailing);
|
|
312
|
+
if (processPayload(payload)) {
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
if (thinkingIndex !== undefined) {
|
|
317
|
+
stream.push({
|
|
318
|
+
type: 'thinking_end',
|
|
319
|
+
contentIndex: thinkingIndex,
|
|
320
|
+
content: output.content[thinkingIndex].thinking,
|
|
321
|
+
partial: clone(output),
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
if (textIndex !== undefined) {
|
|
325
|
+
stream.push({
|
|
326
|
+
type: 'text_end',
|
|
327
|
+
contentIndex: textIndex,
|
|
328
|
+
content: output.content[textIndex].text,
|
|
329
|
+
partial: clone(output),
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
stream.push({
|
|
333
|
+
type: 'done',
|
|
334
|
+
reason: output.stopReason === 'length' ? 'length' : 'stop',
|
|
335
|
+
message: clone(output),
|
|
336
|
+
});
|
|
337
|
+
stream.end(output);
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
output.stopReason = options?.signal?.aborted ? 'aborted' : 'error';
|
|
341
|
+
output.errorMessage = error instanceof Error ? error.message : String(error);
|
|
342
|
+
stream.push({
|
|
343
|
+
type: 'error',
|
|
344
|
+
reason: output.stopReason === 'aborted' ? 'aborted' : 'error',
|
|
345
|
+
error: clone(output),
|
|
346
|
+
});
|
|
347
|
+
stream.end(output);
|
|
348
|
+
}
|
|
349
|
+
})();
|
|
350
|
+
return stream;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
function toOllamaMessages(context) {
|
|
354
|
+
const messages = context.messages.map((message) => {
|
|
355
|
+
if (message.role === 'user') {
|
|
356
|
+
if (typeof message.content === 'string') {
|
|
357
|
+
return { role: 'user', content: message.content };
|
|
358
|
+
}
|
|
359
|
+
return {
|
|
360
|
+
role: 'user',
|
|
361
|
+
content: message.content
|
|
362
|
+
.filter((block) => block.type === 'text')
|
|
363
|
+
.map((block) => block.text)
|
|
364
|
+
.join('\n'),
|
|
365
|
+
images: message.content
|
|
366
|
+
.filter((block) => block.type === 'image')
|
|
367
|
+
.map((block) => block.data),
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
if (message.role === 'toolResult') {
|
|
371
|
+
return {
|
|
372
|
+
role: 'user',
|
|
373
|
+
content: message.content
|
|
374
|
+
.map((block) => block.type === 'text' ? block.text : `[image:${block.mimeType};bytes=${block.data.length}]`)
|
|
375
|
+
.join('\n'),
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
return {
|
|
379
|
+
role: 'assistant',
|
|
380
|
+
content: message.content
|
|
381
|
+
.map((block) => {
|
|
382
|
+
if (block.type === 'text') {
|
|
383
|
+
return block.text;
|
|
384
|
+
}
|
|
385
|
+
if (block.type === 'thinking') {
|
|
386
|
+
return `<thinking>${block.thinking}</thinking>`;
|
|
387
|
+
}
|
|
388
|
+
return `<tool-call name="${block.name}">${JSON.stringify(block.arguments)}</tool-call>`;
|
|
389
|
+
})
|
|
390
|
+
.join('\n'),
|
|
391
|
+
};
|
|
392
|
+
});
|
|
393
|
+
if (context.systemPrompt) {
|
|
394
|
+
messages.unshift({
|
|
395
|
+
role: 'system',
|
|
396
|
+
content: context.systemPrompt,
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
return messages;
|
|
400
|
+
}
|
|
401
|
+
function createAssistantMessage(model) {
|
|
402
|
+
return {
|
|
403
|
+
role: 'assistant',
|
|
404
|
+
api: model.api,
|
|
405
|
+
provider: model.provider,
|
|
406
|
+
model: model.id,
|
|
407
|
+
content: [],
|
|
408
|
+
usage: {
|
|
409
|
+
input: 0,
|
|
410
|
+
output: 0,
|
|
411
|
+
cacheRead: 0,
|
|
412
|
+
cacheWrite: 0,
|
|
413
|
+
totalTokens: 0,
|
|
414
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
415
|
+
},
|
|
416
|
+
stopReason: 'stop',
|
|
417
|
+
timestamp: Date.now(),
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
function legacyInputToContext(input) {
|
|
421
|
+
const messages = input.messages
|
|
422
|
+
? input.messages
|
|
423
|
+
.filter((message) => message.role !== 'system')
|
|
424
|
+
.map((message) => message.role === 'assistant'
|
|
425
|
+
? {
|
|
426
|
+
role: 'assistant',
|
|
427
|
+
api: 'ollama-native',
|
|
428
|
+
provider: 'ollama',
|
|
429
|
+
model: input.model,
|
|
430
|
+
content: [{ type: 'text', text: message.content }],
|
|
431
|
+
usage: {
|
|
432
|
+
input: 0,
|
|
433
|
+
output: 0,
|
|
434
|
+
cacheRead: 0,
|
|
435
|
+
cacheWrite: 0,
|
|
436
|
+
totalTokens: 0,
|
|
437
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
438
|
+
},
|
|
439
|
+
stopReason: 'stop',
|
|
440
|
+
timestamp: Date.now(),
|
|
441
|
+
}
|
|
442
|
+
: {
|
|
443
|
+
role: 'user',
|
|
444
|
+
content: message.content,
|
|
445
|
+
timestamp: Date.now(),
|
|
446
|
+
})
|
|
447
|
+
: [{ role: 'user', content: input.prompt ?? '', timestamp: Date.now() }];
|
|
448
|
+
return {
|
|
449
|
+
systemPrompt: input.system ?? input.messages?.find((message) => message.role === 'system')?.content,
|
|
450
|
+
messages,
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
function clone(value) {
|
|
454
|
+
return JSON.parse(JSON.stringify(value));
|
|
455
|
+
}
|
|
456
|
+
async function* iterateResponseBody(body) {
|
|
457
|
+
if ('getReader' in body && typeof body.getReader === 'function') {
|
|
458
|
+
const reader = body.getReader();
|
|
459
|
+
while (true) {
|
|
460
|
+
const { done, value } = await reader.read();
|
|
461
|
+
if (done) {
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
if (value) {
|
|
465
|
+
yield value;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
for await (const chunk of body) {
|
|
470
|
+
if (typeof chunk === 'string') {
|
|
471
|
+
yield new TextEncoder().encode(chunk);
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
yield chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
export default OllamaClient;
|
package/esm/package.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"module"}
|