@mayurajs/provider-ollama 0.0.0-stage → 1.1.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 +201 -0
- package/NOTICE +8 -0
- package/README.md +32 -2
- package/dist/index.d.ts +40 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +343 -0
- package/dist/index.js.map +1 -0
- package/package.json +45 -4
- package/src/index.ts +288 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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 reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and 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
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
Mayura
|
|
2
|
+
Copyright 2026 The Mayura Authors
|
|
3
|
+
|
|
4
|
+
This product includes software developed by the Mayura contributors.
|
|
5
|
+
|
|
6
|
+
Third-party dependencies retain their own copyright and license terms. Exact
|
|
7
|
+
resolved versions are recorded in pnpm-lock.yaml and reviewed by the release
|
|
8
|
+
artifact and dependency qualification procedures.
|
package/README.md
CHANGED
|
@@ -1,3 +1,33 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mayurajs/provider-ollama
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Ollama models for [Mayura](https://mayurajs.com), on your own machine or in Ollama's cloud, through the official `ollama` SDK.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install mayura @mayurajs/provider-ollama
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { createModels, defineAgent, z } from 'mayura';
|
|
11
|
+
import { ollama } from '@mayurajs/provider-ollama';
|
|
12
|
+
|
|
13
|
+
const models = createModels({
|
|
14
|
+
providers: [ollama()], // http://127.0.0.1:11434
|
|
15
|
+
prices: { 'ollama/gpt-oss:20b': { inputMicrosPerMillionTokens: 0, outputMicrosPerMillionTokens: 0 } },
|
|
16
|
+
maxCallCostMicros: 1,
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const agent = defineAgent({
|
|
20
|
+
id: 'helper', version: '1', instructions: 'Answer in one sentence.', model: models.model('ollama/gpt-oss:20b'), tools: [],
|
|
21
|
+
input: z.object({ question: z.string() }), output: z.object({ answer: z.string() }),
|
|
22
|
+
});
|
|
23
|
+
// Grant it as model:ollama/gpt-oss:20b.
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
- Local models cost nothing, so there is no catalog: give each model's price, zero or your own.
|
|
27
|
+
- `host` is http only on a loopback address, https anywhere else. For Ollama's cloud, use `ollama({ host: 'https://ollama.com', apiKey })`.
|
|
28
|
+
- Nothing is read from the environment (not `OLLAMA_HOST` or `OLLAMA_API_KEY`) or the file system.
|
|
29
|
+
- Structured output and tool inputs use JSON Schema. With tools, the answer comes from one more call, in the format, once the model calls no more tools (a format leaves no way to call a tool). Ollama's cloud accepts a format without enforcing it, so a request with one also gives the schema in its instructions; streaming reports output text as it arrives; set `think` for a thinking model, whose thinking is kept for the next call and never released.
|
|
30
|
+
- Models see no media unless you say so: pass `media: { types: ['image/png', 'image/jpeg'], urls: false }` for a vision model.
|
|
31
|
+
- The default time limit is 120 seconds, since a local model may need loading first.
|
|
32
|
+
|
|
33
|
+
See the [model registry guide](https://mayurajs.com/docs/guides/model-registry/). Apache-2.0.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type ModelMediaCapability, type ModelProvider } from 'mayura';
|
|
2
|
+
export interface OllamaProviderOptions {
|
|
3
|
+
/**
|
|
4
|
+
* The Ollama server: a loopback address over http (the default is http://127.0.0.1:11434), or any https URL, such as
|
|
5
|
+
* https://ollama.com for Ollama's cloud models or a gateway.
|
|
6
|
+
*/
|
|
7
|
+
readonly host?: string;
|
|
8
|
+
/** An API key, sent as a bearer token. Required for https://ollama.com: the provider never reads OLLAMA_API_KEY. */
|
|
9
|
+
readonly apiKey?: string;
|
|
10
|
+
/** Extra headers, such as a gateway's credential. Treated as credentials. They cannot replace Authorization. */
|
|
11
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
12
|
+
/** Whether and how hard thinking models think. Leave it unset for a model that does not think. */
|
|
13
|
+
readonly think?: boolean | 'low' | 'medium' | 'high';
|
|
14
|
+
/** What the models can see. The default is nothing; give PNG or JPEG images (as bytes) for a vision model. */
|
|
15
|
+
readonly media?: ModelMediaCapability | false;
|
|
16
|
+
readonly maxRequestBytes?: number;
|
|
17
|
+
readonly maxResponseBytes?: number;
|
|
18
|
+
/** How long one call may take unless the registry sets `timeoutMs` (default 120 s, as a local model may need loading first). */
|
|
19
|
+
readonly timeoutMs?: number;
|
|
20
|
+
/** A trusted transport for tests or proxies. Never selected from model output. */
|
|
21
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Ollama models for a Mayura model registry, local or in Ollama's cloud, through the official Ollama SDK:
|
|
25
|
+
*
|
|
26
|
+
* ```ts
|
|
27
|
+
* const models = createModels({
|
|
28
|
+
* providers: [ollama()],
|
|
29
|
+
* prices: { 'ollama/gpt-oss:20b': { inputMicrosPerMillionTokens: 0, outputMicrosPerMillionTokens: 0 } },
|
|
30
|
+
* maxCallCostMicros: 1,
|
|
31
|
+
* });
|
|
32
|
+
* const model = models.model('ollama/gpt-oss:20b'); // granted as model:ollama/gpt-oss:20b
|
|
33
|
+
* ```
|
|
34
|
+
*
|
|
35
|
+
* Local models cost nothing, so there is no catalog: give each model's price, zero or your own. Structured output
|
|
36
|
+
* and tool inputs use JSON Schema; streaming reports output text as it arrives; the model's thinking is kept for the
|
|
37
|
+
* next call of the run and never released. Nothing is read from the environment or the file system.
|
|
38
|
+
*/
|
|
39
|
+
export declare function ollama(options?: OllamaProviderOptions): ModelProvider;
|
|
40
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAC+C,KAAK,oBAAoB,EAAqB,KAAK,aAAa,EAC7C,MAAM,QAAQ,CAAC;AAGxF,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,oHAAoH;IACpH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,gHAAgH;IAChH,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACpD,kGAAkG;IAClG,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;IACrD,8GAA8G;IAC9G,QAAQ,CAAC,KAAK,CAAC,EAAE,oBAAoB,GAAG,KAAK,CAAC;IAC9C,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,gIAAgI;IAChI,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,kFAAkF;IAClF,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CAC1C;AA6HD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,MAAM,CAAC,OAAO,GAAE,qBAA0B,GAAG,aAAa,CAwHzE"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
import { Ollama } from 'ollama/browser';
|
|
2
|
+
import { assertPositiveInteger, jsonValue, MayuraError, ModelProviderError } from 'mayura';
|
|
3
|
+
import { bytesToBase64, checkStrictDefinition, encodedMediaBytes, modelToolNames, providerHeaders, providerHttpFailure, streamModelCall, strictJsonSchema, tokenCostMicros } from 'mayura/core/host';
|
|
4
|
+
const OLLAMA_MEDIA = Object.freeze(['image/png', 'image/jpeg']);
|
|
5
|
+
const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
6
|
+
const failed = (reason = 'invalid_response') => { throw new ModelProviderError(reason); };
|
|
7
|
+
const reasonOf = (error) => error instanceof ModelProviderError ? error.reason : 'invalid_response';
|
|
8
|
+
function object(value) {
|
|
9
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
10
|
+
return failed();
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
function integer(value) {
|
|
14
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
|
|
15
|
+
return failed();
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
function mediaOption(value) {
|
|
19
|
+
if (value === undefined || value === false)
|
|
20
|
+
return undefined;
|
|
21
|
+
if (!Array.isArray(value.types) || value.types.length === 0 || value.types.some(type => !OLLAMA_MEDIA.includes(type)) || value.urls !== false) {
|
|
22
|
+
throw new MayuraError('INVALID_CONFIG', 'media must list PNG or JPEG images, sent as bytes (urls: false).');
|
|
23
|
+
}
|
|
24
|
+
return Object.freeze({ types: Object.freeze([...new Set(value.types)]), urls: false });
|
|
25
|
+
}
|
|
26
|
+
/** The server's base URL: http only on a loopback address, https anywhere; no credentials, query or fragment. */
|
|
27
|
+
function hostOf(value) {
|
|
28
|
+
if (value === undefined)
|
|
29
|
+
return 'http://127.0.0.1:11434';
|
|
30
|
+
let url;
|
|
31
|
+
try {
|
|
32
|
+
url = new URL(typeof value === 'string' ? value : '');
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
throw new MayuraError('INVALID_CONFIG', 'ollama(): host must be an absolute URL.');
|
|
36
|
+
}
|
|
37
|
+
if (!(url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK.has(url.hostname))) || url.username || url.password || url.search || url.hash || url.href.length > 2_048) {
|
|
38
|
+
throw new MayuraError('INVALID_CONFIG', 'ollama(): host must be http on a loopback address or https, without credentials, query or fragment.');
|
|
39
|
+
}
|
|
40
|
+
return url.href.replace(/\/+$/u, '');
|
|
41
|
+
}
|
|
42
|
+
/** A response larger than the configured limit; reported as an unusable response. */
|
|
43
|
+
class ResponseTooLarge extends Error {
|
|
44
|
+
}
|
|
45
|
+
/** The server could not be reached, for example because Ollama is not running. */
|
|
46
|
+
class ConnectionFailure extends Error {
|
|
47
|
+
}
|
|
48
|
+
/** An error status; its body, which may echo the request, is never read. */
|
|
49
|
+
class HttpFailure extends Error {
|
|
50
|
+
status;
|
|
51
|
+
constructor(status) {
|
|
52
|
+
super('HTTP failure');
|
|
53
|
+
this.status = status;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* One call's transport: cancelled by the call's signal (the SDK passes none for a non-streamed call), no redirects, an
|
|
58
|
+
* error status reported without reading its body, and a body larger than `limit` (four times that for a stream) fails.
|
|
59
|
+
*/
|
|
60
|
+
function callFetch(transport, limit, signal) {
|
|
61
|
+
return async (input, init) => {
|
|
62
|
+
let response;
|
|
63
|
+
try {
|
|
64
|
+
response = await transport(input, { ...init, signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal, redirect: 'error' });
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
if (signal.aborted)
|
|
68
|
+
throw error;
|
|
69
|
+
throw new ConnectionFailure('Ollama could not be reached.', { cause: error });
|
|
70
|
+
}
|
|
71
|
+
if (!response.ok) {
|
|
72
|
+
void response.body?.cancel().catch(() => undefined);
|
|
73
|
+
throw new HttpFailure(response.status);
|
|
74
|
+
}
|
|
75
|
+
const max = (response.headers.get('content-type') ?? '').includes('ndjson') ? limit * 4 : limit;
|
|
76
|
+
const length = response.headers.get('content-length');
|
|
77
|
+
if (length !== null && (!/^\d+$/u.test(length) || Number(length) > max)) {
|
|
78
|
+
void response.body?.cancel().catch(() => undefined);
|
|
79
|
+
throw new ResponseTooLarge();
|
|
80
|
+
}
|
|
81
|
+
if (!response.body)
|
|
82
|
+
return response;
|
|
83
|
+
let size = 0;
|
|
84
|
+
const counted = response.body.pipeThrough(new TransformStream({
|
|
85
|
+
transform(chunk, controller) { size += chunk.byteLength; if (size > max)
|
|
86
|
+
controller.error(new ResponseTooLarge());
|
|
87
|
+
else
|
|
88
|
+
controller.enqueue(chunk); },
|
|
89
|
+
}));
|
|
90
|
+
return new Response(counted, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/** Images as base64, as Ollama takes them. */
|
|
94
|
+
function images(media) {
|
|
95
|
+
if (!media?.length)
|
|
96
|
+
return {};
|
|
97
|
+
return { images: media.map(item => 'data' in item && OLLAMA_MEDIA.includes(item.mediaType) ? bytesToBase64(item.data) : failed('configuration')) };
|
|
98
|
+
}
|
|
99
|
+
/** Image names, which Ollama's image list cannot carry, follow the text. */
|
|
100
|
+
const withNames = (text, media) => {
|
|
101
|
+
const names = (media ?? []).flatMap(item => item.name === undefined ? [] : [item.name]);
|
|
102
|
+
return names.length ? `${text}\n\nImages, in order: ${names.join(', ')}` : text;
|
|
103
|
+
};
|
|
104
|
+
/** The conversation as Ollama chat messages; `assistants` are the model's own earlier tool-call turns. */
|
|
105
|
+
function messagesFor(request, aliases, assistants) {
|
|
106
|
+
let turn = 0;
|
|
107
|
+
return [{ role: 'system', content: request.instructions }, ...request.messages.map((message) => {
|
|
108
|
+
if (message.role === 'user')
|
|
109
|
+
return { role: 'user', content: withNames(JSON.stringify(message.content), message.media), ...images(message.media) };
|
|
110
|
+
if (message.role === 'tool') {
|
|
111
|
+
const name = aliases.get(message.toolId);
|
|
112
|
+
if (!name)
|
|
113
|
+
return failed();
|
|
114
|
+
return { role: 'tool', tool_name: name, content: withNames(JSON.stringify(message.result), message.media), ...images(message.media) };
|
|
115
|
+
}
|
|
116
|
+
const toolCalls = message.calls.map(call => {
|
|
117
|
+
const name = aliases.get(call.toolId);
|
|
118
|
+
if (!name)
|
|
119
|
+
return failed();
|
|
120
|
+
return { function: { name, arguments: call.input } };
|
|
121
|
+
});
|
|
122
|
+
const own = assistants[turn++];
|
|
123
|
+
if (own && (own.calls.length !== message.calls.length || own.calls.some((id, index) => id !== message.calls[index].id)))
|
|
124
|
+
return failed();
|
|
125
|
+
return { role: 'assistant', content: '', ...(own?.thinking ? { thinking: own.thinking } : {}), tool_calls: toolCalls };
|
|
126
|
+
})];
|
|
127
|
+
}
|
|
128
|
+
/** Ids for a response's tool calls, which Ollama does not give: unique within the run. */
|
|
129
|
+
function callIds(request, count) {
|
|
130
|
+
const used = new Set(request.messages.flatMap(message => message.role === 'assistant' ? message.calls.map(call => call.id) : message.role === 'tool' ? [message.callId] : []));
|
|
131
|
+
const ids = [];
|
|
132
|
+
for (let next = used.size + 1; ids.length < count; next++)
|
|
133
|
+
if (!used.has(`call_${next}`))
|
|
134
|
+
ids.push(`call_${next}`);
|
|
135
|
+
return ids;
|
|
136
|
+
}
|
|
137
|
+
/** Rebuilds the response a non-streamed call returns from Ollama's stream, reporting text as it arrives. */
|
|
138
|
+
async function assemble(chunks, maxResponseBytes, onDelta) {
|
|
139
|
+
let content = '';
|
|
140
|
+
let thinking = '';
|
|
141
|
+
const toolCalls = [];
|
|
142
|
+
let last;
|
|
143
|
+
try {
|
|
144
|
+
for await (const raw of chunks) {
|
|
145
|
+
const data = object(jsonValue(JSON.parse(JSON.stringify(raw)), { maxBytes: maxResponseBytes }));
|
|
146
|
+
const message = data['message'] === undefined ? {} : object(data['message']);
|
|
147
|
+
if (typeof message['content'] === 'string' && message['content']) {
|
|
148
|
+
content += message['content'];
|
|
149
|
+
onDelta(message['content']);
|
|
150
|
+
}
|
|
151
|
+
if (typeof message['thinking'] === 'string')
|
|
152
|
+
thinking += message['thinking'];
|
|
153
|
+
if (Array.isArray(message['tool_calls'])) {
|
|
154
|
+
toolCalls.push(...message['tool_calls']);
|
|
155
|
+
if (toolCalls.length > 128)
|
|
156
|
+
return failed();
|
|
157
|
+
}
|
|
158
|
+
if (data['done'] === true)
|
|
159
|
+
last = data;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
// The server reported an error mid-answer, or ended the stream without finishing it.
|
|
164
|
+
if (error instanceof ModelProviderError || error instanceof ResponseTooLarge || error instanceof SyntaxError)
|
|
165
|
+
throw error;
|
|
166
|
+
return failed('unavailable');
|
|
167
|
+
}
|
|
168
|
+
if (!last)
|
|
169
|
+
return failed();
|
|
170
|
+
return { ...last, message: { role: 'assistant', content, ...(thinking ? { thinking } : {}), ...(toolCalls.length ? { tool_calls: toolCalls } : {}) } };
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Ollama models for a Mayura model registry, local or in Ollama's cloud, through the official Ollama SDK:
|
|
174
|
+
*
|
|
175
|
+
* ```ts
|
|
176
|
+
* const models = createModels({
|
|
177
|
+
* providers: [ollama()],
|
|
178
|
+
* prices: { 'ollama/gpt-oss:20b': { inputMicrosPerMillionTokens: 0, outputMicrosPerMillionTokens: 0 } },
|
|
179
|
+
* maxCallCostMicros: 1,
|
|
180
|
+
* });
|
|
181
|
+
* const model = models.model('ollama/gpt-oss:20b'); // granted as model:ollama/gpt-oss:20b
|
|
182
|
+
* ```
|
|
183
|
+
*
|
|
184
|
+
* Local models cost nothing, so there is no catalog: give each model's price, zero or your own. Structured output
|
|
185
|
+
* and tool inputs use JSON Schema; streaming reports output text as it arrives; the model's thinking is kept for the
|
|
186
|
+
* next call of the run and never released. Nothing is read from the environment or the file system.
|
|
187
|
+
*/
|
|
188
|
+
export function ollama(options = {}) {
|
|
189
|
+
if (!options || typeof options !== 'object')
|
|
190
|
+
throw new MayuraError('INVALID_CONFIG', 'ollama() options must be an object.');
|
|
191
|
+
const host = hostOf(options.host);
|
|
192
|
+
if (options.apiKey !== undefined && (typeof options.apiKey !== 'string' || !options.apiKey.trim() || /[\r\n]/u.test(options.apiKey) || options.apiKey.length > 4096)) {
|
|
193
|
+
throw new MayuraError('INVALID_CONFIG', 'ollama(): apiKey must be a non-empty string.');
|
|
194
|
+
}
|
|
195
|
+
// The SDK falls back to OLLAMA_API_KEY for ollama.com; the key must be given instead.
|
|
196
|
+
if (new URL(host).hostname === 'ollama.com' && options.apiKey === undefined)
|
|
197
|
+
throw new MayuraError('INVALID_CONFIG', 'ollama(): https://ollama.com needs an apiKey.');
|
|
198
|
+
const headers = { ...providerHeaders(options.headers, ['Authorization', 'Accept', 'User-Agent'], 'ollama()'), ...(options.apiKey === undefined ? {} : { Authorization: `Bearer ${options.apiKey}` }) };
|
|
199
|
+
if (options.think !== undefined && ![true, false, 'low', 'medium', 'high'].includes(options.think))
|
|
200
|
+
throw new MayuraError('INVALID_CONFIG', 'ollama(): think must be true, false, low, medium or high.');
|
|
201
|
+
const maxRequestBytes = options.maxRequestBytes ?? 1_048_576;
|
|
202
|
+
const maxResponseBytes = options.maxResponseBytes ?? 1_048_576;
|
|
203
|
+
const defaultTimeout = options.timeoutMs ?? 120_000;
|
|
204
|
+
for (const [value, name] of [[maxRequestBytes, 'maxRequestBytes'], [maxResponseBytes, 'maxResponseBytes'], [defaultTimeout, 'timeoutMs']])
|
|
205
|
+
assertPositiveInteger(value, name);
|
|
206
|
+
const media = mediaOption(options.media);
|
|
207
|
+
return Object.freeze({
|
|
208
|
+
id: 'ollama',
|
|
209
|
+
model(name, settings) {
|
|
210
|
+
if (typeof name !== 'string' || !name.trim() || name.length > 128)
|
|
211
|
+
throw new MayuraError('INVALID_CONFIG', 'An Ollama model name is required.');
|
|
212
|
+
const timeoutMs = settings.timeoutMs ?? defaultTimeout;
|
|
213
|
+
const call = async (request, onDelta, consumer) => {
|
|
214
|
+
const controller = new AbortController();
|
|
215
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
216
|
+
let knownCost;
|
|
217
|
+
let inputTokens = 0;
|
|
218
|
+
let outputTokens = 0;
|
|
219
|
+
try {
|
|
220
|
+
const signal = AbortSignal.any([request.signal, controller.signal, ...(consumer ? [consumer] : [])]);
|
|
221
|
+
if (signal.aborted)
|
|
222
|
+
throw new MayuraError('CANCELLED', 'Provider request was cancelled.');
|
|
223
|
+
let assistants = [];
|
|
224
|
+
if (request.continuation !== undefined) {
|
|
225
|
+
const previous = object(request.continuation);
|
|
226
|
+
if (previous['provider'] !== 'ollama.chat.v1' || previous['model'] !== name || !Array.isArray(previous['assistants']))
|
|
227
|
+
return failed();
|
|
228
|
+
assistants = previous['assistants'].map(raw => {
|
|
229
|
+
const turn = object(raw);
|
|
230
|
+
if ((turn['thinking'] !== null && typeof turn['thinking'] !== 'string') || !Array.isArray(turn['calls']) || turn['calls'].some(id => typeof id !== 'string'))
|
|
231
|
+
return failed();
|
|
232
|
+
return { thinking: turn['thinking'], calls: turn['calls'] };
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
if (assistants.length > request.messages.filter(message => message.role === 'assistant').length)
|
|
236
|
+
return failed();
|
|
237
|
+
assertPositiveInteger(request.maxOutputTokens, 'maxOutputTokens');
|
|
238
|
+
const aliases = new Map(modelToolNames(request.tools.map(tool => tool.id)));
|
|
239
|
+
const ids = new Map([...aliases].map(([toolId, alias]) => [alias, toolId]));
|
|
240
|
+
if (aliases.size !== request.tools.length || aliases.size > 128)
|
|
241
|
+
return failed();
|
|
242
|
+
const tools = request.tools.map(tool => {
|
|
243
|
+
if (!tool.inputJsonSchema)
|
|
244
|
+
throw new MayuraError('INVALID_CONFIG', `Tool "${tool.id}" has no inputJsonSchema.`);
|
|
245
|
+
return { type: 'function', function: { name: aliases.get(tool.id), description: tool.description, parameters: strictJsonSchema(tool.inputJsonSchema, `Tool "${tool.id}" input schema`) } };
|
|
246
|
+
});
|
|
247
|
+
const outputSchema = request.outputJsonSchema === undefined ? failed('configuration') : strictJsonSchema(request.outputJsonSchema, 'The output schema');
|
|
248
|
+
// A format constrains a reply to the answer, which leaves no way to call a tool. So with tools, the model first
|
|
249
|
+
// answers freely; once it calls no more tools, one more call without tools asks for the answer in the format.
|
|
250
|
+
const messages = messagesFor(request, aliases, assistants);
|
|
251
|
+
const common = { model: name, messages, options: { num_predict: request.maxOutputTokens }, ...(options.think === undefined ? {} : { think: options.think }) };
|
|
252
|
+
// Ollama's cloud accepts a format without enforcing it, so a request with one also gives the schema in its instructions.
|
|
253
|
+
const formatted = { ...common, format: outputSchema, messages: [
|
|
254
|
+
{ role: 'system', content: `${request.instructions}\n\nAnswer with one JSON object, and nothing else, that matches this JSON Schema:\n${JSON.stringify(outputSchema)}` }, ...messages.slice(1)
|
|
255
|
+
] };
|
|
256
|
+
const body = tools.length > 0 ? { ...common, tools } : formatted;
|
|
257
|
+
jsonValue(body, { maxBytes: maxRequestBytes + encodedMediaBytes(request.messages) });
|
|
258
|
+
// A client per call, so the call's signal reaches every request it makes.
|
|
259
|
+
const client = new Ollama({ host, headers, fetch: callFetch(options.fetch ?? globalThis.fetch, maxResponseBytes, signal) });
|
|
260
|
+
const chat = async (request, stream) => {
|
|
261
|
+
const payload = stream
|
|
262
|
+
? await assemble(await client.chat({ ...request, stream: true }), maxResponseBytes, stream)
|
|
263
|
+
: object(jsonValue(JSON.parse(JSON.stringify(await client.chat({ ...request, stream: false }))), { maxBytes: maxResponseBytes * 2 }));
|
|
264
|
+
// Ollama leaves out the prompt count when the whole prompt was cached.
|
|
265
|
+
const prompt = payload['prompt_eval_count'] === undefined ? 0 : integer(payload['prompt_eval_count']);
|
|
266
|
+
const completion = integer(payload['eval_count']);
|
|
267
|
+
knownCost = (knownCost ?? 0) + (tokenCostMicros(settings.pricing, prompt, completion) ?? failed());
|
|
268
|
+
inputTokens += prompt;
|
|
269
|
+
outputTokens += completion;
|
|
270
|
+
if (payload['done'] !== true)
|
|
271
|
+
return failed();
|
|
272
|
+
return payload;
|
|
273
|
+
};
|
|
274
|
+
const finalFrom = (payload) => {
|
|
275
|
+
const message = object(payload['message']);
|
|
276
|
+
const finish = payload['done_reason'];
|
|
277
|
+
// Output cut off by the token limit is not an answer.
|
|
278
|
+
if (finish === 'length')
|
|
279
|
+
return failed('refused');
|
|
280
|
+
if (finish !== 'stop' || typeof message['content'] !== 'string' || (Array.isArray(message['tool_calls']) && message['tool_calls'].length > 0))
|
|
281
|
+
return failed();
|
|
282
|
+
return { type: 'final', output: jsonValue(JSON.parse(message['content']), { maxBytes: maxResponseBytes }), usage: { costMicros: knownCost, inputTokens, outputTokens } };
|
|
283
|
+
};
|
|
284
|
+
if (tools.length === 0)
|
|
285
|
+
return finalFrom(await chat(body, onDelta));
|
|
286
|
+
// The free reply is never streamed: it may be prose, which is not the answer.
|
|
287
|
+
const payload = await chat(body, onDelta ? () => undefined : undefined);
|
|
288
|
+
const message = object(payload['message']);
|
|
289
|
+
const finish = payload['done_reason'];
|
|
290
|
+
const toolCalls = message['tool_calls'] ?? [];
|
|
291
|
+
if (!Array.isArray(toolCalls) || toolCalls.length > 128)
|
|
292
|
+
return failed();
|
|
293
|
+
if (toolCalls.length > 0 && finish === 'stop') {
|
|
294
|
+
const given = callIds(request, toolCalls.length);
|
|
295
|
+
const calls = toolCalls.map((raw, index) => {
|
|
296
|
+
const fn = object(object(raw)['function']);
|
|
297
|
+
const alias = fn['name'];
|
|
298
|
+
const args = fn['arguments'];
|
|
299
|
+
if (typeof alias !== 'string' || !ids.has(alias))
|
|
300
|
+
return failed();
|
|
301
|
+
const input = typeof args === 'string' ? JSON.parse(args || '{}') : args === undefined ? {} : object(args);
|
|
302
|
+
return { id: given[index], toolId: ids.get(alias), input: jsonValue(input, { maxBytes: maxResponseBytes }) };
|
|
303
|
+
});
|
|
304
|
+
const thinking = typeof message['thinking'] === 'string' && message['thinking'] ? message['thinking'] : null;
|
|
305
|
+
const continuation = jsonValue({ provider: 'ollama.chat.v1', model: name, assistants: [...assistants, { thinking, calls: calls.map(entry => entry.id) }] }, { maxBytes: maxRequestBytes });
|
|
306
|
+
return { type: 'tool_calls', calls, usage: { costMicros: knownCost, inputTokens, outputTokens }, continuation };
|
|
307
|
+
}
|
|
308
|
+
if (finish === 'length')
|
|
309
|
+
return failed('refused');
|
|
310
|
+
if (finish !== 'stop')
|
|
311
|
+
return failed();
|
|
312
|
+
return finalFrom(await chat(formatted, onDelta));
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
if (knownCost !== undefined)
|
|
316
|
+
throw new ModelProviderError(reasonOf(error), { costMicros: knownCost });
|
|
317
|
+
if (request.signal.aborted || controller.signal.aborted || consumer?.aborted)
|
|
318
|
+
throw new MayuraError('CANCELLED', 'Provider request was cancelled or timed out.');
|
|
319
|
+
if (error instanceof ModelProviderError)
|
|
320
|
+
throw error;
|
|
321
|
+
if (error instanceof MayuraError && error.code === 'INVALID_CONFIG')
|
|
322
|
+
return failed('configuration');
|
|
323
|
+
if (error instanceof HttpFailure)
|
|
324
|
+
throw providerHttpFailure(error.status);
|
|
325
|
+
if (error instanceof ConnectionFailure)
|
|
326
|
+
return failed('unavailable');
|
|
327
|
+
return failed();
|
|
328
|
+
}
|
|
329
|
+
finally {
|
|
330
|
+
clearTimeout(timer);
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
return Object.freeze({
|
|
334
|
+
id: settings.id, maxCostMicros: settings.maxCostMicros,
|
|
335
|
+
capabilities: Object.freeze({ tools: true, structuredOutput: true, ...(media ? { media } : {}) }),
|
|
336
|
+
checkDefinition: (definition) => checkStrictDefinition(definition),
|
|
337
|
+
generate: (request) => call(request),
|
|
338
|
+
stream: (request) => streamModelCall((onDelta, consumer) => call(request, onDelta, consumer)),
|
|
339
|
+
});
|
|
340
|
+
},
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,gBA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AAE,CAAC,qBAAqB,CAAC,UAAU,CAAC;gBAC9F,QAAQ,EAAE,CAAC,OAAqB,EAA0B,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC;gBAC1E,MAAM,EAAE,CAAC,OAAqB,EAAmC,EAAE,CAAC,eAAe,CAAC,CAAC,OAAO,EAAE,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;aAC7I,CAAC,CAAC;QACL,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { Ollama } from 'ollama/browser';\nimport { assertPositiveInteger, jsonValue, MayuraError, ModelProviderError, type JsonObject, type JsonValue, type Media, type MediaType, type ModelAdapter,\n type ModelDefinitionCheck, type ModelFailureReason, type ModelMediaCapability, type ModelMessage, type ModelProvider, type ModelRequest, type ModelResponse,\n type ModelStreamEvent, type ModelToolCall, type ProviderModelSettings } from 'mayura';\nimport { bytesToBase64, checkStrictDefinition, encodedMediaBytes, modelToolNames, providerHeaders, providerHttpFailure, streamModelCall, strictJsonSchema, tokenCostMicros } from 'mayura/core/host';\n\nexport interface OllamaProviderOptions {\n /**\n * The Ollama server: a loopback address over http (the default is http://127.0.0.1:11434), or any https URL, such as\n * https://ollama.com for Ollama's cloud models or a gateway.\n */\n readonly host?: string;\n /** An API key, sent as a bearer token. Required for https://ollama.com: the provider never reads OLLAMA_API_KEY. */\n readonly apiKey?: string;\n /** Extra headers, such as a gateway's credential. Treated as credentials. They cannot replace Authorization. */\n readonly headers?: Readonly<Record<string, string>>;\n /** Whether and how hard thinking models think. Leave it unset for a model that does not think. */\n readonly think?: boolean | 'low' | 'medium' | 'high';\n /** What the models can see. The default is nothing; give PNG or JPEG images (as bytes) for a vision model. */\n readonly media?: ModelMediaCapability | false;\n readonly maxRequestBytes?: number;\n readonly maxResponseBytes?: number;\n /** How long one call may take unless the registry sets `timeoutMs` (default 120 s, as a local model may need loading first). */\n readonly timeoutMs?: number;\n /** A trusted transport for tests or proxies. Never selected from model output. */\n readonly fetch?: typeof globalThis.fetch;\n}\n\nconst OLLAMA_MEDIA: readonly MediaType[] = Object.freeze(['image/png', 'image/jpeg']);\nconst LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nconst failed = (reason: ModelFailureReason = 'invalid_response'): never => { throw new ModelProviderError(reason); };\nconst reasonOf = (error: unknown): ModelFailureReason => error instanceof ModelProviderError ? error.reason : 'invalid_response';\nfunction object(value: JsonValue | undefined): JsonObject {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return failed();\n return value;\n}\nfunction integer(value: JsonValue | undefined): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) return failed();\n return value;\n}\nfunction mediaOption(value: ModelMediaCapability | false | undefined): ModelMediaCapability | undefined {\n if (value === undefined || value === false) return undefined;\n if (!Array.isArray(value.types) || value.types.length === 0 || value.types.some(type => !OLLAMA_MEDIA.includes(type)) || value.urls !== false) {\n throw new MayuraError('INVALID_CONFIG', 'media must list PNG or JPEG images, sent as bytes (urls: false).');\n }\n return Object.freeze({ types: Object.freeze([...new Set(value.types)] as MediaType[]), urls: false });\n}\n/** The server's base URL: http only on a loopback address, https anywhere; no credentials, query or fragment. */\nfunction hostOf(value: unknown): string {\n if (value === undefined) return 'http://127.0.0.1:11434';\n let url: URL;\n try { url = new URL(typeof value === 'string' ? value : ''); } catch { throw new MayuraError('INVALID_CONFIG', 'ollama(): host must be an absolute URL.'); }\n if (!(url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK.has(url.hostname))) || url.username || url.password || url.search || url.hash || url.href.length > 2_048) {\n throw new MayuraError('INVALID_CONFIG', 'ollama(): host must be http on a loopback address or https, without credentials, query or fragment.');\n }\n return url.href.replace(/\\/+$/u, '');\n}\n\n/** A response larger than the configured limit; reported as an unusable response. */\nclass ResponseTooLarge extends Error {}\n/** The server could not be reached, for example because Ollama is not running. */\nclass ConnectionFailure extends Error {}\n/** An error status; its body, which may echo the request, is never read. */\nclass HttpFailure extends Error { constructor(readonly status: number) { super('HTTP failure'); } }\n/**\n * One call's transport: cancelled by the call's signal (the SDK passes none for a non-streamed call), no redirects, an\n * error status reported without reading its body, and a body larger than `limit` (four times that for a stream) fails.\n */\nfunction callFetch(transport: typeof globalThis.fetch, limit: number, signal: AbortSignal): typeof globalThis.fetch {\n return async (input, init) => {\n let response: Response;\n try {\n response = await transport(input, { ...init, signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal, redirect: 'error' });\n } catch (error) {\n if (signal.aborted) throw error;\n throw new ConnectionFailure('Ollama could not be reached.', { cause: error });\n }\n if (!response.ok) { void response.body?.cancel().catch(() => undefined); throw new HttpFailure(response.status); }\n const max = (response.headers.get('content-type') ?? '').includes('ndjson') ? limit * 4 : limit;\n const length = response.headers.get('content-length');\n if (length !== null && (!/^\\d+$/u.test(length) || Number(length) > max)) { void response.body?.cancel().catch(() => undefined); throw new ResponseTooLarge(); }\n if (!response.body) return response;\n let size = 0;\n const counted = response.body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) { size += chunk.byteLength; if (size > max) controller.error(new ResponseTooLarge()); else controller.enqueue(chunk); },\n }));\n return new Response(counted, { status: response.status, statusText: response.statusText, headers: response.headers });\n };\n}\n\n/** Images as base64, as Ollama takes them. */\nfunction images(media: readonly Media[] | undefined): { images?: string[] } {\n if (!media?.length) return {};\n return { images: media.map(item => 'data' in item && OLLAMA_MEDIA.includes(item.mediaType) ? bytesToBase64(item.data) : failed('configuration')) };\n}\n/** Image names, which Ollama's image list cannot carry, follow the text. */\nconst withNames = (text: string, media: readonly Media[] | undefined): string => {\n const names = (media ?? []).flatMap(item => item.name === undefined ? [] : [item.name]);\n return names.length ? `${text}\\n\\nImages, in order: ${names.join(', ')}` : text;\n};\n\n/** One of the model's own tool-call turns in this run: its thinking and the ids given to its calls. */\ntype OwnTurn = { thinking: string | null; calls: string[] };\n/** The conversation as Ollama chat messages; `assistants` are the model's own earlier tool-call turns. */\nfunction messagesFor(request: ModelRequest, aliases: ReadonlyMap<string, string>, assistants: readonly OwnTurn[]): JsonValue[] {\n let turn = 0;\n return [{ role: 'system', content: request.instructions }, ...(request.messages as readonly ModelMessage[]).map((message): JsonValue => {\n if (message.role === 'user') return { role: 'user', content: withNames(JSON.stringify(message.content), message.media), ...images(message.media) };\n if (message.role === 'tool') {\n const name = aliases.get(message.toolId); if (!name) return failed();\n return { role: 'tool', tool_name: name, content: withNames(JSON.stringify(message.result), message.media), ...images(message.media) };\n }\n const toolCalls = message.calls.map(call => {\n const name = aliases.get(call.toolId); if (!name) return failed();\n return { function: { name, arguments: call.input } };\n });\n const own = assistants[turn++];\n if (own && (own.calls.length !== message.calls.length || own.calls.some((id, index) => id !== message.calls[index]!.id))) return failed();\n return { role: 'assistant', content: '', ...(own?.thinking ? { thinking: own.thinking } : {}), tool_calls: toolCalls };\n })];\n}\n/** Ids for a response's tool calls, which Ollama does not give: unique within the run. */\nfunction callIds(request: ModelRequest, count: number): string[] {\n const used = new Set(request.messages.flatMap(message => message.role === 'assistant' ? message.calls.map(call => call.id) : message.role === 'tool' ? [message.callId] : []));\n const ids: string[] = [];\n for (let next = used.size + 1; ids.length < count; next++) if (!used.has(`call_${next}`)) ids.push(`call_${next}`);\n return ids;\n}\n\n/** Rebuilds the response a non-streamed call returns from Ollama's stream, reporting text as it arrives. */\nasync function assemble(chunks: AsyncIterable<unknown>, maxResponseBytes: number, onDelta: (text: string) => void): Promise<JsonObject> {\n let content = ''; let thinking = ''; const toolCalls: JsonValue[] = []; let last: JsonObject | undefined;\n try {\n for await (const raw of chunks) {\n const data = object(jsonValue(JSON.parse(JSON.stringify(raw)) as JsonValue, { maxBytes: maxResponseBytes }));\n const message = data['message'] === undefined ? {} : object(data['message']);\n if (typeof message['content'] === 'string' && message['content']) { content += message['content']; onDelta(message['content']); }\n if (typeof message['thinking'] === 'string') thinking += message['thinking'];\n if (Array.isArray(message['tool_calls'])) { toolCalls.push(...message['tool_calls']); if (toolCalls.length > 128) return failed(); }\n if (data['done'] === true) last = data;\n }\n } catch (error) {\n // The server reported an error mid-answer, or ended the stream without finishing it.\n if (error instanceof ModelProviderError || error instanceof ResponseTooLarge || error instanceof SyntaxError) throw error;\n return failed('unavailable');\n }\n if (!last) return failed();\n return { ...last, message: { role: 'assistant', content, ...(thinking ? { thinking } : {}), ...(toolCalls.length ? { tool_calls: toolCalls } : {}) } };\n}\n\n/**\n * Ollama models for a Mayura model registry, local or in Ollama's cloud, through the official Ollama SDK:\n *\n * ```ts\n * const models = createModels({\n * providers: [ollama()],\n * prices: { 'ollama/gpt-oss:20b': { inputMicrosPerMillionTokens: 0, outputMicrosPerMillionTokens: 0 } },\n * maxCallCostMicros: 1,\n * });\n * const model = models.model('ollama/gpt-oss:20b'); // granted as model:ollama/gpt-oss:20b\n * ```\n *\n * Local models cost nothing, so there is no catalog: give each model's price, zero or your own. Structured output\n * and tool inputs use JSON Schema; streaming reports output text as it arrives; the model's thinking is kept for the\n * next call of the run and never released. Nothing is read from the environment or the file system.\n */\nexport function ollama(options: OllamaProviderOptions = {}): ModelProvider {\n if (!options || typeof options !== 'object') throw new MayuraError('INVALID_CONFIG', 'ollama() options must be an object.');\n const host = hostOf(options.host);\n if (options.apiKey !== undefined && (typeof options.apiKey !== 'string' || !options.apiKey.trim() || /[\\r\\n]/u.test(options.apiKey) || options.apiKey.length > 4096)) {\n throw new MayuraError('INVALID_CONFIG', 'ollama(): apiKey must be a non-empty string.');\n }\n // The SDK falls back to OLLAMA_API_KEY for ollama.com; the key must be given instead.\n if (new URL(host).hostname === 'ollama.com' && options.apiKey === undefined) throw new MayuraError('INVALID_CONFIG', 'ollama(): https://ollama.com needs an apiKey.');\n const headers = { ...providerHeaders(options.headers, ['Authorization', 'Accept', 'User-Agent'], 'ollama()'), ...(options.apiKey === undefined ? {} : { Authorization: `Bearer ${options.apiKey}` }) };\n if (options.think !== undefined && ![true, false, 'low', 'medium', 'high'].includes(options.think)) throw new MayuraError('INVALID_CONFIG', 'ollama(): think must be true, false, low, medium or high.');\n const maxRequestBytes = options.maxRequestBytes ?? 1_048_576; const maxResponseBytes = options.maxResponseBytes ?? 1_048_576;\n const defaultTimeout = options.timeoutMs ?? 120_000;\n for (const [value, name] of [[maxRequestBytes, 'maxRequestBytes'], [maxResponseBytes, 'maxResponseBytes'], [defaultTimeout, 'timeoutMs']] as const) assertPositiveInteger(value, name);\n const media = mediaOption(options.media);\n\n return Object.freeze({\n id: 'ollama',\n model(name: string, settings: ProviderModelSettings): ModelAdapter {\n if (typeof name !== 'string' || !name.trim() || name.length > 128) throw new MayuraError('INVALID_CONFIG', 'An Ollama model name is required.');\n const timeoutMs = settings.timeoutMs ?? defaultTimeout;\n\n const call = async (request: ModelRequest, onDelta?: (text: string) => void, consumer?: AbortSignal): Promise<ModelResponse> => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n let knownCost: number | undefined; let inputTokens = 0; let outputTokens = 0;\n try {\n const signal = AbortSignal.any([request.signal, controller.signal, ...(consumer ? [consumer] : [])]);\n if (signal.aborted) throw new MayuraError('CANCELLED', 'Provider request was cancelled.');\n let assistants: OwnTurn[] = [];\n if (request.continuation !== undefined) {\n const previous = object(request.continuation);\n if (previous['provider'] !== 'ollama.chat.v1' || previous['model'] !== name || !Array.isArray(previous['assistants'])) return failed();\n assistants = previous['assistants'].map(raw => {\n const turn = object(raw);\n if ((turn['thinking'] !== null && typeof turn['thinking'] !== 'string') || !Array.isArray(turn['calls']) || turn['calls'].some(id => typeof id !== 'string')) return failed();\n return { thinking: turn['thinking'], calls: turn['calls'] as string[] };\n });\n }\n if (assistants.length > request.messages.filter(message => message.role === 'assistant').length) return failed();\n assertPositiveInteger(request.maxOutputTokens, 'maxOutputTokens');\n const aliases = new Map(modelToolNames(request.tools.map(tool => tool.id)));\n const ids = new Map([...aliases].map(([toolId, alias]) => [alias, toolId]));\n if (aliases.size !== request.tools.length || aliases.size > 128) return failed();\n const tools = request.tools.map(tool => {\n if (!tool.inputJsonSchema) throw new MayuraError('INVALID_CONFIG', `Tool \"${tool.id}\" has no inputJsonSchema.`);\n return { type: 'function', function: { name: aliases.get(tool.id)!, description: tool.description, parameters: strictJsonSchema(tool.inputJsonSchema, `Tool \"${tool.id}\" input schema`) } };\n });\n const outputSchema = request.outputJsonSchema === undefined ? failed('configuration') : strictJsonSchema(request.outputJsonSchema, 'The output schema');\n // A format constrains a reply to the answer, which leaves no way to call a tool. So with tools, the model first\n // answers freely; once it calls no more tools, one more call without tools asks for the answer in the format.\n const messages = messagesFor(request, aliases, assistants);\n const common = { model: name, messages, options: { num_predict: request.maxOutputTokens }, ...(options.think === undefined ? {} : { think: options.think }) };\n // Ollama's cloud accepts a format without enforcing it, so a request with one also gives the schema in its instructions.\n const formatted: JsonObject = { ...common, format: outputSchema, messages: [\n { role: 'system', content: `${request.instructions}\\n\\nAnswer with one JSON object, and nothing else, that matches this JSON Schema:\\n${JSON.stringify(outputSchema)}` }, ...messages.slice(1)] };\n const body: JsonObject = tools.length > 0 ? { ...common, tools } : formatted;\n jsonValue(body, { maxBytes: maxRequestBytes + encodedMediaBytes(request.messages) });\n\n // A client per call, so the call's signal reaches every request it makes.\n const client = new Ollama({ host, headers, fetch: callFetch(options.fetch ?? globalThis.fetch, maxResponseBytes, signal) });\n const chat = async (request: JsonObject, stream: ((text: string) => void) | undefined): Promise<JsonObject> => {\n const payload = stream\n ? await assemble(await client.chat({ ...request, stream: true } as never) as unknown as AsyncIterable<unknown>, maxResponseBytes, stream)\n : object(jsonValue(JSON.parse(JSON.stringify(await client.chat({ ...request, stream: false } as never))) as JsonValue, { maxBytes: maxResponseBytes * 2 }));\n // Ollama leaves out the prompt count when the whole prompt was cached.\n const prompt = payload['prompt_eval_count'] === undefined ? 0 : integer(payload['prompt_eval_count']); const completion = integer(payload['eval_count']);\n knownCost = (knownCost ?? 0) + (tokenCostMicros(settings.pricing, prompt, completion) ?? failed());\n inputTokens += prompt; outputTokens += completion;\n if (payload['done'] !== true) return failed();\n return payload;\n };\n const finalFrom = (payload: JsonObject): ModelResponse => {\n const message = object(payload['message']); const finish = payload['done_reason'];\n // Output cut off by the token limit is not an answer.\n if (finish === 'length') return failed('refused');\n if (finish !== 'stop' || typeof message['content'] !== 'string' || (Array.isArray(message['tool_calls']) && message['tool_calls'].length > 0)) return failed();\n return { type: 'final', output: jsonValue(JSON.parse(message['content']) as JsonValue, { maxBytes: maxResponseBytes }), usage: { costMicros: knownCost!, inputTokens, outputTokens } };\n };\n if (tools.length === 0) return finalFrom(await chat(body, onDelta));\n\n // The free reply is never streamed: it may be prose, which is not the answer.\n const payload = await chat(body, onDelta ? () => undefined : undefined);\n const message = object(payload['message']); const finish = payload['done_reason'];\n const toolCalls = message['tool_calls'] ?? [];\n if (!Array.isArray(toolCalls) || toolCalls.length > 128) return failed();\n if (toolCalls.length > 0 && finish === 'stop') {\n const given = callIds(request, toolCalls.length);\n const calls: ModelToolCall[] = toolCalls.map((raw, index) => {\n const fn = object(object(raw)['function']); const alias = fn['name']; const args = fn['arguments'];\n if (typeof alias !== 'string' || !ids.has(alias)) return failed();\n const input = typeof args === 'string' ? JSON.parse(args || '{}') as JsonValue : args === undefined ? {} : object(args);\n return { id: given[index]!, toolId: ids.get(alias)!, input: jsonValue(input, { maxBytes: maxResponseBytes }) };\n });\n const thinking = typeof message['thinking'] === 'string' && message['thinking'] ? message['thinking'] : null;\n const continuation = jsonValue({ provider: 'ollama.chat.v1', model: name, assistants: [...assistants, { thinking, calls: calls.map(entry => entry.id) }] }, { maxBytes: maxRequestBytes });\n return { type: 'tool_calls', calls, usage: { costMicros: knownCost!, inputTokens, outputTokens }, continuation };\n }\n if (finish === 'length') return failed('refused');\n if (finish !== 'stop') return failed();\n return finalFrom(await chat(formatted, onDelta));\n } catch (error) {\n if (knownCost !== undefined) throw new ModelProviderError(reasonOf(error), { costMicros: knownCost });\n if (request.signal.aborted || controller.signal.aborted || consumer?.aborted) throw new MayuraError('CANCELLED', 'Provider request was cancelled or timed out.');\n if (error instanceof ModelProviderError) throw error;\n if (error instanceof MayuraError && error.code === 'INVALID_CONFIG') return failed('configuration');\n if (error instanceof HttpFailure) throw providerHttpFailure(error.status);\n if (error instanceof ConnectionFailure) return failed('unavailable');\n return failed();\n } finally { clearTimeout(timer); }\n };\n\n return Object.freeze({\n id: settings.id, maxCostMicros: settings.maxCostMicros,\n capabilities: Object.freeze({ tools: true, structuredOutput: true, ...(media ? { media } : {}) }),\n checkDefinition: (definition: ModelDefinitionCheck): void => checkStrictDefinition(definition),\n generate: (request: ModelRequest): Promise<ModelResponse> => call(request),\n stream: (request: ModelRequest): AsyncIterable<ModelStreamEvent> => streamModelCall((onDelta, consumer) => call(request, onDelta, consumer)),\n });\n },\n });\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mayurajs/provider-ollama",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Ollama models for Mayura, local or in Ollama's cloud, through the official Ollama SDK.",
|
|
5
|
+
"author": {
|
|
6
|
+
"name": "Aryabh",
|
|
7
|
+
"email": "dev@rokad.co"
|
|
8
|
+
},
|
|
9
|
+
"license": "Apache-2.0",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/KartikeyAI/mayura.git",
|
|
13
|
+
"directory": "extensions/provider-ollama"
|
|
14
|
+
},
|
|
15
|
+
"homepage": "https://github.com/KartikeyAI/mayura#readme",
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/KartikeyAI/mayura/issues"
|
|
18
|
+
},
|
|
19
|
+
"type": "module",
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=22.12.0 <23 || >=24.14.1 <25"
|
|
23
|
+
},
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"src/**/*.ts",
|
|
33
|
+
"README.md",
|
|
34
|
+
"LICENSE",
|
|
35
|
+
"NOTICE"
|
|
36
|
+
],
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"ollama": "0.6.3"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"mayura": "^1.1.0"
|
|
42
|
+
},
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public",
|
|
45
|
+
"provenance": true
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import { Ollama } from 'ollama/browser';
|
|
2
|
+
import { assertPositiveInteger, jsonValue, MayuraError, ModelProviderError, type JsonObject, type JsonValue, type Media, type MediaType, type ModelAdapter,
|
|
3
|
+
type ModelDefinitionCheck, type ModelFailureReason, type ModelMediaCapability, type ModelMessage, type ModelProvider, type ModelRequest, type ModelResponse,
|
|
4
|
+
type ModelStreamEvent, type ModelToolCall, type ProviderModelSettings } from 'mayura';
|
|
5
|
+
import { bytesToBase64, checkStrictDefinition, encodedMediaBytes, modelToolNames, providerHeaders, providerHttpFailure, streamModelCall, strictJsonSchema, tokenCostMicros } from 'mayura/core/host';
|
|
6
|
+
|
|
7
|
+
export interface OllamaProviderOptions {
|
|
8
|
+
/**
|
|
9
|
+
* The Ollama server: a loopback address over http (the default is http://127.0.0.1:11434), or any https URL, such as
|
|
10
|
+
* https://ollama.com for Ollama's cloud models or a gateway.
|
|
11
|
+
*/
|
|
12
|
+
readonly host?: string;
|
|
13
|
+
/** An API key, sent as a bearer token. Required for https://ollama.com: the provider never reads OLLAMA_API_KEY. */
|
|
14
|
+
readonly apiKey?: string;
|
|
15
|
+
/** Extra headers, such as a gateway's credential. Treated as credentials. They cannot replace Authorization. */
|
|
16
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
17
|
+
/** Whether and how hard thinking models think. Leave it unset for a model that does not think. */
|
|
18
|
+
readonly think?: boolean | 'low' | 'medium' | 'high';
|
|
19
|
+
/** What the models can see. The default is nothing; give PNG or JPEG images (as bytes) for a vision model. */
|
|
20
|
+
readonly media?: ModelMediaCapability | false;
|
|
21
|
+
readonly maxRequestBytes?: number;
|
|
22
|
+
readonly maxResponseBytes?: number;
|
|
23
|
+
/** How long one call may take unless the registry sets `timeoutMs` (default 120 s, as a local model may need loading first). */
|
|
24
|
+
readonly timeoutMs?: number;
|
|
25
|
+
/** A trusted transport for tests or proxies. Never selected from model output. */
|
|
26
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const OLLAMA_MEDIA: readonly MediaType[] = Object.freeze(['image/png', 'image/jpeg']);
|
|
30
|
+
const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
31
|
+
|
|
32
|
+
const failed = (reason: ModelFailureReason = 'invalid_response'): never => { throw new ModelProviderError(reason); };
|
|
33
|
+
const reasonOf = (error: unknown): ModelFailureReason => error instanceof ModelProviderError ? error.reason : 'invalid_response';
|
|
34
|
+
function object(value: JsonValue | undefined): JsonObject {
|
|
35
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return failed();
|
|
36
|
+
return value;
|
|
37
|
+
}
|
|
38
|
+
function integer(value: JsonValue | undefined): number {
|
|
39
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) return failed();
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
function mediaOption(value: ModelMediaCapability | false | undefined): ModelMediaCapability | undefined {
|
|
43
|
+
if (value === undefined || value === false) return undefined;
|
|
44
|
+
if (!Array.isArray(value.types) || value.types.length === 0 || value.types.some(type => !OLLAMA_MEDIA.includes(type)) || value.urls !== false) {
|
|
45
|
+
throw new MayuraError('INVALID_CONFIG', 'media must list PNG or JPEG images, sent as bytes (urls: false).');
|
|
46
|
+
}
|
|
47
|
+
return Object.freeze({ types: Object.freeze([...new Set(value.types)] as MediaType[]), urls: false });
|
|
48
|
+
}
|
|
49
|
+
/** The server's base URL: http only on a loopback address, https anywhere; no credentials, query or fragment. */
|
|
50
|
+
function hostOf(value: unknown): string {
|
|
51
|
+
if (value === undefined) return 'http://127.0.0.1:11434';
|
|
52
|
+
let url: URL;
|
|
53
|
+
try { url = new URL(typeof value === 'string' ? value : ''); } catch { throw new MayuraError('INVALID_CONFIG', 'ollama(): host must be an absolute URL.'); }
|
|
54
|
+
if (!(url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK.has(url.hostname))) || url.username || url.password || url.search || url.hash || url.href.length > 2_048) {
|
|
55
|
+
throw new MayuraError('INVALID_CONFIG', 'ollama(): host must be http on a loopback address or https, without credentials, query or fragment.');
|
|
56
|
+
}
|
|
57
|
+
return url.href.replace(/\/+$/u, '');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A response larger than the configured limit; reported as an unusable response. */
|
|
61
|
+
class ResponseTooLarge extends Error {}
|
|
62
|
+
/** The server could not be reached, for example because Ollama is not running. */
|
|
63
|
+
class ConnectionFailure extends Error {}
|
|
64
|
+
/** An error status; its body, which may echo the request, is never read. */
|
|
65
|
+
class HttpFailure extends Error { constructor(readonly status: number) { super('HTTP failure'); } }
|
|
66
|
+
/**
|
|
67
|
+
* One call's transport: cancelled by the call's signal (the SDK passes none for a non-streamed call), no redirects, an
|
|
68
|
+
* error status reported without reading its body, and a body larger than `limit` (four times that for a stream) fails.
|
|
69
|
+
*/
|
|
70
|
+
function callFetch(transport: typeof globalThis.fetch, limit: number, signal: AbortSignal): typeof globalThis.fetch {
|
|
71
|
+
return async (input, init) => {
|
|
72
|
+
let response: Response;
|
|
73
|
+
try {
|
|
74
|
+
response = await transport(input, { ...init, signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal, redirect: 'error' });
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (signal.aborted) throw error;
|
|
77
|
+
throw new ConnectionFailure('Ollama could not be reached.', { cause: error });
|
|
78
|
+
}
|
|
79
|
+
if (!response.ok) { void response.body?.cancel().catch(() => undefined); throw new HttpFailure(response.status); }
|
|
80
|
+
const max = (response.headers.get('content-type') ?? '').includes('ndjson') ? limit * 4 : limit;
|
|
81
|
+
const length = response.headers.get('content-length');
|
|
82
|
+
if (length !== null && (!/^\d+$/u.test(length) || Number(length) > max)) { void response.body?.cancel().catch(() => undefined); throw new ResponseTooLarge(); }
|
|
83
|
+
if (!response.body) return response;
|
|
84
|
+
let size = 0;
|
|
85
|
+
const counted = response.body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
|
|
86
|
+
transform(chunk, controller) { size += chunk.byteLength; if (size > max) controller.error(new ResponseTooLarge()); else controller.enqueue(chunk); },
|
|
87
|
+
}));
|
|
88
|
+
return new Response(counted, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Images as base64, as Ollama takes them. */
|
|
93
|
+
function images(media: readonly Media[] | undefined): { images?: string[] } {
|
|
94
|
+
if (!media?.length) return {};
|
|
95
|
+
return { images: media.map(item => 'data' in item && OLLAMA_MEDIA.includes(item.mediaType) ? bytesToBase64(item.data) : failed('configuration')) };
|
|
96
|
+
}
|
|
97
|
+
/** Image names, which Ollama's image list cannot carry, follow the text. */
|
|
98
|
+
const withNames = (text: string, media: readonly Media[] | undefined): string => {
|
|
99
|
+
const names = (media ?? []).flatMap(item => item.name === undefined ? [] : [item.name]);
|
|
100
|
+
return names.length ? `${text}\n\nImages, in order: ${names.join(', ')}` : text;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
/** One of the model's own tool-call turns in this run: its thinking and the ids given to its calls. */
|
|
104
|
+
type OwnTurn = { thinking: string | null; calls: string[] };
|
|
105
|
+
/** The conversation as Ollama chat messages; `assistants` are the model's own earlier tool-call turns. */
|
|
106
|
+
function messagesFor(request: ModelRequest, aliases: ReadonlyMap<string, string>, assistants: readonly OwnTurn[]): JsonValue[] {
|
|
107
|
+
let turn = 0;
|
|
108
|
+
return [{ role: 'system', content: request.instructions }, ...(request.messages as readonly ModelMessage[]).map((message): JsonValue => {
|
|
109
|
+
if (message.role === 'user') return { role: 'user', content: withNames(JSON.stringify(message.content), message.media), ...images(message.media) };
|
|
110
|
+
if (message.role === 'tool') {
|
|
111
|
+
const name = aliases.get(message.toolId); if (!name) return failed();
|
|
112
|
+
return { role: 'tool', tool_name: name, content: withNames(JSON.stringify(message.result), message.media), ...images(message.media) };
|
|
113
|
+
}
|
|
114
|
+
const toolCalls = message.calls.map(call => {
|
|
115
|
+
const name = aliases.get(call.toolId); if (!name) return failed();
|
|
116
|
+
return { function: { name, arguments: call.input } };
|
|
117
|
+
});
|
|
118
|
+
const own = assistants[turn++];
|
|
119
|
+
if (own && (own.calls.length !== message.calls.length || own.calls.some((id, index) => id !== message.calls[index]!.id))) return failed();
|
|
120
|
+
return { role: 'assistant', content: '', ...(own?.thinking ? { thinking: own.thinking } : {}), tool_calls: toolCalls };
|
|
121
|
+
})];
|
|
122
|
+
}
|
|
123
|
+
/** Ids for a response's tool calls, which Ollama does not give: unique within the run. */
|
|
124
|
+
function callIds(request: ModelRequest, count: number): string[] {
|
|
125
|
+
const used = new Set(request.messages.flatMap(message => message.role === 'assistant' ? message.calls.map(call => call.id) : message.role === 'tool' ? [message.callId] : []));
|
|
126
|
+
const ids: string[] = [];
|
|
127
|
+
for (let next = used.size + 1; ids.length < count; next++) if (!used.has(`call_${next}`)) ids.push(`call_${next}`);
|
|
128
|
+
return ids;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Rebuilds the response a non-streamed call returns from Ollama's stream, reporting text as it arrives. */
|
|
132
|
+
async function assemble(chunks: AsyncIterable<unknown>, maxResponseBytes: number, onDelta: (text: string) => void): Promise<JsonObject> {
|
|
133
|
+
let content = ''; let thinking = ''; const toolCalls: JsonValue[] = []; let last: JsonObject | undefined;
|
|
134
|
+
try {
|
|
135
|
+
for await (const raw of chunks) {
|
|
136
|
+
const data = object(jsonValue(JSON.parse(JSON.stringify(raw)) as JsonValue, { maxBytes: maxResponseBytes }));
|
|
137
|
+
const message = data['message'] === undefined ? {} : object(data['message']);
|
|
138
|
+
if (typeof message['content'] === 'string' && message['content']) { content += message['content']; onDelta(message['content']); }
|
|
139
|
+
if (typeof message['thinking'] === 'string') thinking += message['thinking'];
|
|
140
|
+
if (Array.isArray(message['tool_calls'])) { toolCalls.push(...message['tool_calls']); if (toolCalls.length > 128) return failed(); }
|
|
141
|
+
if (data['done'] === true) last = data;
|
|
142
|
+
}
|
|
143
|
+
} catch (error) {
|
|
144
|
+
// The server reported an error mid-answer, or ended the stream without finishing it.
|
|
145
|
+
if (error instanceof ModelProviderError || error instanceof ResponseTooLarge || error instanceof SyntaxError) throw error;
|
|
146
|
+
return failed('unavailable');
|
|
147
|
+
}
|
|
148
|
+
if (!last) return failed();
|
|
149
|
+
return { ...last, message: { role: 'assistant', content, ...(thinking ? { thinking } : {}), ...(toolCalls.length ? { tool_calls: toolCalls } : {}) } };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Ollama models for a Mayura model registry, local or in Ollama's cloud, through the official Ollama SDK:
|
|
154
|
+
*
|
|
155
|
+
* ```ts
|
|
156
|
+
* const models = createModels({
|
|
157
|
+
* providers: [ollama()],
|
|
158
|
+
* prices: { 'ollama/gpt-oss:20b': { inputMicrosPerMillionTokens: 0, outputMicrosPerMillionTokens: 0 } },
|
|
159
|
+
* maxCallCostMicros: 1,
|
|
160
|
+
* });
|
|
161
|
+
* const model = models.model('ollama/gpt-oss:20b'); // granted as model:ollama/gpt-oss:20b
|
|
162
|
+
* ```
|
|
163
|
+
*
|
|
164
|
+
* Local models cost nothing, so there is no catalog: give each model's price, zero or your own. Structured output
|
|
165
|
+
* and tool inputs use JSON Schema; streaming reports output text as it arrives; the model's thinking is kept for the
|
|
166
|
+
* next call of the run and never released. Nothing is read from the environment or the file system.
|
|
167
|
+
*/
|
|
168
|
+
export function ollama(options: OllamaProviderOptions = {}): ModelProvider {
|
|
169
|
+
if (!options || typeof options !== 'object') throw new MayuraError('INVALID_CONFIG', 'ollama() options must be an object.');
|
|
170
|
+
const host = hostOf(options.host);
|
|
171
|
+
if (options.apiKey !== undefined && (typeof options.apiKey !== 'string' || !options.apiKey.trim() || /[\r\n]/u.test(options.apiKey) || options.apiKey.length > 4096)) {
|
|
172
|
+
throw new MayuraError('INVALID_CONFIG', 'ollama(): apiKey must be a non-empty string.');
|
|
173
|
+
}
|
|
174
|
+
// The SDK falls back to OLLAMA_API_KEY for ollama.com; the key must be given instead.
|
|
175
|
+
if (new URL(host).hostname === 'ollama.com' && options.apiKey === undefined) throw new MayuraError('INVALID_CONFIG', 'ollama(): https://ollama.com needs an apiKey.');
|
|
176
|
+
const headers = { ...providerHeaders(options.headers, ['Authorization', 'Accept', 'User-Agent'], 'ollama()'), ...(options.apiKey === undefined ? {} : { Authorization: `Bearer ${options.apiKey}` }) };
|
|
177
|
+
if (options.think !== undefined && ![true, false, 'low', 'medium', 'high'].includes(options.think)) throw new MayuraError('INVALID_CONFIG', 'ollama(): think must be true, false, low, medium or high.');
|
|
178
|
+
const maxRequestBytes = options.maxRequestBytes ?? 1_048_576; const maxResponseBytes = options.maxResponseBytes ?? 1_048_576;
|
|
179
|
+
const defaultTimeout = options.timeoutMs ?? 120_000;
|
|
180
|
+
for (const [value, name] of [[maxRequestBytes, 'maxRequestBytes'], [maxResponseBytes, 'maxResponseBytes'], [defaultTimeout, 'timeoutMs']] as const) assertPositiveInteger(value, name);
|
|
181
|
+
const media = mediaOption(options.media);
|
|
182
|
+
|
|
183
|
+
return Object.freeze({
|
|
184
|
+
id: 'ollama',
|
|
185
|
+
model(name: string, settings: ProviderModelSettings): ModelAdapter {
|
|
186
|
+
if (typeof name !== 'string' || !name.trim() || name.length > 128) throw new MayuraError('INVALID_CONFIG', 'An Ollama model name is required.');
|
|
187
|
+
const timeoutMs = settings.timeoutMs ?? defaultTimeout;
|
|
188
|
+
|
|
189
|
+
const call = async (request: ModelRequest, onDelta?: (text: string) => void, consumer?: AbortSignal): Promise<ModelResponse> => {
|
|
190
|
+
const controller = new AbortController();
|
|
191
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
192
|
+
let knownCost: number | undefined; let inputTokens = 0; let outputTokens = 0;
|
|
193
|
+
try {
|
|
194
|
+
const signal = AbortSignal.any([request.signal, controller.signal, ...(consumer ? [consumer] : [])]);
|
|
195
|
+
if (signal.aborted) throw new MayuraError('CANCELLED', 'Provider request was cancelled.');
|
|
196
|
+
let assistants: OwnTurn[] = [];
|
|
197
|
+
if (request.continuation !== undefined) {
|
|
198
|
+
const previous = object(request.continuation);
|
|
199
|
+
if (previous['provider'] !== 'ollama.chat.v1' || previous['model'] !== name || !Array.isArray(previous['assistants'])) return failed();
|
|
200
|
+
assistants = previous['assistants'].map(raw => {
|
|
201
|
+
const turn = object(raw);
|
|
202
|
+
if ((turn['thinking'] !== null && typeof turn['thinking'] !== 'string') || !Array.isArray(turn['calls']) || turn['calls'].some(id => typeof id !== 'string')) return failed();
|
|
203
|
+
return { thinking: turn['thinking'], calls: turn['calls'] as string[] };
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
if (assistants.length > request.messages.filter(message => message.role === 'assistant').length) return failed();
|
|
207
|
+
assertPositiveInteger(request.maxOutputTokens, 'maxOutputTokens');
|
|
208
|
+
const aliases = new Map(modelToolNames(request.tools.map(tool => tool.id)));
|
|
209
|
+
const ids = new Map([...aliases].map(([toolId, alias]) => [alias, toolId]));
|
|
210
|
+
if (aliases.size !== request.tools.length || aliases.size > 128) return failed();
|
|
211
|
+
const tools = request.tools.map(tool => {
|
|
212
|
+
if (!tool.inputJsonSchema) throw new MayuraError('INVALID_CONFIG', `Tool "${tool.id}" has no inputJsonSchema.`);
|
|
213
|
+
return { type: 'function', function: { name: aliases.get(tool.id)!, description: tool.description, parameters: strictJsonSchema(tool.inputJsonSchema, `Tool "${tool.id}" input schema`) } };
|
|
214
|
+
});
|
|
215
|
+
const outputSchema = request.outputJsonSchema === undefined ? failed('configuration') : strictJsonSchema(request.outputJsonSchema, 'The output schema');
|
|
216
|
+
// A format constrains a reply to the answer, which leaves no way to call a tool. So with tools, the model first
|
|
217
|
+
// answers freely; once it calls no more tools, one more call without tools asks for the answer in the format.
|
|
218
|
+
const messages = messagesFor(request, aliases, assistants);
|
|
219
|
+
const common = { model: name, messages, options: { num_predict: request.maxOutputTokens }, ...(options.think === undefined ? {} : { think: options.think }) };
|
|
220
|
+
// Ollama's cloud accepts a format without enforcing it, so a request with one also gives the schema in its instructions.
|
|
221
|
+
const formatted: JsonObject = { ...common, format: outputSchema, messages: [
|
|
222
|
+
{ role: 'system', content: `${request.instructions}\n\nAnswer with one JSON object, and nothing else, that matches this JSON Schema:\n${JSON.stringify(outputSchema)}` }, ...messages.slice(1)] };
|
|
223
|
+
const body: JsonObject = tools.length > 0 ? { ...common, tools } : formatted;
|
|
224
|
+
jsonValue(body, { maxBytes: maxRequestBytes + encodedMediaBytes(request.messages) });
|
|
225
|
+
|
|
226
|
+
// A client per call, so the call's signal reaches every request it makes.
|
|
227
|
+
const client = new Ollama({ host, headers, fetch: callFetch(options.fetch ?? globalThis.fetch, maxResponseBytes, signal) });
|
|
228
|
+
const chat = async (request: JsonObject, stream: ((text: string) => void) | undefined): Promise<JsonObject> => {
|
|
229
|
+
const payload = stream
|
|
230
|
+
? await assemble(await client.chat({ ...request, stream: true } as never) as unknown as AsyncIterable<unknown>, maxResponseBytes, stream)
|
|
231
|
+
: object(jsonValue(JSON.parse(JSON.stringify(await client.chat({ ...request, stream: false } as never))) as JsonValue, { maxBytes: maxResponseBytes * 2 }));
|
|
232
|
+
// Ollama leaves out the prompt count when the whole prompt was cached.
|
|
233
|
+
const prompt = payload['prompt_eval_count'] === undefined ? 0 : integer(payload['prompt_eval_count']); const completion = integer(payload['eval_count']);
|
|
234
|
+
knownCost = (knownCost ?? 0) + (tokenCostMicros(settings.pricing, prompt, completion) ?? failed());
|
|
235
|
+
inputTokens += prompt; outputTokens += completion;
|
|
236
|
+
if (payload['done'] !== true) return failed();
|
|
237
|
+
return payload;
|
|
238
|
+
};
|
|
239
|
+
const finalFrom = (payload: JsonObject): ModelResponse => {
|
|
240
|
+
const message = object(payload['message']); const finish = payload['done_reason'];
|
|
241
|
+
// Output cut off by the token limit is not an answer.
|
|
242
|
+
if (finish === 'length') return failed('refused');
|
|
243
|
+
if (finish !== 'stop' || typeof message['content'] !== 'string' || (Array.isArray(message['tool_calls']) && message['tool_calls'].length > 0)) return failed();
|
|
244
|
+
return { type: 'final', output: jsonValue(JSON.parse(message['content']) as JsonValue, { maxBytes: maxResponseBytes }), usage: { costMicros: knownCost!, inputTokens, outputTokens } };
|
|
245
|
+
};
|
|
246
|
+
if (tools.length === 0) return finalFrom(await chat(body, onDelta));
|
|
247
|
+
|
|
248
|
+
// The free reply is never streamed: it may be prose, which is not the answer.
|
|
249
|
+
const payload = await chat(body, onDelta ? () => undefined : undefined);
|
|
250
|
+
const message = object(payload['message']); const finish = payload['done_reason'];
|
|
251
|
+
const toolCalls = message['tool_calls'] ?? [];
|
|
252
|
+
if (!Array.isArray(toolCalls) || toolCalls.length > 128) return failed();
|
|
253
|
+
if (toolCalls.length > 0 && finish === 'stop') {
|
|
254
|
+
const given = callIds(request, toolCalls.length);
|
|
255
|
+
const calls: ModelToolCall[] = toolCalls.map((raw, index) => {
|
|
256
|
+
const fn = object(object(raw)['function']); const alias = fn['name']; const args = fn['arguments'];
|
|
257
|
+
if (typeof alias !== 'string' || !ids.has(alias)) return failed();
|
|
258
|
+
const input = typeof args === 'string' ? JSON.parse(args || '{}') as JsonValue : args === undefined ? {} : object(args);
|
|
259
|
+
return { id: given[index]!, toolId: ids.get(alias)!, input: jsonValue(input, { maxBytes: maxResponseBytes }) };
|
|
260
|
+
});
|
|
261
|
+
const thinking = typeof message['thinking'] === 'string' && message['thinking'] ? message['thinking'] : null;
|
|
262
|
+
const continuation = jsonValue({ provider: 'ollama.chat.v1', model: name, assistants: [...assistants, { thinking, calls: calls.map(entry => entry.id) }] }, { maxBytes: maxRequestBytes });
|
|
263
|
+
return { type: 'tool_calls', calls, usage: { costMicros: knownCost!, inputTokens, outputTokens }, continuation };
|
|
264
|
+
}
|
|
265
|
+
if (finish === 'length') return failed('refused');
|
|
266
|
+
if (finish !== 'stop') return failed();
|
|
267
|
+
return finalFrom(await chat(formatted, onDelta));
|
|
268
|
+
} catch (error) {
|
|
269
|
+
if (knownCost !== undefined) throw new ModelProviderError(reasonOf(error), { costMicros: knownCost });
|
|
270
|
+
if (request.signal.aborted || controller.signal.aborted || consumer?.aborted) throw new MayuraError('CANCELLED', 'Provider request was cancelled or timed out.');
|
|
271
|
+
if (error instanceof ModelProviderError) throw error;
|
|
272
|
+
if (error instanceof MayuraError && error.code === 'INVALID_CONFIG') return failed('configuration');
|
|
273
|
+
if (error instanceof HttpFailure) throw providerHttpFailure(error.status);
|
|
274
|
+
if (error instanceof ConnectionFailure) return failed('unavailable');
|
|
275
|
+
return failed();
|
|
276
|
+
} finally { clearTimeout(timer); }
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
return Object.freeze({
|
|
280
|
+
id: settings.id, maxCostMicros: settings.maxCostMicros,
|
|
281
|
+
capabilities: Object.freeze({ tools: true, structuredOutput: true, ...(media ? { media } : {}) }),
|
|
282
|
+
checkDefinition: (definition: ModelDefinitionCheck): void => checkStrictDefinition(definition),
|
|
283
|
+
generate: (request: ModelRequest): Promise<ModelResponse> => call(request),
|
|
284
|
+
stream: (request: ModelRequest): AsyncIterable<ModelStreamEvent> => streamModelCall((onDelta, consumer) => call(request, onDelta, consumer)),
|
|
285
|
+
});
|
|
286
|
+
},
|
|
287
|
+
});
|
|
288
|
+
}
|