@ziro-agent/ollama 0.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 +190 -0
- package/README.md +62 -0
- package/dist/index.cjs +280 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +92 -0
- package/dist/index.d.ts +92 -0
- package/dist/index.js +276 -0
- package/dist/index.js.map +1 -0
- package/package.json +75 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for describing the origin of the Work and
|
|
141
|
+
reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 ZiroAgent Contributors
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# @ziro-agent/ollama
|
|
2
|
+
|
|
3
|
+
Ollama provider for ZiroAgent SDK — run open-weight LLMs locally with
|
|
4
|
+
the same interface as `@ziro-agent/openai` / `@ziro-agent/anthropic`.
|
|
5
|
+
|
|
6
|
+
> **Sovereign pillar primitive.** Part of the v0.1.9 *trust recovery*
|
|
7
|
+
> milestone (RFC 0004). Lets the SDK keep its OSS-first promise: you
|
|
8
|
+
> can build an agent end-to-end without ever sending bytes to a
|
|
9
|
+
> third-party API.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install @ziro-agent/ollama @ziro-agent/agent
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { createAgent, generateText } from '@ziro-agent/agent';
|
|
21
|
+
import { ollama } from '@ziro-agent/ollama';
|
|
22
|
+
|
|
23
|
+
const text = await generateText({
|
|
24
|
+
model: ollama('llama3.1'),
|
|
25
|
+
prompt: 'Explain RAG to a junior engineer.',
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const agent = createAgent({ model: ollama('qwen2.5'), tools: { /* ... */ } });
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
For a remote / containerised daemon:
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { createOllama } from '@ziro-agent/ollama';
|
|
35
|
+
|
|
36
|
+
const ollama = createOllama({
|
|
37
|
+
baseURL: process.env.OLLAMA_BASE_URL ?? 'http://ollama:11434',
|
|
38
|
+
defaultOptions: { num_ctx: 8192, repeat_penalty: 1.1 },
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Budget Guard
|
|
43
|
+
|
|
44
|
+
Local models are free at runtime, so `Budget Guard` reports `$0` and
|
|
45
|
+
`pricingAvailable: true`. `maxUsd` constraints simply never trip
|
|
46
|
+
(instead of being silently disabled). The meaningful local-runtime
|
|
47
|
+
limits keep working exactly as documented:
|
|
48
|
+
|
|
49
|
+
- `maxTokens`
|
|
50
|
+
- `maxLlmCalls`
|
|
51
|
+
- `maxDurationMs`
|
|
52
|
+
- `maxSteps`
|
|
53
|
+
|
|
54
|
+
## Tools
|
|
55
|
+
|
|
56
|
+
Uses Ollama's native function-calling protocol (not the OpenAI compat
|
|
57
|
+
shim — it loses tool-call fidelity on several models). Recommended
|
|
58
|
+
tool-capable models: `llama3.1`, `qwen2.5`, `mistral-nemo`, `gemma3`.
|
|
59
|
+
|
|
60
|
+
## License
|
|
61
|
+
|
|
62
|
+
Apache-2.0 © ZiroAgent
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var core = require('@ziro-agent/core');
|
|
4
|
+
|
|
5
|
+
// src/ollama-chat-model.ts
|
|
6
|
+
|
|
7
|
+
// src/util/ndjson.ts
|
|
8
|
+
async function* parseNDJSON(body) {
|
|
9
|
+
const reader = body.getReader();
|
|
10
|
+
const decoder = new TextDecoder();
|
|
11
|
+
let buffer = "";
|
|
12
|
+
try {
|
|
13
|
+
while (true) {
|
|
14
|
+
const { value, done } = await reader.read();
|
|
15
|
+
if (done) break;
|
|
16
|
+
buffer += decoder.decode(value, { stream: true });
|
|
17
|
+
let nl = buffer.indexOf("\n");
|
|
18
|
+
while (nl !== -1) {
|
|
19
|
+
const line = buffer.slice(0, nl).replace(/\r$/, "").trim();
|
|
20
|
+
buffer = buffer.slice(nl + 1);
|
|
21
|
+
if (line.length > 0) {
|
|
22
|
+
yield JSON.parse(line);
|
|
23
|
+
}
|
|
24
|
+
nl = buffer.indexOf("\n");
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const tail = buffer.trim();
|
|
28
|
+
if (tail.length > 0) yield JSON.parse(tail);
|
|
29
|
+
} finally {
|
|
30
|
+
reader.releaseLock();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// src/ollama-chat-model.ts
|
|
35
|
+
var OllamaChatModel = class {
|
|
36
|
+
provider = "ollama";
|
|
37
|
+
modelId;
|
|
38
|
+
config;
|
|
39
|
+
constructor(config) {
|
|
40
|
+
this.modelId = config.modelId;
|
|
41
|
+
this.config = config;
|
|
42
|
+
}
|
|
43
|
+
async generate(options) {
|
|
44
|
+
const body = this.buildBody(options, false);
|
|
45
|
+
const res = await this.fetch("/api/chat", body, options);
|
|
46
|
+
const json = await res.json();
|
|
47
|
+
const text = json.message?.content ?? "";
|
|
48
|
+
const toolCalls = json.message?.tool_calls?.map((tc, i) => ({
|
|
49
|
+
type: "tool-call",
|
|
50
|
+
toolCallId: synthesizeToolCallId(tc.function?.name ?? "unknown", i),
|
|
51
|
+
toolName: tc.function?.name ?? "",
|
|
52
|
+
args: tc.function?.arguments ?? {}
|
|
53
|
+
})) ?? [];
|
|
54
|
+
return {
|
|
55
|
+
text,
|
|
56
|
+
content: [...text.length > 0 ? [{ type: "text", text }] : [], ...toolCalls],
|
|
57
|
+
toolCalls,
|
|
58
|
+
finishReason: mapFinishReason(json),
|
|
59
|
+
usage: mapUsage(json),
|
|
60
|
+
rawResponse: json
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
async stream(options) {
|
|
64
|
+
const body = this.buildBody(options, true);
|
|
65
|
+
const res = await this.fetch("/api/chat", body, options);
|
|
66
|
+
if (!res.body) {
|
|
67
|
+
throw new core.APICallError({
|
|
68
|
+
message: "Ollama streaming response has no body.",
|
|
69
|
+
statusCode: res.status
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
const ndjson = parseNDJSON(res.body);
|
|
73
|
+
return new ReadableStream({
|
|
74
|
+
async start(controller) {
|
|
75
|
+
let usage;
|
|
76
|
+
let finish = "unknown";
|
|
77
|
+
let toolIdx = 0;
|
|
78
|
+
try {
|
|
79
|
+
for await (const chunk of ndjson) {
|
|
80
|
+
if (chunk.message?.content) {
|
|
81
|
+
controller.enqueue({ type: "text-delta", textDelta: chunk.message.content });
|
|
82
|
+
}
|
|
83
|
+
if (chunk.message?.tool_calls) {
|
|
84
|
+
for (const tc of chunk.message.tool_calls) {
|
|
85
|
+
const id = synthesizeToolCallId(tc.function?.name ?? "unknown", toolIdx++);
|
|
86
|
+
controller.enqueue({
|
|
87
|
+
type: "tool-call",
|
|
88
|
+
toolCallId: id,
|
|
89
|
+
toolName: tc.function?.name ?? "",
|
|
90
|
+
args: tc.function?.arguments ?? {}
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (chunk.done) {
|
|
95
|
+
finish = mapFinishReason(chunk);
|
|
96
|
+
usage = mapUsage(chunk);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
controller.enqueue({ type: "finish", finishReason: finish, usage: usage ?? {} });
|
|
100
|
+
controller.close();
|
|
101
|
+
} catch (err) {
|
|
102
|
+
controller.enqueue({ type: "error", error: err });
|
|
103
|
+
controller.close();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Local models are free at runtime — their cost is electricity / GPU
|
|
110
|
+
* time, not per-token billing. We report `pricingAvailable: true`
|
|
111
|
+
* with `$0` so `Budget Guard.maxUsd` constraints simply never trip
|
|
112
|
+
* for Ollama runs (instead of being silently disabled, which would
|
|
113
|
+
* surprise callers migrating from OpenAI).
|
|
114
|
+
*
|
|
115
|
+
* `maxTokens`, `maxLlmCalls`, `maxDurationMs`, and `maxSteps` budgets
|
|
116
|
+
* keep working as documented — those are the meaningful limits when
|
|
117
|
+
* GPU time is the bottleneck.
|
|
118
|
+
*/
|
|
119
|
+
estimateCost(options) {
|
|
120
|
+
const inputTokens = core.estimateTokensFromMessages(asChatMessages(options.messages));
|
|
121
|
+
const maxOut = options.maxTokens ?? 8192;
|
|
122
|
+
const minOut = Math.min(16, maxOut);
|
|
123
|
+
return {
|
|
124
|
+
minTokens: inputTokens + minOut,
|
|
125
|
+
maxTokens: inputTokens + maxOut,
|
|
126
|
+
minUsd: 0,
|
|
127
|
+
maxUsd: 0,
|
|
128
|
+
pricingAvailable: true
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
buildBody(options, stream) {
|
|
132
|
+
const ollamaOptions = {
|
|
133
|
+
...this.config.defaultOptions ?? {}
|
|
134
|
+
};
|
|
135
|
+
if (options.temperature !== void 0) ollamaOptions.temperature = options.temperature;
|
|
136
|
+
if (options.topP !== void 0) ollamaOptions.top_p = options.topP;
|
|
137
|
+
if (options.maxTokens !== void 0) ollamaOptions.num_predict = options.maxTokens;
|
|
138
|
+
if (options.stopSequences !== void 0) ollamaOptions.stop = options.stopSequences;
|
|
139
|
+
if (options.seed !== void 0) ollamaOptions.seed = options.seed;
|
|
140
|
+
const body = {
|
|
141
|
+
model: this.modelId,
|
|
142
|
+
messages: options.messages.map(toOllamaMessage),
|
|
143
|
+
stream
|
|
144
|
+
};
|
|
145
|
+
if (Object.keys(ollamaOptions).length > 0) body.options = ollamaOptions;
|
|
146
|
+
if (options.tools?.length) {
|
|
147
|
+
body.tools = options.tools.map((t) => ({
|
|
148
|
+
type: "function",
|
|
149
|
+
function: {
|
|
150
|
+
name: t.name,
|
|
151
|
+
...t.description !== void 0 ? { description: t.description } : {},
|
|
152
|
+
parameters: t.parameters
|
|
153
|
+
}
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
if (options.providerOptions) Object.assign(body, options.providerOptions);
|
|
157
|
+
return body;
|
|
158
|
+
}
|
|
159
|
+
async fetch(path, body, options) {
|
|
160
|
+
const url = `${this.config.baseURL}${path}`;
|
|
161
|
+
const headers = { ...this.config.headers, ...options.headers };
|
|
162
|
+
const init = {
|
|
163
|
+
method: "POST",
|
|
164
|
+
headers,
|
|
165
|
+
body: JSON.stringify(body)
|
|
166
|
+
};
|
|
167
|
+
if (options.abortSignal) init.signal = options.abortSignal;
|
|
168
|
+
const res = await this.config.fetcher(url, init);
|
|
169
|
+
if (!res.ok) {
|
|
170
|
+
const text = await res.text().catch(() => "");
|
|
171
|
+
throw new core.APICallError({
|
|
172
|
+
message: `Ollama API error: ${res.status} ${res.statusText}`,
|
|
173
|
+
url,
|
|
174
|
+
statusCode: res.status,
|
|
175
|
+
responseBody: text
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
return res;
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
function toOllamaMessage(m) {
|
|
182
|
+
switch (m.role) {
|
|
183
|
+
case "system":
|
|
184
|
+
case "user": {
|
|
185
|
+
const text = m.content.filter((p) => p.type === "text").map((p) => p.text).join("");
|
|
186
|
+
const images = m.content.filter((p) => p.type === "image").map((p) => {
|
|
187
|
+
const img = p.image;
|
|
188
|
+
if (typeof img === "string") return img.replace(/^data:[^;]+;base64,/, "");
|
|
189
|
+
if (img instanceof URL) return img.toString();
|
|
190
|
+
return uint8ToBase64(img);
|
|
191
|
+
});
|
|
192
|
+
const out = { role: m.role, content: text };
|
|
193
|
+
if (images.length > 0) out.images = images;
|
|
194
|
+
return out;
|
|
195
|
+
}
|
|
196
|
+
case "assistant": {
|
|
197
|
+
const text = m.content.filter((p) => p.type === "text").map((p) => p.text).join("");
|
|
198
|
+
const toolCalls = m.content.filter((p) => p.type === "tool-call");
|
|
199
|
+
const out = { role: "assistant", content: text };
|
|
200
|
+
if (toolCalls.length > 0) {
|
|
201
|
+
out.tool_calls = toolCalls.map((tc) => ({
|
|
202
|
+
function: {
|
|
203
|
+
name: tc.toolName,
|
|
204
|
+
arguments: tc.args ?? {}
|
|
205
|
+
}
|
|
206
|
+
}));
|
|
207
|
+
}
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
case "tool": {
|
|
211
|
+
const first = m.content[0];
|
|
212
|
+
if (!first || first.type !== "tool-result") {
|
|
213
|
+
return { role: "tool", content: "" };
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
role: "tool",
|
|
217
|
+
content: typeof first.result === "string" ? first.result : JSON.stringify(first.result)
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
function synthesizeToolCallId(name, index) {
|
|
223
|
+
return `ollama_${name}_${index}_${Math.random().toString(36).slice(2, 8)}`;
|
|
224
|
+
}
|
|
225
|
+
function asChatMessages(messages) {
|
|
226
|
+
return messages;
|
|
227
|
+
}
|
|
228
|
+
function uint8ToBase64(arr) {
|
|
229
|
+
let s = "";
|
|
230
|
+
for (let i = 0; i < arr.byteLength; i++) s += String.fromCharCode(arr[i]);
|
|
231
|
+
return typeof btoa !== "undefined" ? btoa(s) : Buffer.from(s, "binary").toString("base64");
|
|
232
|
+
}
|
|
233
|
+
function mapFinishReason(json) {
|
|
234
|
+
if (json.message?.tool_calls?.length) return "tool-calls";
|
|
235
|
+
if (json.done_reason === "stop" || json.done) return "stop";
|
|
236
|
+
if (json.done_reason === "length") return "length";
|
|
237
|
+
return "unknown";
|
|
238
|
+
}
|
|
239
|
+
function mapUsage(json) {
|
|
240
|
+
const out = {};
|
|
241
|
+
if (json.prompt_eval_count !== void 0) out.promptTokens = json.prompt_eval_count;
|
|
242
|
+
if (json.eval_count !== void 0) out.completionTokens = json.eval_count;
|
|
243
|
+
if (json.prompt_eval_count !== void 0 && json.eval_count !== void 0) {
|
|
244
|
+
out.totalTokens = json.prompt_eval_count + json.eval_count;
|
|
245
|
+
}
|
|
246
|
+
return out;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// src/ollama-provider.ts
|
|
250
|
+
function createOllama(options = {}) {
|
|
251
|
+
const baseURL = (options.baseURL ?? loadEnv("OLLAMA_BASE_URL") ?? "http://localhost:11434").replace(/\/+$/, "");
|
|
252
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
253
|
+
const headers = {
|
|
254
|
+
"Content-Type": "application/json",
|
|
255
|
+
...options.headers
|
|
256
|
+
};
|
|
257
|
+
const make = (modelId) => new OllamaChatModel({
|
|
258
|
+
modelId,
|
|
259
|
+
baseURL,
|
|
260
|
+
headers,
|
|
261
|
+
fetcher,
|
|
262
|
+
...options.defaultOptions ? { defaultOptions: options.defaultOptions } : {}
|
|
263
|
+
});
|
|
264
|
+
const provider = ((modelId) => make(modelId));
|
|
265
|
+
provider.chat = make;
|
|
266
|
+
return provider;
|
|
267
|
+
}
|
|
268
|
+
var ollama = createOllama();
|
|
269
|
+
function loadEnv(name) {
|
|
270
|
+
if (typeof process !== "undefined" && process.env) {
|
|
271
|
+
return process.env[name];
|
|
272
|
+
}
|
|
273
|
+
return void 0;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
exports.OllamaChatModel = OllamaChatModel;
|
|
277
|
+
exports.createOllama = createOllama;
|
|
278
|
+
exports.ollama = ollama;
|
|
279
|
+
//# sourceMappingURL=index.cjs.map
|
|
280
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/util/ndjson.ts","../src/ollama-chat-model.ts","../src/ollama-provider.ts"],"names":["APICallError","estimateTokensFromMessages"],"mappings":";;;;;;;AAQA,gBAAuB,YACrB,IAAA,EACkB;AAClB,EAAA,MAAM,MAAA,GAAS,KAAK,SAAA,EAAU;AAC9B,EAAA,MAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAChC,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,EAAM;AACX,MAAA,MAAM,EAAE,KAAA,EAAO,IAAA,EAAK,GAAI,MAAM,OAAO,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AO,CAAA,CAAA;AAC9D,EAAA,QAAA,CAAS,IAAA,GAAO,IAAA;AAChB,EAAA,OAAO,QAAA;AACT;AAQO,IAAM,SAAyB,YAAA;AAEtC,SAAS,QAAQ,IAAA,EAAkC;AACjD,EAAA,IAAI,OAAO,OAAA,KAAY,WAAA,IAAe,OAAA,CAAQ,GAAA,EAAK;AACjD,IAAA,OAAO,OAAA,CAAQ,IAAI,IAAI,CAAA;AAAA,EACzB;AACA,EAAA,OAAO,MAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * Parse a `ReadableStream<Uint8Array>` of newline-delimited JSON into an\n * async iterator of parsed records. Tolerates `\\r\\n`, blank lines, and\n * partial chunks.\n *\n * Ollama's `/api/chat?stream=true` emits one JSON object per line —\n * unlike OpenAI / Anthropic which use SSE (`data: {...}\\n\\n`).\n */\nexport async function* parseNDJSON<T = unknown>(\n body: ReadableStream<Uint8Array>,\n): AsyncIterable<T> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let nl = buffer.indexOf('\\n');\n while (nl !== -1) {\n const line = buffer.slice(0, nl).replace(/\\r$/, '').trim();\n buffer = buffer.slice(nl + 1);\n if (line.length > 0) {\n yield JSON.parse(line) as T;\n }\n nl = buffer.indexOf('\\n');\n }\n }\n const tail = buffer.trim();\n if (tail.length > 0) yield JSON.parse(tail) as T;\n } finally {\n reader.releaseLock();\n }\n}\n","import {\n APICallError,\n type CostEstimate,\n estimateTokensFromMessages,\n type FinishReason,\n type LanguageModel,\n type ModelCallOptions,\n type ModelGenerateResult,\n type ModelStreamPart,\n type NormalizedMessage,\n type TokenUsage,\n type ToolCallPart,\n} from '@ziro-agent/core';\nimport { parseNDJSON } from './util/ndjson.js';\n\n/**\n * Common Ollama model ids. Ollama is open-weight and the catalogue\n * grows weekly, so we leave the type open via `(string & {})` — pulling\n * a model is `ollama pull <name>` and any tag works.\n *\n * The enumerated entries are the most-pulled tool-capable models on\n * ollama.com as of v0.1.9. They are deliberately conservative — listing\n * every quant would explode the union without changing runtime behaviour.\n */\nexport type OllamaChatModelId =\n | 'llama3.1'\n | 'llama3.1:8b'\n | 'llama3.1:70b'\n | 'llama3.2'\n | 'llama3.2:3b'\n | 'llama3.3'\n | 'qwen2.5'\n | 'qwen2.5:7b'\n | 'qwen2.5:14b'\n | 'qwen2.5:32b'\n | 'qwen2.5-coder'\n | 'mistral'\n | 'mistral-nemo'\n | 'mixtral'\n | 'gemma3'\n | 'phi4'\n | (string & {});\n\ninterface OllamaChatModelConfig {\n modelId: OllamaChatModelId;\n baseURL: string;\n headers: Record<string, string>;\n fetcher: typeof fetch;\n /** Forwarded into Ollama's per-request `options` block. */\n defaultOptions?: Record<string, unknown>;\n}\n\n/**\n * `LanguageModel` adapter for the local Ollama HTTP API\n * (`http://localhost:11434/api/chat`). Talks the native Ollama protocol\n * (NDJSON streaming, function-calling shape) — not the OpenAI-compat\n * shim, which loses tool-call fidelity on several models.\n *\n * Sovereign-pillar primitive (RFC 0004 §v0.1.9): an open-weight default\n * provider so the SDK is not assumed-cloud-only.\n */\nexport class OllamaChatModel implements LanguageModel {\n readonly provider = 'ollama';\n readonly modelId: string;\n private readonly config: OllamaChatModelConfig;\n\n constructor(config: OllamaChatModelConfig) {\n this.modelId = config.modelId;\n this.config = config;\n }\n\n async generate(options: ModelCallOptions): Promise<ModelGenerateResult> {\n const body = this.buildBody(options, false);\n const res = await this.fetch('/api/chat', body, options);\n const json = (await res.json()) as OllamaChatResponse;\n\n const text = json.message?.content ?? '';\n const toolCalls: ToolCallPart[] =\n json.message?.tool_calls?.map((tc, i) => ({\n type: 'tool-call' as const,\n toolCallId: synthesizeToolCallId(tc.function?.name ?? 'unknown', i),\n toolName: tc.function?.name ?? '',\n args: tc.function?.arguments ?? {},\n })) ?? [];\n\n return {\n text,\n content: [...(text.length > 0 ? [{ type: 'text' as const, text }] : []), ...toolCalls],\n toolCalls,\n finishReason: mapFinishReason(json),\n usage: mapUsage(json),\n rawResponse: json,\n };\n }\n\n async stream(options: ModelCallOptions): Promise<ReadableStream<ModelStreamPart>> {\n const body = this.buildBody(options, true);\n const res = await this.fetch('/api/chat', body, options);\n if (!res.body) {\n throw new APICallError({\n message: 'Ollama streaming response has no body.',\n statusCode: res.status,\n });\n }\n\n const ndjson = parseNDJSON<OllamaChatResponse>(res.body);\n\n return new ReadableStream<ModelStreamPart>({\n async start(controller) {\n let usage: TokenUsage | undefined;\n let finish: FinishReason = 'unknown';\n let toolIdx = 0;\n\n try {\n for await (const chunk of ndjson) {\n if (chunk.message?.content) {\n controller.enqueue({ type: 'text-delta', textDelta: chunk.message.content });\n }\n if (chunk.message?.tool_calls) {\n for (const tc of chunk.message.tool_calls) {\n const id = synthesizeToolCallId(tc.function?.name ?? 'unknown', toolIdx++);\n // Ollama emits each tool call complete (no incremental\n // arg streaming), so we forward the full call directly\n // — matching the OpenAI provider's terminal `tool-call`\n // event shape.\n controller.enqueue({\n type: 'tool-call',\n toolCallId: id,\n toolName: tc.function?.name ?? '',\n args: tc.function?.arguments ?? {},\n });\n }\n }\n if (chunk.done) {\n finish = mapFinishReason(chunk);\n usage = mapUsage(chunk);\n }\n }\n controller.enqueue({ type: 'finish', finishReason: finish, usage: usage ?? {} });\n controller.close();\n } catch (err) {\n controller.enqueue({ type: 'error', error: err });\n controller.close();\n }\n },\n });\n }\n\n /**\n * Local models are free at runtime — their cost is electricity / GPU\n * time, not per-token billing. We report `pricingAvailable: true`\n * with `$0` so `Budget Guard.maxUsd` constraints simply never trip\n * for Ollama runs (instead of being silently disabled, which would\n * surprise callers migrating from OpenAI).\n *\n * `maxTokens`, `maxLlmCalls`, `maxDurationMs`, and `maxSteps` budgets\n * keep working as documented — those are the meaningful limits when\n * GPU time is the bottleneck.\n */\n estimateCost(options: ModelCallOptions): CostEstimate {\n const inputTokens = estimateTokensFromMessages(asChatMessages(options.messages));\n const maxOut = options.maxTokens ?? 8_192;\n const minOut = Math.min(16, maxOut);\n return {\n minTokens: inputTokens + minOut,\n maxTokens: inputTokens + maxOut,\n minUsd: 0,\n maxUsd: 0,\n pricingAvailable: true,\n };\n }\n\n private buildBody(options: ModelCallOptions, stream: boolean): Record<string, unknown> {\n const ollamaOptions: Record<string, unknown> = {\n ...(this.config.defaultOptions ?? {}),\n };\n if (options.temperature !== undefined) ollamaOptions.temperature = options.temperature;\n if (options.topP !== undefined) ollamaOptions.top_p = options.topP;\n if (options.maxTokens !== undefined) ollamaOptions.num_predict = options.maxTokens;\n if (options.stopSequences !== undefined) ollamaOptions.stop = options.stopSequences;\n if (options.seed !== undefined) ollamaOptions.seed = options.seed;\n\n const body: Record<string, unknown> = {\n model: this.modelId,\n messages: options.messages.map(toOllamaMessage),\n stream,\n };\n if (Object.keys(ollamaOptions).length > 0) body.options = ollamaOptions;\n if (options.tools?.length) {\n body.tools = options.tools.map((t) => ({\n type: 'function',\n function: {\n name: t.name,\n ...(t.description !== undefined ? { description: t.description } : {}),\n parameters: t.parameters,\n },\n }));\n }\n if (options.providerOptions) Object.assign(body, options.providerOptions);\n return body;\n }\n\n private async fetch(path: string, body: unknown, options: ModelCallOptions): Promise<Response> {\n const url = `${this.config.baseURL}${path}`;\n const headers = { ...this.config.headers, ...options.headers };\n const init: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n };\n if (options.abortSignal) init.signal = options.abortSignal;\n\n const res = await this.config.fetcher(url, init);\n if (!res.ok) {\n const text = await res.text().catch(() => '');\n throw new APICallError({\n message: `Ollama API error: ${res.status} ${res.statusText}`,\n url,\n statusCode: res.status,\n responseBody: text,\n });\n }\n return res;\n }\n}\n\nfunction toOllamaMessage(m: NormalizedMessage): unknown {\n switch (m.role) {\n case 'system':\n case 'user': {\n const text = m.content\n .filter((p) => p.type === 'text')\n .map((p) => (p as { text: string }).text)\n .join('');\n const images = m.content\n .filter((p) => p.type === 'image')\n .map((p) => {\n const img = (p as { image: string | URL | Uint8Array }).image;\n if (typeof img === 'string') return img.replace(/^data:[^;]+;base64,/, '');\n if (img instanceof URL) return img.toString();\n return uint8ToBase64(img);\n });\n const out: Record<string, unknown> = { role: m.role, content: text };\n if (images.length > 0) out.images = images;\n return out;\n }\n case 'assistant': {\n const text = m.content\n .filter((p) => p.type === 'text')\n .map((p) => (p as { text: string }).text)\n .join('');\n const toolCalls = m.content.filter((p) => p.type === 'tool-call');\n const out: Record<string, unknown> = { role: 'assistant', content: text };\n if (toolCalls.length > 0) {\n out.tool_calls = toolCalls.map((tc) => ({\n function: {\n name: (tc as ToolCallPart).toolName,\n arguments: (tc as ToolCallPart).args ?? {},\n },\n }));\n }\n return out;\n }\n case 'tool': {\n const first = m.content[0];\n if (!first || first.type !== 'tool-result') {\n return { role: 'tool', content: '' };\n }\n return {\n role: 'tool',\n content: typeof first.result === 'string' ? first.result : JSON.stringify(first.result),\n };\n }\n }\n}\n\n/**\n * Ollama's `tool_calls[]` entries don't carry a stable id — they're\n * just `{ function: { name, arguments } }`. We synthesise an id so the\n * downstream agent loop can match tool results back to calls without\n * collisions across a batch.\n */\nfunction synthesizeToolCallId(name: string, index: number): string {\n return `ollama_${name}_${index}_${Math.random().toString(36).slice(2, 8)}`;\n}\n\nfunction asChatMessages(\n messages: NormalizedMessage[],\n): Parameters<typeof estimateTokensFromMessages>[0] {\n return messages as unknown as Parameters<typeof estimateTokensFromMessages>[0];\n}\n\nfunction uint8ToBase64(arr: Uint8Array): string {\n let s = '';\n for (let i = 0; i < arr.byteLength; i++) s += String.fromCharCode(arr[i] as number);\n return typeof btoa !== 'undefined' ? btoa(s) : Buffer.from(s, 'binary').toString('base64');\n}\n\nfunction mapFinishReason(json: OllamaChatResponse): FinishReason {\n if (json.message?.tool_calls?.length) return 'tool-calls';\n if (json.done_reason === 'stop' || json.done) return 'stop';\n if (json.done_reason === 'length') return 'length';\n return 'unknown';\n}\n\nfunction mapUsage(json: OllamaChatResponse): TokenUsage {\n const out: TokenUsage = {};\n if (json.prompt_eval_count !== undefined) out.promptTokens = json.prompt_eval_count;\n if (json.eval_count !== undefined) out.completionTokens = json.eval_count;\n if (json.prompt_eval_count !== undefined && json.eval_count !== undefined) {\n out.totalTokens = json.prompt_eval_count + json.eval_count;\n }\n return out;\n}\n\ninterface OllamaChatResponse {\n model?: string;\n created_at?: string;\n message?: {\n role?: string;\n content?: string;\n tool_calls?: Array<{\n function?: {\n name?: string;\n arguments?: Record<string, unknown>;\n };\n }>;\n };\n done?: boolean;\n done_reason?: 'stop' | 'length' | 'load' | string;\n total_duration?: number;\n load_duration?: number;\n prompt_eval_count?: number;\n prompt_eval_duration?: number;\n eval_count?: number;\n eval_duration?: number;\n}\n","import type { LanguageModel } from '@ziro-agent/core';\nimport { OllamaChatModel, type OllamaChatModelId } from './ollama-chat-model.js';\n\nexport interface OllamaProviderOptions {\n /**\n * Base URL of the Ollama daemon. Defaults to\n * `process.env.OLLAMA_BASE_URL` then `http://localhost:11434`.\n *\n * For remote / containerised Ollama (e.g. compose stack, Coolify),\n * set this to `http://ollama:11434` or whatever your network exposes.\n */\n baseURL?: string;\n /** Extra default headers attached to every request. */\n headers?: Record<string, string>;\n /** Custom `fetch`. Defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n /**\n * Default Ollama-native sampling options (`num_ctx`, `mirostat`,\n * `repeat_penalty`, …) merged into every request's `options` block.\n * Per-call overrides via `ModelCallOptions.providerOptions.options`\n * still win.\n */\n defaultOptions?: Record<string, unknown>;\n}\n\nexport interface OllamaProvider {\n (modelId: OllamaChatModelId): LanguageModel;\n chat(modelId: OllamaChatModelId): LanguageModel;\n}\n\n/**\n * Build an {@link OllamaProvider} bound to a specific Ollama daemon.\n * Mirrors `createOpenAI` / `createAnthropic` so swapping providers in\n * `createAgent({ model })` is a one-line change.\n */\nexport function createOllama(options: OllamaProviderOptions = {}): OllamaProvider {\n const baseURL = (\n options.baseURL ??\n loadEnv('OLLAMA_BASE_URL') ??\n 'http://localhost:11434'\n ).replace(/\\/+$/, '');\n const fetcher = options.fetch ?? globalThis.fetch;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...options.headers,\n };\n\n const make = (modelId: OllamaChatModelId): LanguageModel =>\n new OllamaChatModel({\n modelId,\n baseURL,\n headers,\n fetcher,\n ...(options.defaultOptions ? { defaultOptions: options.defaultOptions } : {}),\n });\n\n const provider = ((modelId: OllamaChatModelId) => make(modelId)) as OllamaProvider;\n provider.chat = make;\n return provider;\n}\n\n/**\n * Default singleton — connects to `localhost:11434` (or\n * `OLLAMA_BASE_URL` if set). Suitable for the typical\n * `ollama serve` setup; build a custom provider with `createOllama()`\n * for remote / authenticated daemons.\n */\nexport const ollama: OllamaProvider = createOllama();\n\nfunction loadEnv(name: string): string | undefined {\n if (typeof process !== 'undefined' && process.env) {\n return process.env[name];\n }\n return undefined;\n}\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { LanguageModel, ModelCallOptions, ModelGenerateResult, ModelStreamPart, CostEstimate } from '@ziro-agent/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Common Ollama model ids. Ollama is open-weight and the catalogue
|
|
5
|
+
* grows weekly, so we leave the type open via `(string & {})` — pulling
|
|
6
|
+
* a model is `ollama pull <name>` and any tag works.
|
|
7
|
+
*
|
|
8
|
+
* The enumerated entries are the most-pulled tool-capable models on
|
|
9
|
+
* ollama.com as of v0.1.9. They are deliberately conservative — listing
|
|
10
|
+
* every quant would explode the union without changing runtime behaviour.
|
|
11
|
+
*/
|
|
12
|
+
type OllamaChatModelId = 'llama3.1' | 'llama3.1:8b' | 'llama3.1:70b' | 'llama3.2' | 'llama3.2:3b' | 'llama3.3' | 'qwen2.5' | 'qwen2.5:7b' | 'qwen2.5:14b' | 'qwen2.5:32b' | 'qwen2.5-coder' | 'mistral' | 'mistral-nemo' | 'mixtral' | 'gemma3' | 'phi4' | (string & {});
|
|
13
|
+
interface OllamaChatModelConfig {
|
|
14
|
+
modelId: OllamaChatModelId;
|
|
15
|
+
baseURL: string;
|
|
16
|
+
headers: Record<string, string>;
|
|
17
|
+
fetcher: typeof fetch;
|
|
18
|
+
/** Forwarded into Ollama's per-request `options` block. */
|
|
19
|
+
defaultOptions?: Record<string, unknown>;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* `LanguageModel` adapter for the local Ollama HTTP API
|
|
23
|
+
* (`http://localhost:11434/api/chat`). Talks the native Ollama protocol
|
|
24
|
+
* (NDJSON streaming, function-calling shape) — not the OpenAI-compat
|
|
25
|
+
* shim, which loses tool-call fidelity on several models.
|
|
26
|
+
*
|
|
27
|
+
* Sovereign-pillar primitive (RFC 0004 §v0.1.9): an open-weight default
|
|
28
|
+
* provider so the SDK is not assumed-cloud-only.
|
|
29
|
+
*/
|
|
30
|
+
declare class OllamaChatModel implements LanguageModel {
|
|
31
|
+
readonly provider = "ollama";
|
|
32
|
+
readonly modelId: string;
|
|
33
|
+
private readonly config;
|
|
34
|
+
constructor(config: OllamaChatModelConfig);
|
|
35
|
+
generate(options: ModelCallOptions): Promise<ModelGenerateResult>;
|
|
36
|
+
stream(options: ModelCallOptions): Promise<ReadableStream<ModelStreamPart>>;
|
|
37
|
+
/**
|
|
38
|
+
* Local models are free at runtime — their cost is electricity / GPU
|
|
39
|
+
* time, not per-token billing. We report `pricingAvailable: true`
|
|
40
|
+
* with `$0` so `Budget Guard.maxUsd` constraints simply never trip
|
|
41
|
+
* for Ollama runs (instead of being silently disabled, which would
|
|
42
|
+
* surprise callers migrating from OpenAI).
|
|
43
|
+
*
|
|
44
|
+
* `maxTokens`, `maxLlmCalls`, `maxDurationMs`, and `maxSteps` budgets
|
|
45
|
+
* keep working as documented — those are the meaningful limits when
|
|
46
|
+
* GPU time is the bottleneck.
|
|
47
|
+
*/
|
|
48
|
+
estimateCost(options: ModelCallOptions): CostEstimate;
|
|
49
|
+
private buildBody;
|
|
50
|
+
private fetch;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface OllamaProviderOptions {
|
|
54
|
+
/**
|
|
55
|
+
* Base URL of the Ollama daemon. Defaults to
|
|
56
|
+
* `process.env.OLLAMA_BASE_URL` then `http://localhost:11434`.
|
|
57
|
+
*
|
|
58
|
+
* For remote / containerised Ollama (e.g. compose stack, Coolify),
|
|
59
|
+
* set this to `http://ollama:11434` or whatever your network exposes.
|
|
60
|
+
*/
|
|
61
|
+
baseURL?: string;
|
|
62
|
+
/** Extra default headers attached to every request. */
|
|
63
|
+
headers?: Record<string, string>;
|
|
64
|
+
/** Custom `fetch`. Defaults to `globalThis.fetch`. */
|
|
65
|
+
fetch?: typeof fetch;
|
|
66
|
+
/**
|
|
67
|
+
* Default Ollama-native sampling options (`num_ctx`, `mirostat`,
|
|
68
|
+
* `repeat_penalty`, …) merged into every request's `options` block.
|
|
69
|
+
* Per-call overrides via `ModelCallOptions.providerOptions.options`
|
|
70
|
+
* still win.
|
|
71
|
+
*/
|
|
72
|
+
defaultOptions?: Record<string, unknown>;
|
|
73
|
+
}
|
|
74
|
+
interface OllamaProvider {
|
|
75
|
+
(modelId: OllamaChatModelId): LanguageModel;
|
|
76
|
+
chat(modelId: OllamaChatModelId): LanguageModel;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Build an {@link OllamaProvider} bound to a specific Ollama daemon.
|
|
80
|
+
* Mirrors `createOpenAI` / `createAnthropic` so swapping providers in
|
|
81
|
+
* `createAgent({ model })` is a one-line change.
|
|
82
|
+
*/
|
|
83
|
+
declare function createOllama(options?: OllamaProviderOptions): OllamaProvider;
|
|
84
|
+
/**
|
|
85
|
+
* Default singleton — connects to `localhost:11434` (or
|
|
86
|
+
* `OLLAMA_BASE_URL` if set). Suitable for the typical
|
|
87
|
+
* `ollama serve` setup; build a custom provider with `createOllama()`
|
|
88
|
+
* for remote / authenticated daemons.
|
|
89
|
+
*/
|
|
90
|
+
declare const ollama: OllamaProvider;
|
|
91
|
+
|
|
92
|
+
export { OllamaChatModel, type OllamaChatModelId, type OllamaProviderOptions, createOllama, ollama };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { LanguageModel, ModelCallOptions, ModelGenerateResult, ModelStreamPart, CostEstimate } from '@ziro-agent/core';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Common Ollama model ids. Ollama is open-weight and the catalogue
|
|
5
|
+
* grows weekly, so we leave the type open via `(string & {})` — pulling
|
|
6
|
+
* a model is `ollama pull <name>` and any tag works.
|
|
7
|
+
*
|
|
8
|
+
* The enumerated entries are the most-pulled tool-capable models on
|
|
9
|
+
* ollama.com as of v0.1.9. They are deliberately conservative — listing
|
|
10
|
+
* every quant would explode the union without changing runtime behaviour.
|
|
11
|
+
*/
|
|
12
|
+
type OllamaChatModelId = 'llama3.1' | 'llama3.1:8b' | 'llama3.1:70b' | 'llama3.2' | 'llama3.2:3b' | 'llama3.3' | 'qwen2.5' | 'qwen2.5:7b' | 'qwen2.5:14b' | 'qwen2.5:32b' | 'qwen2.5-coder' | 'mistral' | 'mistral-nemo' | 'mixtral' | 'gemma3' | 'phi4' | (string & {});
|
|
13
|
+
interface OllamaChatModelConfig {
|
|
14
|
+
modelId: OllamaChatModelId;
|
|
15
|
+
baseURL: string;
|
|
16
|
+
headers: Record<string, string>;
|
|
17
|
+
fetcher: typeof fetch;
|
|
18
|
+
/** Forwarded into Ollama's per-request `options` block. */
|
|
19
|
+
defaultOptions?: Record<string, unknown>;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* `LanguageModel` adapter for the local Ollama HTTP API
|
|
23
|
+
* (`http://localhost:11434/api/chat`). Talks the native Ollama protocol
|
|
24
|
+
* (NDJSON streaming, function-calling shape) — not the OpenAI-compat
|
|
25
|
+
* shim, which loses tool-call fidelity on several models.
|
|
26
|
+
*
|
|
27
|
+
* Sovereign-pillar primitive (RFC 0004 §v0.1.9): an open-weight default
|
|
28
|
+
* provider so the SDK is not assumed-cloud-only.
|
|
29
|
+
*/
|
|
30
|
+
declare class OllamaChatModel implements LanguageModel {
|
|
31
|
+
readonly provider = "ollama";
|
|
32
|
+
readonly modelId: string;
|
|
33
|
+
private readonly config;
|
|
34
|
+
constructor(config: OllamaChatModelConfig);
|
|
35
|
+
generate(options: ModelCallOptions): Promise<ModelGenerateResult>;
|
|
36
|
+
stream(options: ModelCallOptions): Promise<ReadableStream<ModelStreamPart>>;
|
|
37
|
+
/**
|
|
38
|
+
* Local models are free at runtime — their cost is electricity / GPU
|
|
39
|
+
* time, not per-token billing. We report `pricingAvailable: true`
|
|
40
|
+
* with `$0` so `Budget Guard.maxUsd` constraints simply never trip
|
|
41
|
+
* for Ollama runs (instead of being silently disabled, which would
|
|
42
|
+
* surprise callers migrating from OpenAI).
|
|
43
|
+
*
|
|
44
|
+
* `maxTokens`, `maxLlmCalls`, `maxDurationMs`, and `maxSteps` budgets
|
|
45
|
+
* keep working as documented — those are the meaningful limits when
|
|
46
|
+
* GPU time is the bottleneck.
|
|
47
|
+
*/
|
|
48
|
+
estimateCost(options: ModelCallOptions): CostEstimate;
|
|
49
|
+
private buildBody;
|
|
50
|
+
private fetch;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface OllamaProviderOptions {
|
|
54
|
+
/**
|
|
55
|
+
* Base URL of the Ollama daemon. Defaults to
|
|
56
|
+
* `process.env.OLLAMA_BASE_URL` then `http://localhost:11434`.
|
|
57
|
+
*
|
|
58
|
+
* For remote / containerised Ollama (e.g. compose stack, Coolify),
|
|
59
|
+
* set this to `http://ollama:11434` or whatever your network exposes.
|
|
60
|
+
*/
|
|
61
|
+
baseURL?: string;
|
|
62
|
+
/** Extra default headers attached to every request. */
|
|
63
|
+
headers?: Record<string, string>;
|
|
64
|
+
/** Custom `fetch`. Defaults to `globalThis.fetch`. */
|
|
65
|
+
fetch?: typeof fetch;
|
|
66
|
+
/**
|
|
67
|
+
* Default Ollama-native sampling options (`num_ctx`, `mirostat`,
|
|
68
|
+
* `repeat_penalty`, …) merged into every request's `options` block.
|
|
69
|
+
* Per-call overrides via `ModelCallOptions.providerOptions.options`
|
|
70
|
+
* still win.
|
|
71
|
+
*/
|
|
72
|
+
defaultOptions?: Record<string, unknown>;
|
|
73
|
+
}
|
|
74
|
+
interface OllamaProvider {
|
|
75
|
+
(modelId: OllamaChatModelId): LanguageModel;
|
|
76
|
+
chat(modelId: OllamaChatModelId): LanguageModel;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Build an {@link OllamaProvider} bound to a specific Ollama daemon.
|
|
80
|
+
* Mirrors `createOpenAI` / `createAnthropic` so swapping providers in
|
|
81
|
+
* `createAgent({ model })` is a one-line change.
|
|
82
|
+
*/
|
|
83
|
+
declare function createOllama(options?: OllamaProviderOptions): OllamaProvider;
|
|
84
|
+
/**
|
|
85
|
+
* Default singleton — connects to `localhost:11434` (or
|
|
86
|
+
* `OLLAMA_BASE_URL` if set). Suitable for the typical
|
|
87
|
+
* `ollama serve` setup; build a custom provider with `createOllama()`
|
|
88
|
+
* for remote / authenticated daemons.
|
|
89
|
+
*/
|
|
90
|
+
declare const ollama: OllamaProvider;
|
|
91
|
+
|
|
92
|
+
export { OllamaChatModel, type OllamaChatModelId, type OllamaProviderOptions, createOllama, ollama };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { APICallError, estimateTokensFromMessages } from '@ziro-agent/core';
|
|
2
|
+
|
|
3
|
+
// src/ollama-chat-model.ts
|
|
4
|
+
|
|
5
|
+
// src/util/ndjson.ts
|
|
6
|
+
async function* parseNDJSON(body) {
|
|
7
|
+
const reader = body.getReader();
|
|
8
|
+
const decoder = new TextDecoder();
|
|
9
|
+
let buffer = "";
|
|
10
|
+
try {
|
|
11
|
+
while (true) {
|
|
12
|
+
const { value, done } = await reader.read();
|
|
13
|
+
if (done) break;
|
|
14
|
+
buffer += decoder.decode(value, { stream: true });
|
|
15
|
+
let nl = buffer.indexOf("\n");
|
|
16
|
+
while (nl !== -1) {
|
|
17
|
+
const line = buffer.slice(0, nl).replace(/\r$/, "").trim();
|
|
18
|
+
buffer = buffer.slice(nl + 1);
|
|
19
|
+
if (line.length > 0) {
|
|
20
|
+
yield JSON.parse(line);
|
|
21
|
+
}
|
|
22
|
+
nl = buffer.indexOf("\n");
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const tail = buffer.trim();
|
|
26
|
+
if (tail.length > 0) yield JSON.parse(tail);
|
|
27
|
+
} finally {
|
|
28
|
+
reader.releaseLock();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// src/ollama-chat-model.ts
|
|
33
|
+
var OllamaChatModel = class {
|
|
34
|
+
provider = "ollama";
|
|
35
|
+
modelId;
|
|
36
|
+
config;
|
|
37
|
+
constructor(config) {
|
|
38
|
+
this.modelId = config.modelId;
|
|
39
|
+
this.config = config;
|
|
40
|
+
}
|
|
41
|
+
async generate(options) {
|
|
42
|
+
const body = this.buildBody(options, false);
|
|
43
|
+
const res = await this.fetch("/api/chat", body, options);
|
|
44
|
+
const json = await res.json();
|
|
45
|
+
const text = json.message?.content ?? "";
|
|
46
|
+
const toolCalls = json.message?.tool_calls?.map((tc, i) => ({
|
|
47
|
+
type: "tool-call",
|
|
48
|
+
toolCallId: synthesizeToolCallId(tc.function?.name ?? "unknown", i),
|
|
49
|
+
toolName: tc.function?.name ?? "",
|
|
50
|
+
args: tc.function?.arguments ?? {}
|
|
51
|
+
})) ?? [];
|
|
52
|
+
return {
|
|
53
|
+
text,
|
|
54
|
+
content: [...text.length > 0 ? [{ type: "text", text }] : [], ...toolCalls],
|
|
55
|
+
toolCalls,
|
|
56
|
+
finishReason: mapFinishReason(json),
|
|
57
|
+
usage: mapUsage(json),
|
|
58
|
+
rawResponse: json
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
async stream(options) {
|
|
62
|
+
const body = this.buildBody(options, true);
|
|
63
|
+
const res = await this.fetch("/api/chat", body, options);
|
|
64
|
+
if (!res.body) {
|
|
65
|
+
throw new APICallError({
|
|
66
|
+
message: "Ollama streaming response has no body.",
|
|
67
|
+
statusCode: res.status
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
const ndjson = parseNDJSON(res.body);
|
|
71
|
+
return new ReadableStream({
|
|
72
|
+
async start(controller) {
|
|
73
|
+
let usage;
|
|
74
|
+
let finish = "unknown";
|
|
75
|
+
let toolIdx = 0;
|
|
76
|
+
try {
|
|
77
|
+
for await (const chunk of ndjson) {
|
|
78
|
+
if (chunk.message?.content) {
|
|
79
|
+
controller.enqueue({ type: "text-delta", textDelta: chunk.message.content });
|
|
80
|
+
}
|
|
81
|
+
if (chunk.message?.tool_calls) {
|
|
82
|
+
for (const tc of chunk.message.tool_calls) {
|
|
83
|
+
const id = synthesizeToolCallId(tc.function?.name ?? "unknown", toolIdx++);
|
|
84
|
+
controller.enqueue({
|
|
85
|
+
type: "tool-call",
|
|
86
|
+
toolCallId: id,
|
|
87
|
+
toolName: tc.function?.name ?? "",
|
|
88
|
+
args: tc.function?.arguments ?? {}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (chunk.done) {
|
|
93
|
+
finish = mapFinishReason(chunk);
|
|
94
|
+
usage = mapUsage(chunk);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
controller.enqueue({ type: "finish", finishReason: finish, usage: usage ?? {} });
|
|
98
|
+
controller.close();
|
|
99
|
+
} catch (err) {
|
|
100
|
+
controller.enqueue({ type: "error", error: err });
|
|
101
|
+
controller.close();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Local models are free at runtime — their cost is electricity / GPU
|
|
108
|
+
* time, not per-token billing. We report `pricingAvailable: true`
|
|
109
|
+
* with `$0` so `Budget Guard.maxUsd` constraints simply never trip
|
|
110
|
+
* for Ollama runs (instead of being silently disabled, which would
|
|
111
|
+
* surprise callers migrating from OpenAI).
|
|
112
|
+
*
|
|
113
|
+
* `maxTokens`, `maxLlmCalls`, `maxDurationMs`, and `maxSteps` budgets
|
|
114
|
+
* keep working as documented — those are the meaningful limits when
|
|
115
|
+
* GPU time is the bottleneck.
|
|
116
|
+
*/
|
|
117
|
+
estimateCost(options) {
|
|
118
|
+
const inputTokens = estimateTokensFromMessages(asChatMessages(options.messages));
|
|
119
|
+
const maxOut = options.maxTokens ?? 8192;
|
|
120
|
+
const minOut = Math.min(16, maxOut);
|
|
121
|
+
return {
|
|
122
|
+
minTokens: inputTokens + minOut,
|
|
123
|
+
maxTokens: inputTokens + maxOut,
|
|
124
|
+
minUsd: 0,
|
|
125
|
+
maxUsd: 0,
|
|
126
|
+
pricingAvailable: true
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
buildBody(options, stream) {
|
|
130
|
+
const ollamaOptions = {
|
|
131
|
+
...this.config.defaultOptions ?? {}
|
|
132
|
+
};
|
|
133
|
+
if (options.temperature !== void 0) ollamaOptions.temperature = options.temperature;
|
|
134
|
+
if (options.topP !== void 0) ollamaOptions.top_p = options.topP;
|
|
135
|
+
if (options.maxTokens !== void 0) ollamaOptions.num_predict = options.maxTokens;
|
|
136
|
+
if (options.stopSequences !== void 0) ollamaOptions.stop = options.stopSequences;
|
|
137
|
+
if (options.seed !== void 0) ollamaOptions.seed = options.seed;
|
|
138
|
+
const body = {
|
|
139
|
+
model: this.modelId,
|
|
140
|
+
messages: options.messages.map(toOllamaMessage),
|
|
141
|
+
stream
|
|
142
|
+
};
|
|
143
|
+
if (Object.keys(ollamaOptions).length > 0) body.options = ollamaOptions;
|
|
144
|
+
if (options.tools?.length) {
|
|
145
|
+
body.tools = options.tools.map((t) => ({
|
|
146
|
+
type: "function",
|
|
147
|
+
function: {
|
|
148
|
+
name: t.name,
|
|
149
|
+
...t.description !== void 0 ? { description: t.description } : {},
|
|
150
|
+
parameters: t.parameters
|
|
151
|
+
}
|
|
152
|
+
}));
|
|
153
|
+
}
|
|
154
|
+
if (options.providerOptions) Object.assign(body, options.providerOptions);
|
|
155
|
+
return body;
|
|
156
|
+
}
|
|
157
|
+
async fetch(path, body, options) {
|
|
158
|
+
const url = `${this.config.baseURL}${path}`;
|
|
159
|
+
const headers = { ...this.config.headers, ...options.headers };
|
|
160
|
+
const init = {
|
|
161
|
+
method: "POST",
|
|
162
|
+
headers,
|
|
163
|
+
body: JSON.stringify(body)
|
|
164
|
+
};
|
|
165
|
+
if (options.abortSignal) init.signal = options.abortSignal;
|
|
166
|
+
const res = await this.config.fetcher(url, init);
|
|
167
|
+
if (!res.ok) {
|
|
168
|
+
const text = await res.text().catch(() => "");
|
|
169
|
+
throw new APICallError({
|
|
170
|
+
message: `Ollama API error: ${res.status} ${res.statusText}`,
|
|
171
|
+
url,
|
|
172
|
+
statusCode: res.status,
|
|
173
|
+
responseBody: text
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
return res;
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
function toOllamaMessage(m) {
|
|
180
|
+
switch (m.role) {
|
|
181
|
+
case "system":
|
|
182
|
+
case "user": {
|
|
183
|
+
const text = m.content.filter((p) => p.type === "text").map((p) => p.text).join("");
|
|
184
|
+
const images = m.content.filter((p) => p.type === "image").map((p) => {
|
|
185
|
+
const img = p.image;
|
|
186
|
+
if (typeof img === "string") return img.replace(/^data:[^;]+;base64,/, "");
|
|
187
|
+
if (img instanceof URL) return img.toString();
|
|
188
|
+
return uint8ToBase64(img);
|
|
189
|
+
});
|
|
190
|
+
const out = { role: m.role, content: text };
|
|
191
|
+
if (images.length > 0) out.images = images;
|
|
192
|
+
return out;
|
|
193
|
+
}
|
|
194
|
+
case "assistant": {
|
|
195
|
+
const text = m.content.filter((p) => p.type === "text").map((p) => p.text).join("");
|
|
196
|
+
const toolCalls = m.content.filter((p) => p.type === "tool-call");
|
|
197
|
+
const out = { role: "assistant", content: text };
|
|
198
|
+
if (toolCalls.length > 0) {
|
|
199
|
+
out.tool_calls = toolCalls.map((tc) => ({
|
|
200
|
+
function: {
|
|
201
|
+
name: tc.toolName,
|
|
202
|
+
arguments: tc.args ?? {}
|
|
203
|
+
}
|
|
204
|
+
}));
|
|
205
|
+
}
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
case "tool": {
|
|
209
|
+
const first = m.content[0];
|
|
210
|
+
if (!first || first.type !== "tool-result") {
|
|
211
|
+
return { role: "tool", content: "" };
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
role: "tool",
|
|
215
|
+
content: typeof first.result === "string" ? first.result : JSON.stringify(first.result)
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
function synthesizeToolCallId(name, index) {
|
|
221
|
+
return `ollama_${name}_${index}_${Math.random().toString(36).slice(2, 8)}`;
|
|
222
|
+
}
|
|
223
|
+
function asChatMessages(messages) {
|
|
224
|
+
return messages;
|
|
225
|
+
}
|
|
226
|
+
function uint8ToBase64(arr) {
|
|
227
|
+
let s = "";
|
|
228
|
+
for (let i = 0; i < arr.byteLength; i++) s += String.fromCharCode(arr[i]);
|
|
229
|
+
return typeof btoa !== "undefined" ? btoa(s) : Buffer.from(s, "binary").toString("base64");
|
|
230
|
+
}
|
|
231
|
+
function mapFinishReason(json) {
|
|
232
|
+
if (json.message?.tool_calls?.length) return "tool-calls";
|
|
233
|
+
if (json.done_reason === "stop" || json.done) return "stop";
|
|
234
|
+
if (json.done_reason === "length") return "length";
|
|
235
|
+
return "unknown";
|
|
236
|
+
}
|
|
237
|
+
function mapUsage(json) {
|
|
238
|
+
const out = {};
|
|
239
|
+
if (json.prompt_eval_count !== void 0) out.promptTokens = json.prompt_eval_count;
|
|
240
|
+
if (json.eval_count !== void 0) out.completionTokens = json.eval_count;
|
|
241
|
+
if (json.prompt_eval_count !== void 0 && json.eval_count !== void 0) {
|
|
242
|
+
out.totalTokens = json.prompt_eval_count + json.eval_count;
|
|
243
|
+
}
|
|
244
|
+
return out;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// src/ollama-provider.ts
|
|
248
|
+
function createOllama(options = {}) {
|
|
249
|
+
const baseURL = (options.baseURL ?? loadEnv("OLLAMA_BASE_URL") ?? "http://localhost:11434").replace(/\/+$/, "");
|
|
250
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
251
|
+
const headers = {
|
|
252
|
+
"Content-Type": "application/json",
|
|
253
|
+
...options.headers
|
|
254
|
+
};
|
|
255
|
+
const make = (modelId) => new OllamaChatModel({
|
|
256
|
+
modelId,
|
|
257
|
+
baseURL,
|
|
258
|
+
headers,
|
|
259
|
+
fetcher,
|
|
260
|
+
...options.defaultOptions ? { defaultOptions: options.defaultOptions } : {}
|
|
261
|
+
});
|
|
262
|
+
const provider = ((modelId) => make(modelId));
|
|
263
|
+
provider.chat = make;
|
|
264
|
+
return provider;
|
|
265
|
+
}
|
|
266
|
+
var ollama = createOllama();
|
|
267
|
+
function loadEnv(name) {
|
|
268
|
+
if (typeof process !== "undefined" && process.env) {
|
|
269
|
+
return process.env[name];
|
|
270
|
+
}
|
|
271
|
+
return void 0;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export { OllamaChatModel, createOllama, ollama };
|
|
275
|
+
//# sourceMappingURL=index.js.map
|
|
276
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/util/ndjson.ts","../src/ollama-chat-model.ts","../src/ollama-provider.ts"],"names":[],"mappings":";;;;;AAQA,gBAAuB,YACrB,IAAA,EACkB;AAClB,EAAA,MAAM,MAAA,GAAS,KAAK,SAAA,EAAU;AAC9B,EAAA,MAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAChC,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,EAAM;AACX,MAAA,MAAM,EAAE,KAAA,EAAO,IAAA,EAAK,GAAI,MAAM,OAAO,IAAA,EAAK;AAC1C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EAAA,QAAA,CAAS,IAAA,GAAO,IAAA;AAChB,EAAA,OAAO,QAAA;AACT;AAQO,IAAM,SAAyB,YAAA;AAEtC,SAAS,QAAQ,IAAA,EAAkC;AACjD,EAAA,IAAI,OAAO,OAAA,KAAY,WAAA,IAAe,OAAA,CAAQ,GAAA,EAAK;AACjD,IAAA,OAAO,OAAA,CAAQ,IAAI,IAAI,CAAA;AAAA,EACzB;AACA,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["/**\n * Parse a `ReadableStream<Uint8Array>` of newline-delimited JSON into an\n * async iterator of parsed records. Tolerates `\\r\\n`, blank lines, and\n * partial chunks.\n *\n * Ollama's `/api/chat?stream=true` emits one JSON object per line —\n * unlike OpenAI / Anthropic which use SSE (`data: {...}\\n\\n`).\n */\nexport async function* parseNDJSON<T = unknown>(\n body: ReadableStream<Uint8Array>,\n): AsyncIterable<T> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let nl = buffer.indexOf('\\n');\n while (nl !== -1) {\n const line = buffer.slice(0, nl).replace(/\\r$/, '').trim();\n buffer = buffer.slice(nl + 1);\n if (line.length > 0) {\n yield JSON.parse(line) as T;\n }\n nl = buffer.indexOf('\\n');\n }\n }\n const tail = buffer.trim();\n if (tail.length > 0) yield JSON.parse(tail) as T;\n } finally {\n reader.releaseLock();\n }\n}\n","import {\n APICallError,\n type CostEstimate,\n estimateTokensFromMessages,\n type FinishReason,\n type LanguageModel,\n type ModelCallOptions,\n type ModelGenerateResult,\n type ModelStreamPart,\n type NormalizedMessage,\n type TokenUsage,\n type ToolCallPart,\n} from '@ziro-agent/core';\nimport { parseNDJSON } from './util/ndjson.js';\n\n/**\n * Common Ollama model ids. Ollama is open-weight and the catalogue\n * grows weekly, so we leave the type open via `(string & {})` — pulling\n * a model is `ollama pull <name>` and any tag works.\n *\n * The enumerated entries are the most-pulled tool-capable models on\n * ollama.com as of v0.1.9. They are deliberately conservative — listing\n * every quant would explode the union without changing runtime behaviour.\n */\nexport type OllamaChatModelId =\n | 'llama3.1'\n | 'llama3.1:8b'\n | 'llama3.1:70b'\n | 'llama3.2'\n | 'llama3.2:3b'\n | 'llama3.3'\n | 'qwen2.5'\n | 'qwen2.5:7b'\n | 'qwen2.5:14b'\n | 'qwen2.5:32b'\n | 'qwen2.5-coder'\n | 'mistral'\n | 'mistral-nemo'\n | 'mixtral'\n | 'gemma3'\n | 'phi4'\n | (string & {});\n\ninterface OllamaChatModelConfig {\n modelId: OllamaChatModelId;\n baseURL: string;\n headers: Record<string, string>;\n fetcher: typeof fetch;\n /** Forwarded into Ollama's per-request `options` block. */\n defaultOptions?: Record<string, unknown>;\n}\n\n/**\n * `LanguageModel` adapter for the local Ollama HTTP API\n * (`http://localhost:11434/api/chat`). Talks the native Ollama protocol\n * (NDJSON streaming, function-calling shape) — not the OpenAI-compat\n * shim, which loses tool-call fidelity on several models.\n *\n * Sovereign-pillar primitive (RFC 0004 §v0.1.9): an open-weight default\n * provider so the SDK is not assumed-cloud-only.\n */\nexport class OllamaChatModel implements LanguageModel {\n readonly provider = 'ollama';\n readonly modelId: string;\n private readonly config: OllamaChatModelConfig;\n\n constructor(config: OllamaChatModelConfig) {\n this.modelId = config.modelId;\n this.config = config;\n }\n\n async generate(options: ModelCallOptions): Promise<ModelGenerateResult> {\n const body = this.buildBody(options, false);\n const res = await this.fetch('/api/chat', body, options);\n const json = (await res.json()) as OllamaChatResponse;\n\n const text = json.message?.content ?? '';\n const toolCalls: ToolCallPart[] =\n json.message?.tool_calls?.map((tc, i) => ({\n type: 'tool-call' as const,\n toolCallId: synthesizeToolCallId(tc.function?.name ?? 'unknown', i),\n toolName: tc.function?.name ?? '',\n args: tc.function?.arguments ?? {},\n })) ?? [];\n\n return {\n text,\n content: [...(text.length > 0 ? [{ type: 'text' as const, text }] : []), ...toolCalls],\n toolCalls,\n finishReason: mapFinishReason(json),\n usage: mapUsage(json),\n rawResponse: json,\n };\n }\n\n async stream(options: ModelCallOptions): Promise<ReadableStream<ModelStreamPart>> {\n const body = this.buildBody(options, true);\n const res = await this.fetch('/api/chat', body, options);\n if (!res.body) {\n throw new APICallError({\n message: 'Ollama streaming response has no body.',\n statusCode: res.status,\n });\n }\n\n const ndjson = parseNDJSON<OllamaChatResponse>(res.body);\n\n return new ReadableStream<ModelStreamPart>({\n async start(controller) {\n let usage: TokenUsage | undefined;\n let finish: FinishReason = 'unknown';\n let toolIdx = 0;\n\n try {\n for await (const chunk of ndjson) {\n if (chunk.message?.content) {\n controller.enqueue({ type: 'text-delta', textDelta: chunk.message.content });\n }\n if (chunk.message?.tool_calls) {\n for (const tc of chunk.message.tool_calls) {\n const id = synthesizeToolCallId(tc.function?.name ?? 'unknown', toolIdx++);\n // Ollama emits each tool call complete (no incremental\n // arg streaming), so we forward the full call directly\n // — matching the OpenAI provider's terminal `tool-call`\n // event shape.\n controller.enqueue({\n type: 'tool-call',\n toolCallId: id,\n toolName: tc.function?.name ?? '',\n args: tc.function?.arguments ?? {},\n });\n }\n }\n if (chunk.done) {\n finish = mapFinishReason(chunk);\n usage = mapUsage(chunk);\n }\n }\n controller.enqueue({ type: 'finish', finishReason: finish, usage: usage ?? {} });\n controller.close();\n } catch (err) {\n controller.enqueue({ type: 'error', error: err });\n controller.close();\n }\n },\n });\n }\n\n /**\n * Local models are free at runtime — their cost is electricity / GPU\n * time, not per-token billing. We report `pricingAvailable: true`\n * with `$0` so `Budget Guard.maxUsd` constraints simply never trip\n * for Ollama runs (instead of being silently disabled, which would\n * surprise callers migrating from OpenAI).\n *\n * `maxTokens`, `maxLlmCalls`, `maxDurationMs`, and `maxSteps` budgets\n * keep working as documented — those are the meaningful limits when\n * GPU time is the bottleneck.\n */\n estimateCost(options: ModelCallOptions): CostEstimate {\n const inputTokens = estimateTokensFromMessages(asChatMessages(options.messages));\n const maxOut = options.maxTokens ?? 8_192;\n const minOut = Math.min(16, maxOut);\n return {\n minTokens: inputTokens + minOut,\n maxTokens: inputTokens + maxOut,\n minUsd: 0,\n maxUsd: 0,\n pricingAvailable: true,\n };\n }\n\n private buildBody(options: ModelCallOptions, stream: boolean): Record<string, unknown> {\n const ollamaOptions: Record<string, unknown> = {\n ...(this.config.defaultOptions ?? {}),\n };\n if (options.temperature !== undefined) ollamaOptions.temperature = options.temperature;\n if (options.topP !== undefined) ollamaOptions.top_p = options.topP;\n if (options.maxTokens !== undefined) ollamaOptions.num_predict = options.maxTokens;\n if (options.stopSequences !== undefined) ollamaOptions.stop = options.stopSequences;\n if (options.seed !== undefined) ollamaOptions.seed = options.seed;\n\n const body: Record<string, unknown> = {\n model: this.modelId,\n messages: options.messages.map(toOllamaMessage),\n stream,\n };\n if (Object.keys(ollamaOptions).length > 0) body.options = ollamaOptions;\n if (options.tools?.length) {\n body.tools = options.tools.map((t) => ({\n type: 'function',\n function: {\n name: t.name,\n ...(t.description !== undefined ? { description: t.description } : {}),\n parameters: t.parameters,\n },\n }));\n }\n if (options.providerOptions) Object.assign(body, options.providerOptions);\n return body;\n }\n\n private async fetch(path: string, body: unknown, options: ModelCallOptions): Promise<Response> {\n const url = `${this.config.baseURL}${path}`;\n const headers = { ...this.config.headers, ...options.headers };\n const init: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n };\n if (options.abortSignal) init.signal = options.abortSignal;\n\n const res = await this.config.fetcher(url, init);\n if (!res.ok) {\n const text = await res.text().catch(() => '');\n throw new APICallError({\n message: `Ollama API error: ${res.status} ${res.statusText}`,\n url,\n statusCode: res.status,\n responseBody: text,\n });\n }\n return res;\n }\n}\n\nfunction toOllamaMessage(m: NormalizedMessage): unknown {\n switch (m.role) {\n case 'system':\n case 'user': {\n const text = m.content\n .filter((p) => p.type === 'text')\n .map((p) => (p as { text: string }).text)\n .join('');\n const images = m.content\n .filter((p) => p.type === 'image')\n .map((p) => {\n const img = (p as { image: string | URL | Uint8Array }).image;\n if (typeof img === 'string') return img.replace(/^data:[^;]+;base64,/, '');\n if (img instanceof URL) return img.toString();\n return uint8ToBase64(img);\n });\n const out: Record<string, unknown> = { role: m.role, content: text };\n if (images.length > 0) out.images = images;\n return out;\n }\n case 'assistant': {\n const text = m.content\n .filter((p) => p.type === 'text')\n .map((p) => (p as { text: string }).text)\n .join('');\n const toolCalls = m.content.filter((p) => p.type === 'tool-call');\n const out: Record<string, unknown> = { role: 'assistant', content: text };\n if (toolCalls.length > 0) {\n out.tool_calls = toolCalls.map((tc) => ({\n function: {\n name: (tc as ToolCallPart).toolName,\n arguments: (tc as ToolCallPart).args ?? {},\n },\n }));\n }\n return out;\n }\n case 'tool': {\n const first = m.content[0];\n if (!first || first.type !== 'tool-result') {\n return { role: 'tool', content: '' };\n }\n return {\n role: 'tool',\n content: typeof first.result === 'string' ? first.result : JSON.stringify(first.result),\n };\n }\n }\n}\n\n/**\n * Ollama's `tool_calls[]` entries don't carry a stable id — they're\n * just `{ function: { name, arguments } }`. We synthesise an id so the\n * downstream agent loop can match tool results back to calls without\n * collisions across a batch.\n */\nfunction synthesizeToolCallId(name: string, index: number): string {\n return `ollama_${name}_${index}_${Math.random().toString(36).slice(2, 8)}`;\n}\n\nfunction asChatMessages(\n messages: NormalizedMessage[],\n): Parameters<typeof estimateTokensFromMessages>[0] {\n return messages as unknown as Parameters<typeof estimateTokensFromMessages>[0];\n}\n\nfunction uint8ToBase64(arr: Uint8Array): string {\n let s = '';\n for (let i = 0; i < arr.byteLength; i++) s += String.fromCharCode(arr[i] as number);\n return typeof btoa !== 'undefined' ? btoa(s) : Buffer.from(s, 'binary').toString('base64');\n}\n\nfunction mapFinishReason(json: OllamaChatResponse): FinishReason {\n if (json.message?.tool_calls?.length) return 'tool-calls';\n if (json.done_reason === 'stop' || json.done) return 'stop';\n if (json.done_reason === 'length') return 'length';\n return 'unknown';\n}\n\nfunction mapUsage(json: OllamaChatResponse): TokenUsage {\n const out: TokenUsage = {};\n if (json.prompt_eval_count !== undefined) out.promptTokens = json.prompt_eval_count;\n if (json.eval_count !== undefined) out.completionTokens = json.eval_count;\n if (json.prompt_eval_count !== undefined && json.eval_count !== undefined) {\n out.totalTokens = json.prompt_eval_count + json.eval_count;\n }\n return out;\n}\n\ninterface OllamaChatResponse {\n model?: string;\n created_at?: string;\n message?: {\n role?: string;\n content?: string;\n tool_calls?: Array<{\n function?: {\n name?: string;\n arguments?: Record<string, unknown>;\n };\n }>;\n };\n done?: boolean;\n done_reason?: 'stop' | 'length' | 'load' | string;\n total_duration?: number;\n load_duration?: number;\n prompt_eval_count?: number;\n prompt_eval_duration?: number;\n eval_count?: number;\n eval_duration?: number;\n}\n","import type { LanguageModel } from '@ziro-agent/core';\nimport { OllamaChatModel, type OllamaChatModelId } from './ollama-chat-model.js';\n\nexport interface OllamaProviderOptions {\n /**\n * Base URL of the Ollama daemon. Defaults to\n * `process.env.OLLAMA_BASE_URL` then `http://localhost:11434`.\n *\n * For remote / containerised Ollama (e.g. compose stack, Coolify),\n * set this to `http://ollama:11434` or whatever your network exposes.\n */\n baseURL?: string;\n /** Extra default headers attached to every request. */\n headers?: Record<string, string>;\n /** Custom `fetch`. Defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n /**\n * Default Ollama-native sampling options (`num_ctx`, `mirostat`,\n * `repeat_penalty`, …) merged into every request's `options` block.\n * Per-call overrides via `ModelCallOptions.providerOptions.options`\n * still win.\n */\n defaultOptions?: Record<string, unknown>;\n}\n\nexport interface OllamaProvider {\n (modelId: OllamaChatModelId): LanguageModel;\n chat(modelId: OllamaChatModelId): LanguageModel;\n}\n\n/**\n * Build an {@link OllamaProvider} bound to a specific Ollama daemon.\n * Mirrors `createOpenAI` / `createAnthropic` so swapping providers in\n * `createAgent({ model })` is a one-line change.\n */\nexport function createOllama(options: OllamaProviderOptions = {}): OllamaProvider {\n const baseURL = (\n options.baseURL ??\n loadEnv('OLLAMA_BASE_URL') ??\n 'http://localhost:11434'\n ).replace(/\\/+$/, '');\n const fetcher = options.fetch ?? globalThis.fetch;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...options.headers,\n };\n\n const make = (modelId: OllamaChatModelId): LanguageModel =>\n new OllamaChatModel({\n modelId,\n baseURL,\n headers,\n fetcher,\n ...(options.defaultOptions ? { defaultOptions: options.defaultOptions } : {}),\n });\n\n const provider = ((modelId: OllamaChatModelId) => make(modelId)) as OllamaProvider;\n provider.chat = make;\n return provider;\n}\n\n/**\n * Default singleton — connects to `localhost:11434` (or\n * `OLLAMA_BASE_URL` if set). Suitable for the typical\n * `ollama serve` setup; build a custom provider with `createOllama()`\n * for remote / authenticated daemons.\n */\nexport const ollama: OllamaProvider = createOllama();\n\nfunction loadEnv(name: string): string | undefined {\n if (typeof process !== 'undefined' && process.env) {\n return process.env[name];\n }\n return undefined;\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ziro-agent/ollama",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Ollama provider for ZiroAgent SDK — run open-weight LLMs locally with the same interface as OpenAI / Anthropic. Sovereign pillar primitive.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://ziroagent.com",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/ziroagent/sdk-typescript.git",
|
|
10
|
+
"directory": "packages/providers-ollama"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/ziroagent/sdk-typescript/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"ai",
|
|
17
|
+
"llm",
|
|
18
|
+
"ollama",
|
|
19
|
+
"local",
|
|
20
|
+
"open-weight",
|
|
21
|
+
"sovereign",
|
|
22
|
+
"ziroagent"
|
|
23
|
+
],
|
|
24
|
+
"type": "module",
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"main": "./dist/index.cjs",
|
|
27
|
+
"module": "./dist/index.js",
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"import": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"default": "./dist/index.js"
|
|
34
|
+
},
|
|
35
|
+
"require": {
|
|
36
|
+
"types": "./dist/index.d.cts",
|
|
37
|
+
"default": "./dist/index.cjs"
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"./package.json": "./package.json"
|
|
41
|
+
},
|
|
42
|
+
"files": [
|
|
43
|
+
"dist",
|
|
44
|
+
"README.md",
|
|
45
|
+
"LICENSE"
|
|
46
|
+
],
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"@ziro-agent/core": "0.4.0"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@arethetypeswrong/cli": "^0.18.2",
|
|
52
|
+
"msw": "^2.11.7",
|
|
53
|
+
"publint": "^0.3.18",
|
|
54
|
+
"tsup": "^8.5.1",
|
|
55
|
+
"typescript": "^5.9.3",
|
|
56
|
+
"vitest": "^4.1.4"
|
|
57
|
+
},
|
|
58
|
+
"engines": {
|
|
59
|
+
"node": ">=20.10.0"
|
|
60
|
+
},
|
|
61
|
+
"publishConfig": {
|
|
62
|
+
"access": "public"
|
|
63
|
+
},
|
|
64
|
+
"author": "ZiroAgent <hello@ziroagent.com> (https://ziroagent.com)",
|
|
65
|
+
"scripts": {
|
|
66
|
+
"build": "tsup",
|
|
67
|
+
"dev": "tsup --watch",
|
|
68
|
+
"test": "vitest run",
|
|
69
|
+
"test:watch": "vitest",
|
|
70
|
+
"typecheck": "tsc --noEmit",
|
|
71
|
+
"clean": "rm -rf dist .turbo *.tsbuildinfo",
|
|
72
|
+
"publint": "publint",
|
|
73
|
+
"attw": "attw --pack . --profile=node16"
|
|
74
|
+
}
|
|
75
|
+
}
|