@mayurajs/provider-ollama 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE 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,38 @@
1
- # Temporary Holding Version
1
+ # @mayurajs/provider-ollama
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+ - A run's conversation history (`capabilities.history`) goes first on every call, the one for the answer in the format included. Tool calls get ids (`call_N`) that no earlier call of the conversation has.
31
+ - Models see no media unless you say so: pass `media: { types: ['image/png', 'image/jpeg'], urls: false }` for a vision model.
32
+ - The default time limit is 120 seconds, since a local model may need loading first.
33
+
34
+ See the [model registry guide](https://mayurajs.com/docs/guides/model-registry/). Apache-2.0.
35
+
36
+ ### RAG embeddings
37
+
38
+ This provider exports `ollamaEmbeddings` for scoped RAG ingestion and retrieval. See [the RAG guide](../../docs/guides/rag.md) for explicit permissions, cost ceilings and sensitivity profiles. Development cases are authored; validation is deferred.
@@ -0,0 +1,13 @@
1
+ import type { RagEmbedder } from 'mayura/rag';
2
+ import { type RagHttpOptions } from 'mayura/rag/host';
3
+ export interface EmbeddingsOptions extends Omit<RagHttpOptions, 'endpoint' | 'headers'> {
4
+ readonly model: string;
5
+ readonly dimensions: number;
6
+ readonly maxBatch: number;
7
+ readonly costMicros: number;
8
+ readonly endpoint: string;
9
+ readonly location: "local" | "hosted";
10
+ }
11
+ /** Explicit native embedding transport. Declared cost is the host's ceiling per bounded request. */
12
+ export declare function ollamaEmbeddings(options: EmbeddingsOptions): RagEmbedder;
13
+ //# sourceMappingURL=embeddings.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embeddings.d.ts","sourceRoot":"","sources":["../src/embeddings.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAuC,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAC3F,MAAM,WAAW,iBAAkB,SAAQ,IAAI,CAAC,cAAc,EAAC,UAAU,GAAC,SAAS,CAAC;IAClF,QAAQ,CAAC,KAAK,EAAC,MAAM,CAAC;IAAC,QAAQ,CAAC,UAAU,EAAC,MAAM,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAC,MAAM,CAAC;IAAC,QAAQ,CAAC,UAAU,EAAC,MAAM,CAAC;IACxG,QAAQ,CAAC,QAAQ,EAAC,MAAM,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAC,OAAO,GAAC,QAAQ,CAAC;CAC9D;AACD,oGAAoG;AACpG,wBAAgB,gBAAgB,CAAC,OAAO,EAAC,iBAAiB,GAAE,WAAW,CAYtE"}
@@ -0,0 +1,33 @@
1
+ import { MayuraError } from 'mayura/core';
2
+ import { cancelled, integer, ragHttp, vector } from 'mayura/rag/host';
3
+ /** Explicit native embedding transport. Declared cost is the host's ceiling per bounded request. */
4
+ export function ollamaEmbeddings(options) {
5
+ if (typeof options.model !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(options.model))
6
+ throw new MayuraError('INVALID_CONFIG', 'Embedding model must be explicit and bounded.');
7
+ const dimensions = integer(options.dimensions, 1, 4096);
8
+ const maxBatch = integer(options.maxBatch, 1, 128);
9
+ const costMicros = integer(options.costMicros, 0, Number.MAX_SAFE_INTEGER);
10
+ const endpoint = options.endpoint;
11
+ const url = new URL(endpoint);
12
+ if (!['local', 'hosted'].includes(options.location) || options.location === 'local' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
13
+ throw new MayuraError('INVALID_CONFIG', 'Local embedding location requires a loopback endpoint.');
14
+ const request = ragHttp('ollama-embeddings', { ...options, endpoint, headers: {} });
15
+ return Object.freeze({ id: `ollama.embeddings.${options.model}.${dimensions}`, dimensions, maxBatch, costMicros, location: options.location,
16
+ async embed(texts, signal) {
17
+ cancelled(signal);
18
+ if (texts.length < 1 || texts.length > maxBatch || texts.some(value => typeof value !== 'string' || !value.trim() || value.length > 8000))
19
+ throw new MayuraError('INVALID_INPUT', 'Embedding batch exceeds its bounds.');
20
+ try {
21
+ const response = await request('/api/embed', { model: options.model, input: texts, dimensions, truncate: false }, signal);
22
+ const rows = response['embeddings'];
23
+ if (!Array.isArray(rows) || rows.length !== texts.length)
24
+ throw new Error();
25
+ return rows.map(row => vector(row, dimensions));
26
+ }
27
+ catch {
28
+ throw new MayuraError(signal.aborted ? 'CANCELLED' : 'MODEL_FAILED', 'Embedding operation failed; no automatic retry was performed.');
29
+ }
30
+ },
31
+ });
32
+ }
33
+ //# sourceMappingURL=embeddings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embeddings.js","sourceRoot":"","sources":["../src/embeddings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAuB,MAAM,iBAAiB,CAAC;AAK3F,oGAAoG;AACpG,MAAM,UAAU,gBAAgB,CAAC,OAAyB;IACxD,IAAG,OAAO,OAAO,CAAC,KAAK,KAAG,QAAQ,IAAE,CAAC,sCAAsC,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;QAAC,MAAM,IAAI,WAAW,CAAC,gBAAgB,EAAC,+CAA+C,CAAC,CAAC;IACxL,MAAM,UAAU,GAAC,OAAO,CAAC,OAAO,CAAC,UAAU,EAAC,CAAC,EAAC,IAAI,CAAC,CAAC;IAAA,MAAM,QAAQ,GAAC,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAC,CAAC,EAAC,GAAG,CAAC,CAAC;IAAA,MAAM,UAAU,GAAC,OAAO,CAAC,OAAO,CAAC,UAAU,EAAC,CAAC,EAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;IAC1K,MAAM,QAAQ,GAAC,OAAO,CAAC,QAAQ,CAAC;IAAA,MAAM,GAAG,GAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;IAAA,IAAG,CAAC,CAAC,OA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,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAE,IAAI,CAAC,MAAM,KAAG,KAAK,CAAC,MAAM;oBAAC,MAAM,IAAI,KAAK,EAAE,CAAC;gBAAA,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,CAAA,EAAE,CAAA,MAAM,CAAC,GAAe,EAAC,UAAU,CAAC,CAAC,CAAC;YAAC,CAAC;YACvR,MAAM,CAAC;gBAAA,MAAM,IAAI,WAAW,CAAC,MAAM,CAAC,OAAO,CAAA,CAAC,CAAA,WAAW,CAAA,CAAC,CAAA,cAAc,EAAC,+DAA+D,CAAC,CAAC;YAAA,CAAC;QAC3I,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { MayuraError } from 'mayura/core';\nimport type { RagEmbedder } from 'mayura/rag';\nimport { cancelled, integer, ragHttp, vector, type RagHttpOptions } from 'mayura/rag/host';\nexport interface EmbeddingsOptions extends Omit<RagHttpOptions,'endpoint'|'headers'> {\n readonly model:string; readonly dimensions:number; readonly maxBatch:number; readonly costMicros:number;\n readonly endpoint:string; readonly location:\"local\"|\"hosted\";\n}\n/** Explicit native embedding transport. Declared cost is the host's ceiling per bounded request. */\nexport function ollamaEmbeddings(options:EmbeddingsOptions):RagEmbedder {\n if(typeof options.model!=='string'||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(options.model))throw new MayuraError('INVALID_CONFIG','Embedding model must be explicit and bounded.');\n const dimensions=integer(options.dimensions,1,4096);const maxBatch=integer(options.maxBatch,1,128);const costMicros=integer(options.costMicros,0,Number.MAX_SAFE_INTEGER);\n const endpoint=options.endpoint;const url=new URL(endpoint);if(!['local','hosted'].includes(options.location)||options.location==='local'&&!['localhost','127.0.0.1','[::1]'].includes(url.hostname))throw new MayuraError('INVALID_CONFIG','Local embedding location requires a loopback endpoint.');\n const request=ragHttp('ollama-embeddings',{...options,endpoint,headers:{}});\n return Object.freeze({id:`ollama.embeddings.${options.model}.${dimensions}`,dimensions,maxBatch,costMicros,location:options.location,\n async embed(texts:readonly string[],signal:AbortSignal) {\n cancelled(signal);if(texts.length<1||texts.length>maxBatch||texts.some(value=>typeof value!=='string'||!value.trim()||value.length>8000))throw new MayuraError('INVALID_INPUT','Embedding batch exceeds its bounds.');\n try { const response=await request('/api/embed',{model:options.model,input:texts,dimensions,truncate:false},signal);const rows=response['embeddings'];if(!Array.isArray(rows)||rows.length!==texts.length)throw new Error();return rows.map(row=>vector(row as number[],dimensions)); }\n catch {throw new MayuraError(signal.aborted?'CANCELLED':'MODEL_FAILED','Embedding operation failed; no automatic retry was performed.');}\n },\n });\n}\n"]}
@@ -0,0 +1,41 @@
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
+ export { ollamaEmbeddings, type EmbeddingsOptions } from './embeddings.js';
41
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACyE,KAAK,oBAAoB,EAAqB,KAAK,aAAa,EACvE,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;AA+ID;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,MAAM,CAAC,OAAO,GAAE,qBAA0B,GAAG,aAAa,CAwHzE;AAED,OAAO,EAAE,gBAAgB,EAAE,KAAK,iBAAiB,EAAE,MAAM,iBAAiB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,366 @@
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
+ /**
105
+ * The history as Ollama chat messages, in the encoding this run's own turns use, without thinking (history has none).
106
+ * This run's tools keep their names; a tool only the history used gets its own.
107
+ */
108
+ function historyMessages(request, history) {
109
+ const used = history.flatMap(message => message.role === 'assistant' && 'calls' in message ? message.calls.map(call => call.toolId) : message.role === 'tool' ? [message.toolId] : []);
110
+ const names = modelToolNames([...new Set([...request.tools.map(tool => tool.id), ...used])]);
111
+ return history.map((message) => {
112
+ if ('media' in message && message.media?.length)
113
+ return failed('configuration');
114
+ if (message.role === 'user')
115
+ return { role: 'user', content: JSON.stringify(message.content) };
116
+ if (message.role === 'tool')
117
+ return { role: 'tool', tool_name: names.get(message.toolId), content: JSON.stringify(message.result) };
118
+ if ('output' in message)
119
+ return { role: 'assistant', content: JSON.stringify(message.output) };
120
+ return { role: 'assistant', content: '', tool_calls: message.calls.map(call => ({ function: { name: names.get(call.toolId), arguments: call.input } })) };
121
+ });
122
+ }
123
+ /**
124
+ * The conversation as Ollama chat messages: the history first, then this run's messages. `assistants` are the model's
125
+ * own earlier tool-call turns in this run, counted in this run's messages alone.
126
+ */
127
+ function messagesFor(request, aliases, assistants) {
128
+ let turn = 0;
129
+ return [{ role: 'system', content: request.instructions }, ...request.history ? historyMessages(request, request.history) : [], ...request.messages.map((message) => {
130
+ if (message.role === 'user')
131
+ return { role: 'user', content: withNames(JSON.stringify(message.content), message.media), ...images(message.media) };
132
+ if (message.role === 'tool') {
133
+ const name = aliases.get(message.toolId);
134
+ if (!name)
135
+ return failed();
136
+ return { role: 'tool', tool_name: name, content: withNames(JSON.stringify(message.result), message.media), ...images(message.media) };
137
+ }
138
+ const toolCalls = message.calls.map(call => {
139
+ const name = aliases.get(call.toolId);
140
+ if (!name)
141
+ return failed();
142
+ return { function: { name, arguments: call.input } };
143
+ });
144
+ const own = assistants[turn++];
145
+ if (own && (own.calls.length !== message.calls.length || own.calls.some((id, index) => id !== message.calls[index].id)))
146
+ return failed();
147
+ return { role: 'assistant', content: '', ...(own?.thinking ? { thinking: own.thinking } : {}), tool_calls: toolCalls };
148
+ })];
149
+ }
150
+ /** Ids for a response's tool calls, which Ollama does not give: unique within the conversation, its history included. */
151
+ function callIds(request, count) {
152
+ const used = new Set([...request.history ?? [], ...request.messages].flatMap(message => message.role === 'assistant' ? 'calls' in message ? message.calls.map(call => call.id) : [] : message.role === 'tool' ? [message.callId] : []));
153
+ const ids = [];
154
+ for (let next = used.size + 1; ids.length < count; next++)
155
+ if (!used.has(`call_${next}`))
156
+ ids.push(`call_${next}`);
157
+ return ids;
158
+ }
159
+ /** Rebuilds the response a non-streamed call returns from Ollama's stream, reporting text as it arrives. */
160
+ async function assemble(chunks, maxResponseBytes, onDelta) {
161
+ let content = '';
162
+ let thinking = '';
163
+ const toolCalls = [];
164
+ let last;
165
+ try {
166
+ for await (const raw of chunks) {
167
+ const data = object(jsonValue(JSON.parse(JSON.stringify(raw)), { maxBytes: maxResponseBytes }));
168
+ const message = data['message'] === undefined ? {} : object(data['message']);
169
+ if (typeof message['content'] === 'string' && message['content']) {
170
+ content += message['content'];
171
+ onDelta(message['content']);
172
+ }
173
+ if (typeof message['thinking'] === 'string')
174
+ thinking += message['thinking'];
175
+ if (Array.isArray(message['tool_calls'])) {
176
+ toolCalls.push(...message['tool_calls']);
177
+ if (toolCalls.length > 128)
178
+ return failed();
179
+ }
180
+ if (data['done'] === true)
181
+ last = data;
182
+ }
183
+ }
184
+ catch (error) {
185
+ // The server reported an error mid-answer, or ended the stream without finishing it.
186
+ if (error instanceof ModelProviderError || error instanceof ResponseTooLarge || error instanceof SyntaxError)
187
+ throw error;
188
+ return failed('unavailable');
189
+ }
190
+ if (!last)
191
+ return failed();
192
+ return { ...last, message: { role: 'assistant', content, ...(thinking ? { thinking } : {}), ...(toolCalls.length ? { tool_calls: toolCalls } : {}) } };
193
+ }
194
+ /**
195
+ * Ollama models for a Mayura model registry, local or in Ollama's cloud, through the official Ollama SDK:
196
+ *
197
+ * ```ts
198
+ * const models = createModels({
199
+ * providers: [ollama()],
200
+ * prices: { 'ollama/gpt-oss:20b': { inputMicrosPerMillionTokens: 0, outputMicrosPerMillionTokens: 0 } },
201
+ * maxCallCostMicros: 1,
202
+ * });
203
+ * const model = models.model('ollama/gpt-oss:20b'); // granted as model:ollama/gpt-oss:20b
204
+ * ```
205
+ *
206
+ * Local models cost nothing, so there is no catalog: give each model's price, zero or your own. Structured output
207
+ * and tool inputs use JSON Schema; streaming reports output text as it arrives; the model's thinking is kept for the
208
+ * next call of the run and never released. Nothing is read from the environment or the file system.
209
+ */
210
+ export function ollama(options = {}) {
211
+ if (!options || typeof options !== 'object')
212
+ throw new MayuraError('INVALID_CONFIG', 'ollama() options must be an object.');
213
+ const host = hostOf(options.host);
214
+ if (options.apiKey !== undefined && (typeof options.apiKey !== 'string' || !options.apiKey.trim() || /[\r\n]/u.test(options.apiKey) || options.apiKey.length > 4096)) {
215
+ throw new MayuraError('INVALID_CONFIG', 'ollama(): apiKey must be a non-empty string.');
216
+ }
217
+ // The SDK falls back to OLLAMA_API_KEY for ollama.com; the key must be given instead.
218
+ if (new URL(host).hostname === 'ollama.com' && options.apiKey === undefined)
219
+ throw new MayuraError('INVALID_CONFIG', 'ollama(): https://ollama.com needs an apiKey.');
220
+ const headers = { ...providerHeaders(options.headers, ['Authorization', 'Accept', 'User-Agent'], 'ollama()'), ...(options.apiKey === undefined ? {} : { Authorization: `Bearer ${options.apiKey}` }) };
221
+ if (options.think !== undefined && ![true, false, 'low', 'medium', 'high'].includes(options.think))
222
+ throw new MayuraError('INVALID_CONFIG', 'ollama(): think must be true, false, low, medium or high.');
223
+ const maxRequestBytes = options.maxRequestBytes ?? 1_048_576;
224
+ const maxResponseBytes = options.maxResponseBytes ?? 1_048_576;
225
+ const defaultTimeout = options.timeoutMs ?? 120_000;
226
+ for (const [value, name] of [[maxRequestBytes, 'maxRequestBytes'], [maxResponseBytes, 'maxResponseBytes'], [defaultTimeout, 'timeoutMs']])
227
+ assertPositiveInteger(value, name);
228
+ const media = mediaOption(options.media);
229
+ return Object.freeze({
230
+ id: 'ollama',
231
+ model(name, settings) {
232
+ if (typeof name !== 'string' || !name.trim() || name.length > 128)
233
+ throw new MayuraError('INVALID_CONFIG', 'An Ollama model name is required.');
234
+ const timeoutMs = settings.timeoutMs ?? defaultTimeout;
235
+ const call = async (request, onDelta, consumer) => {
236
+ const controller = new AbortController();
237
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
238
+ let knownCost;
239
+ let inputTokens = 0;
240
+ let outputTokens = 0;
241
+ try {
242
+ const signal = AbortSignal.any([request.signal, controller.signal, ...(consumer ? [consumer] : [])]);
243
+ if (signal.aborted)
244
+ throw new MayuraError('CANCELLED', 'Provider request was cancelled.');
245
+ let assistants = [];
246
+ if (request.continuation !== undefined) {
247
+ const previous = object(request.continuation);
248
+ if (previous['provider'] !== 'ollama.chat.v1' || previous['model'] !== name || !Array.isArray(previous['assistants']))
249
+ return failed();
250
+ assistants = previous['assistants'].map(raw => {
251
+ const turn = object(raw);
252
+ if ((turn['thinking'] !== null && typeof turn['thinking'] !== 'string') || !Array.isArray(turn['calls']) || turn['calls'].some(id => typeof id !== 'string'))
253
+ return failed();
254
+ return { thinking: turn['thinking'], calls: turn['calls'] };
255
+ });
256
+ }
257
+ if (assistants.length > request.messages.filter(message => message.role === 'assistant').length)
258
+ return failed();
259
+ assertPositiveInteger(request.maxOutputTokens, 'maxOutputTokens');
260
+ const aliases = new Map(modelToolNames(request.tools.map(tool => tool.id)));
261
+ const ids = new Map([...aliases].map(([toolId, alias]) => [alias, toolId]));
262
+ if (aliases.size !== request.tools.length || aliases.size > 128)
263
+ return failed();
264
+ const tools = request.tools.map(tool => {
265
+ if (!tool.inputJsonSchema)
266
+ throw new MayuraError('INVALID_CONFIG', `Tool "${tool.id}" has no inputJsonSchema.`);
267
+ return { type: 'function', function: { name: aliases.get(tool.id), description: tool.description, parameters: strictJsonSchema(tool.inputJsonSchema, `Tool "${tool.id}" input schema`) } };
268
+ });
269
+ const outputSchema = request.outputJsonSchema === undefined ? failed('configuration') : strictJsonSchema(request.outputJsonSchema, 'The output schema');
270
+ // A format constrains a reply to the answer, which leaves no way to call a tool. So with tools, the model first
271
+ // answers freely; once it calls no more tools, one more call without tools asks for the answer in the format.
272
+ const messages = messagesFor(request, aliases, assistants);
273
+ const common = { model: name, messages, options: { num_predict: request.maxOutputTokens }, ...(options.think === undefined ? {} : { think: options.think }) };
274
+ // Ollama's cloud accepts a format without enforcing it, so a request with one also gives the schema in its instructions.
275
+ const formatted = { ...common, format: outputSchema, messages: [
276
+ { 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)
277
+ ] };
278
+ const body = tools.length > 0 ? { ...common, tools } : formatted;
279
+ jsonValue(body, { maxBytes: maxRequestBytes + encodedMediaBytes(request.messages) });
280
+ // A client per call, so the call's signal reaches every request it makes.
281
+ const client = new Ollama({ host, headers, fetch: callFetch(options.fetch ?? globalThis.fetch, maxResponseBytes, signal) });
282
+ const chat = async (request, stream) => {
283
+ const payload = stream
284
+ ? await assemble(await client.chat({ ...request, stream: true }), maxResponseBytes, stream)
285
+ : object(jsonValue(JSON.parse(JSON.stringify(await client.chat({ ...request, stream: false }))), { maxBytes: maxResponseBytes * 2 }));
286
+ // Ollama leaves out the prompt count when the whole prompt was cached.
287
+ const prompt = payload['prompt_eval_count'] === undefined ? 0 : integer(payload['prompt_eval_count']);
288
+ const completion = integer(payload['eval_count']);
289
+ knownCost = (knownCost ?? 0) + (tokenCostMicros(settings.pricing, prompt, completion) ?? failed());
290
+ inputTokens += prompt;
291
+ outputTokens += completion;
292
+ if (payload['done'] !== true)
293
+ return failed();
294
+ return payload;
295
+ };
296
+ const finalFrom = (payload) => {
297
+ const message = object(payload['message']);
298
+ const finish = payload['done_reason'];
299
+ // Output cut off by the token limit is not an answer.
300
+ if (finish === 'length')
301
+ return failed('refused');
302
+ if (finish !== 'stop' || typeof message['content'] !== 'string' || (Array.isArray(message['tool_calls']) && message['tool_calls'].length > 0))
303
+ return failed();
304
+ return { type: 'final', output: jsonValue(JSON.parse(message['content']), { maxBytes: maxResponseBytes }), usage: { costMicros: knownCost, inputTokens, outputTokens } };
305
+ };
306
+ if (tools.length === 0)
307
+ return finalFrom(await chat(body, onDelta));
308
+ // The free reply is never streamed: it may be prose, which is not the answer.
309
+ const payload = await chat(body, onDelta ? () => undefined : undefined);
310
+ const message = object(payload['message']);
311
+ const finish = payload['done_reason'];
312
+ const toolCalls = message['tool_calls'] ?? [];
313
+ if (!Array.isArray(toolCalls) || toolCalls.length > 128)
314
+ return failed();
315
+ if (toolCalls.length > 0 && finish === 'stop') {
316
+ const given = callIds(request, toolCalls.length);
317
+ const calls = toolCalls.map((raw, index) => {
318
+ const fn = object(object(raw)['function']);
319
+ const alias = fn['name'];
320
+ const args = fn['arguments'];
321
+ if (typeof alias !== 'string' || !ids.has(alias))
322
+ return failed();
323
+ const input = typeof args === 'string' ? JSON.parse(args || '{}') : args === undefined ? {} : object(args);
324
+ return { id: given[index], toolId: ids.get(alias), input: jsonValue(input, { maxBytes: maxResponseBytes }) };
325
+ });
326
+ const thinking = typeof message['thinking'] === 'string' && message['thinking'] ? message['thinking'] : null;
327
+ const continuation = jsonValue({ provider: 'ollama.chat.v1', model: name, assistants: [...assistants, { thinking, calls: calls.map(entry => entry.id) }] }, { maxBytes: maxRequestBytes });
328
+ return { type: 'tool_calls', calls, usage: { costMicros: knownCost, inputTokens, outputTokens }, continuation };
329
+ }
330
+ if (finish === 'length')
331
+ return failed('refused');
332
+ if (finish !== 'stop')
333
+ return failed();
334
+ return finalFrom(await chat(formatted, onDelta));
335
+ }
336
+ catch (error) {
337
+ if (knownCost !== undefined)
338
+ throw new ModelProviderError(reasonOf(error), { costMicros: knownCost });
339
+ if (request.signal.aborted || controller.signal.aborted || consumer?.aborted)
340
+ throw new MayuraError('CANCELLED', 'Provider request was cancelled or timed out.');
341
+ if (error instanceof ModelProviderError)
342
+ throw error;
343
+ if (error instanceof MayuraError && error.code === 'INVALID_CONFIG')
344
+ return failed('configuration');
345
+ if (error instanceof HttpFailure)
346
+ throw providerHttpFailure(error.status);
347
+ if (error instanceof ConnectionFailure)
348
+ return failed('unavailable');
349
+ return failed();
350
+ }
351
+ finally {
352
+ clearTimeout(timer);
353
+ }
354
+ };
355
+ return Object.freeze({
356
+ id: settings.id, maxCostMicros: settings.maxCostMicros,
357
+ capabilities: Object.freeze({ tools: true, structuredOutput: true, history: true, ...(media ? { media } : {}) }),
358
+ checkDefinition: (definition) => checkStrictDefinition(definition),
359
+ generate: (request) => call(request),
360
+ stream: (request) => streamModelCall((onDelta, consumer) => call(request, onDelta, consumer)),
361
+ });
362
+ },
363
+ });
364
+ }
365
+ export { ollamaEmbeddings } from './embeddings.js';
366
+ //# 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,gBAAgB,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,SAAS,EAAE,WAAW,EAAE,kBAAkB,EAED,MAAM,QAAQ,CAAC;AACxF,OAAO,EAAE,aAAa,EAAE,qBAAqB,EAAE,iBA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;wBAAE,OAAO,MAAM,CAAC,aAAa,CAAC,CAAC;oBACrE,OAAO,MAAM,EAAE,CAAC;gBAClB,CAAC;wBAAS,CAAC;oBAAC,YAAY,CAAC,KAAK,CAAC,CAAC;gBAAC,CAAC;YACpC,CAAC,CAAC;YAEF,OAAO,MAAM,CAAC,MAAM,CAAC;gBACnB,EAAE,EAAE,QAAQ,CAAC,EAAE,EAAE,aAAa,EAAE,QAAQ,CAAC,aAAa;gBACtD,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,gBAAgB,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;gBAChH,eAAe,EAAE,CAAC,UAAgC,EAAQ,EAAE,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;AAED,OAAO,EAAE,gBAAgB,EAA0B,MAAM,iBAAiB,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 ModelHistoryMessage, 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/**\n * The history as Ollama chat messages, in the encoding this run's own turns use, without thinking (history has none).\n * This run's tools keep their names; a tool only the history used gets its own.\n */\nfunction historyMessages(request: ModelRequest, history: readonly ModelHistoryMessage[]): JsonValue[] {\n const used = history.flatMap(message => message.role === 'assistant' && 'calls' in message ? message.calls.map(call => call.toolId) : message.role === 'tool' ? [message.toolId] : []);\n const names = modelToolNames([...new Set([...request.tools.map(tool => tool.id), ...used])]);\n return history.map((message): JsonValue => {\n if ('media' in message && message.media?.length) return failed('configuration');\n if (message.role === 'user') return { role: 'user', content: JSON.stringify(message.content) };\n if (message.role === 'tool') return { role: 'tool', tool_name: names.get(message.toolId)!, content: JSON.stringify(message.result) };\n if ('output' in message) return { role: 'assistant', content: JSON.stringify(message.output) };\n return { role: 'assistant', content: '', tool_calls: message.calls.map(call => ({ function: { name: names.get(call.toolId)!, arguments: call.input } })) };\n });\n}\n/**\n * The conversation as Ollama chat messages: the history first, then this run's messages. `assistants` are the model's\n * own earlier tool-call turns in this run, counted in this run's messages alone.\n */\nfunction messagesFor(request: ModelRequest, aliases: ReadonlyMap<string, string>, assistants: readonly OwnTurn[]): JsonValue[] {\n let turn = 0;\n return [{ role: 'system', content: request.instructions }, ...request.history ? historyMessages(request, request.history) : [], ...(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 conversation, its history included. */\nfunction callIds(request: ModelRequest, count: number): string[] {\n const used = new Set([...request.history ?? [], ...request.messages].flatMap(message => message.role === 'assistant' ? 'calls' in message ? 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, history: 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\nexport { ollamaEmbeddings, type EmbeddingsOptions } from './embeddings.js';\n"]}
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@mayurajs/provider-ollama",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.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.2.0"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public",
45
+ "provenance": true
46
+ }
47
+ }
@@ -0,0 +1,21 @@
1
+ import { MayuraError } from 'mayura/core';
2
+ import type { RagEmbedder } from 'mayura/rag';
3
+ import { cancelled, integer, ragHttp, vector, type RagHttpOptions } from 'mayura/rag/host';
4
+ export interface EmbeddingsOptions extends Omit<RagHttpOptions,'endpoint'|'headers'> {
5
+ readonly model:string; readonly dimensions:number; readonly maxBatch:number; readonly costMicros:number;
6
+ readonly endpoint:string; readonly location:"local"|"hosted";
7
+ }
8
+ /** Explicit native embedding transport. Declared cost is the host's ceiling per bounded request. */
9
+ export function ollamaEmbeddings(options:EmbeddingsOptions):RagEmbedder {
10
+ if(typeof options.model!=='string'||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(options.model))throw new MayuraError('INVALID_CONFIG','Embedding model must be explicit and bounded.');
11
+ const dimensions=integer(options.dimensions,1,4096);const maxBatch=integer(options.maxBatch,1,128);const costMicros=integer(options.costMicros,0,Number.MAX_SAFE_INTEGER);
12
+ const endpoint=options.endpoint;const url=new URL(endpoint);if(!['local','hosted'].includes(options.location)||options.location==='local'&&!['localhost','127.0.0.1','[::1]'].includes(url.hostname))throw new MayuraError('INVALID_CONFIG','Local embedding location requires a loopback endpoint.');
13
+ const request=ragHttp('ollama-embeddings',{...options,endpoint,headers:{}});
14
+ return Object.freeze({id:`ollama.embeddings.${options.model}.${dimensions}`,dimensions,maxBatch,costMicros,location:options.location,
15
+ async embed(texts:readonly string[],signal:AbortSignal) {
16
+ cancelled(signal);if(texts.length<1||texts.length>maxBatch||texts.some(value=>typeof value!=='string'||!value.trim()||value.length>8000))throw new MayuraError('INVALID_INPUT','Embedding batch exceeds its bounds.');
17
+ try { const response=await request('/api/embed',{model:options.model,input:texts,dimensions,truncate:false},signal);const rows=response['embeddings'];if(!Array.isArray(rows)||rows.length!==texts.length)throw new Error();return rows.map(row=>vector(row as number[],dimensions)); }
18
+ catch {throw new MayuraError(signal.aborted?'CANCELLED':'MODEL_FAILED','Embedding operation failed; no automatic retry was performed.');}
19
+ },
20
+ });
21
+ }
package/src/index.ts ADDED
@@ -0,0 +1,308 @@
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 ModelHistoryMessage, 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
+ /**
106
+ * The history as Ollama chat messages, in the encoding this run's own turns use, without thinking (history has none).
107
+ * This run's tools keep their names; a tool only the history used gets its own.
108
+ */
109
+ function historyMessages(request: ModelRequest, history: readonly ModelHistoryMessage[]): JsonValue[] {
110
+ const used = history.flatMap(message => message.role === 'assistant' && 'calls' in message ? message.calls.map(call => call.toolId) : message.role === 'tool' ? [message.toolId] : []);
111
+ const names = modelToolNames([...new Set([...request.tools.map(tool => tool.id), ...used])]);
112
+ return history.map((message): JsonValue => {
113
+ if ('media' in message && message.media?.length) return failed('configuration');
114
+ if (message.role === 'user') return { role: 'user', content: JSON.stringify(message.content) };
115
+ if (message.role === 'tool') return { role: 'tool', tool_name: names.get(message.toolId)!, content: JSON.stringify(message.result) };
116
+ if ('output' in message) return { role: 'assistant', content: JSON.stringify(message.output) };
117
+ return { role: 'assistant', content: '', tool_calls: message.calls.map(call => ({ function: { name: names.get(call.toolId)!, arguments: call.input } })) };
118
+ });
119
+ }
120
+ /**
121
+ * The conversation as Ollama chat messages: the history first, then this run's messages. `assistants` are the model's
122
+ * own earlier tool-call turns in this run, counted in this run's messages alone.
123
+ */
124
+ function messagesFor(request: ModelRequest, aliases: ReadonlyMap<string, string>, assistants: readonly OwnTurn[]): JsonValue[] {
125
+ let turn = 0;
126
+ return [{ role: 'system', content: request.instructions }, ...request.history ? historyMessages(request, request.history) : [], ...(request.messages as readonly ModelMessage[]).map((message): JsonValue => {
127
+ if (message.role === 'user') return { role: 'user', content: withNames(JSON.stringify(message.content), message.media), ...images(message.media) };
128
+ if (message.role === 'tool') {
129
+ const name = aliases.get(message.toolId); if (!name) return failed();
130
+ return { role: 'tool', tool_name: name, content: withNames(JSON.stringify(message.result), message.media), ...images(message.media) };
131
+ }
132
+ const toolCalls = message.calls.map(call => {
133
+ const name = aliases.get(call.toolId); if (!name) return failed();
134
+ return { function: { name, arguments: call.input } };
135
+ });
136
+ const own = assistants[turn++];
137
+ if (own && (own.calls.length !== message.calls.length || own.calls.some((id, index) => id !== message.calls[index]!.id))) return failed();
138
+ return { role: 'assistant', content: '', ...(own?.thinking ? { thinking: own.thinking } : {}), tool_calls: toolCalls };
139
+ })];
140
+ }
141
+ /** Ids for a response's tool calls, which Ollama does not give: unique within the conversation, its history included. */
142
+ function callIds(request: ModelRequest, count: number): string[] {
143
+ const used = new Set([...request.history ?? [], ...request.messages].flatMap(message => message.role === 'assistant' ? 'calls' in message ? message.calls.map(call => call.id) : [] : message.role === 'tool' ? [message.callId] : []));
144
+ const ids: string[] = [];
145
+ for (let next = used.size + 1; ids.length < count; next++) if (!used.has(`call_${next}`)) ids.push(`call_${next}`);
146
+ return ids;
147
+ }
148
+
149
+ /** Rebuilds the response a non-streamed call returns from Ollama's stream, reporting text as it arrives. */
150
+ async function assemble(chunks: AsyncIterable<unknown>, maxResponseBytes: number, onDelta: (text: string) => void): Promise<JsonObject> {
151
+ let content = ''; let thinking = ''; const toolCalls: JsonValue[] = []; let last: JsonObject | undefined;
152
+ try {
153
+ for await (const raw of chunks) {
154
+ const data = object(jsonValue(JSON.parse(JSON.stringify(raw)) as JsonValue, { maxBytes: maxResponseBytes }));
155
+ const message = data['message'] === undefined ? {} : object(data['message']);
156
+ if (typeof message['content'] === 'string' && message['content']) { content += message['content']; onDelta(message['content']); }
157
+ if (typeof message['thinking'] === 'string') thinking += message['thinking'];
158
+ if (Array.isArray(message['tool_calls'])) { toolCalls.push(...message['tool_calls']); if (toolCalls.length > 128) return failed(); }
159
+ if (data['done'] === true) last = data;
160
+ }
161
+ } catch (error) {
162
+ // The server reported an error mid-answer, or ended the stream without finishing it.
163
+ if (error instanceof ModelProviderError || error instanceof ResponseTooLarge || error instanceof SyntaxError) throw error;
164
+ return failed('unavailable');
165
+ }
166
+ if (!last) return failed();
167
+ return { ...last, message: { role: 'assistant', content, ...(thinking ? { thinking } : {}), ...(toolCalls.length ? { tool_calls: toolCalls } : {}) } };
168
+ }
169
+
170
+ /**
171
+ * Ollama models for a Mayura model registry, local or in Ollama's cloud, through the official Ollama SDK:
172
+ *
173
+ * ```ts
174
+ * const models = createModels({
175
+ * providers: [ollama()],
176
+ * prices: { 'ollama/gpt-oss:20b': { inputMicrosPerMillionTokens: 0, outputMicrosPerMillionTokens: 0 } },
177
+ * maxCallCostMicros: 1,
178
+ * });
179
+ * const model = models.model('ollama/gpt-oss:20b'); // granted as model:ollama/gpt-oss:20b
180
+ * ```
181
+ *
182
+ * Local models cost nothing, so there is no catalog: give each model's price, zero or your own. Structured output
183
+ * and tool inputs use JSON Schema; streaming reports output text as it arrives; the model's thinking is kept for the
184
+ * next call of the run and never released. Nothing is read from the environment or the file system.
185
+ */
186
+ export function ollama(options: OllamaProviderOptions = {}): ModelProvider {
187
+ if (!options || typeof options !== 'object') throw new MayuraError('INVALID_CONFIG', 'ollama() options must be an object.');
188
+ const host = hostOf(options.host);
189
+ if (options.apiKey !== undefined && (typeof options.apiKey !== 'string' || !options.apiKey.trim() || /[\r\n]/u.test(options.apiKey) || options.apiKey.length > 4096)) {
190
+ throw new MayuraError('INVALID_CONFIG', 'ollama(): apiKey must be a non-empty string.');
191
+ }
192
+ // The SDK falls back to OLLAMA_API_KEY for ollama.com; the key must be given instead.
193
+ if (new URL(host).hostname === 'ollama.com' && options.apiKey === undefined) throw new MayuraError('INVALID_CONFIG', 'ollama(): https://ollama.com needs an apiKey.');
194
+ const headers = { ...providerHeaders(options.headers, ['Authorization', 'Accept', 'User-Agent'], 'ollama()'), ...(options.apiKey === undefined ? {} : { Authorization: `Bearer ${options.apiKey}` }) };
195
+ 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.');
196
+ const maxRequestBytes = options.maxRequestBytes ?? 1_048_576; const maxResponseBytes = options.maxResponseBytes ?? 1_048_576;
197
+ const defaultTimeout = options.timeoutMs ?? 120_000;
198
+ for (const [value, name] of [[maxRequestBytes, 'maxRequestBytes'], [maxResponseBytes, 'maxResponseBytes'], [defaultTimeout, 'timeoutMs']] as const) assertPositiveInteger(value, name);
199
+ const media = mediaOption(options.media);
200
+
201
+ return Object.freeze({
202
+ id: 'ollama',
203
+ model(name: string, settings: ProviderModelSettings): ModelAdapter {
204
+ if (typeof name !== 'string' || !name.trim() || name.length > 128) throw new MayuraError('INVALID_CONFIG', 'An Ollama model name is required.');
205
+ const timeoutMs = settings.timeoutMs ?? defaultTimeout;
206
+
207
+ const call = async (request: ModelRequest, onDelta?: (text: string) => void, consumer?: AbortSignal): Promise<ModelResponse> => {
208
+ const controller = new AbortController();
209
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
210
+ let knownCost: number | undefined; let inputTokens = 0; let outputTokens = 0;
211
+ try {
212
+ const signal = AbortSignal.any([request.signal, controller.signal, ...(consumer ? [consumer] : [])]);
213
+ if (signal.aborted) throw new MayuraError('CANCELLED', 'Provider request was cancelled.');
214
+ let assistants: OwnTurn[] = [];
215
+ if (request.continuation !== undefined) {
216
+ const previous = object(request.continuation);
217
+ if (previous['provider'] !== 'ollama.chat.v1' || previous['model'] !== name || !Array.isArray(previous['assistants'])) return failed();
218
+ assistants = previous['assistants'].map(raw => {
219
+ const turn = object(raw);
220
+ if ((turn['thinking'] !== null && typeof turn['thinking'] !== 'string') || !Array.isArray(turn['calls']) || turn['calls'].some(id => typeof id !== 'string')) return failed();
221
+ return { thinking: turn['thinking'], calls: turn['calls'] as string[] };
222
+ });
223
+ }
224
+ if (assistants.length > request.messages.filter(message => message.role === 'assistant').length) return failed();
225
+ assertPositiveInteger(request.maxOutputTokens, 'maxOutputTokens');
226
+ const aliases = new Map(modelToolNames(request.tools.map(tool => tool.id)));
227
+ const ids = new Map([...aliases].map(([toolId, alias]) => [alias, toolId]));
228
+ if (aliases.size !== request.tools.length || aliases.size > 128) return failed();
229
+ const tools = request.tools.map(tool => {
230
+ if (!tool.inputJsonSchema) throw new MayuraError('INVALID_CONFIG', `Tool "${tool.id}" has no inputJsonSchema.`);
231
+ return { type: 'function', function: { name: aliases.get(tool.id)!, description: tool.description, parameters: strictJsonSchema(tool.inputJsonSchema, `Tool "${tool.id}" input schema`) } };
232
+ });
233
+ const outputSchema = request.outputJsonSchema === undefined ? failed('configuration') : strictJsonSchema(request.outputJsonSchema, 'The output schema');
234
+ // A format constrains a reply to the answer, which leaves no way to call a tool. So with tools, the model first
235
+ // answers freely; once it calls no more tools, one more call without tools asks for the answer in the format.
236
+ const messages = messagesFor(request, aliases, assistants);
237
+ const common = { model: name, messages, options: { num_predict: request.maxOutputTokens }, ...(options.think === undefined ? {} : { think: options.think }) };
238
+ // Ollama's cloud accepts a format without enforcing it, so a request with one also gives the schema in its instructions.
239
+ const formatted: JsonObject = { ...common, format: outputSchema, messages: [
240
+ { 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)] };
241
+ const body: JsonObject = tools.length > 0 ? { ...common, tools } : formatted;
242
+ jsonValue(body, { maxBytes: maxRequestBytes + encodedMediaBytes(request.messages) });
243
+
244
+ // A client per call, so the call's signal reaches every request it makes.
245
+ const client = new Ollama({ host, headers, fetch: callFetch(options.fetch ?? globalThis.fetch, maxResponseBytes, signal) });
246
+ const chat = async (request: JsonObject, stream: ((text: string) => void) | undefined): Promise<JsonObject> => {
247
+ const payload = stream
248
+ ? await assemble(await client.chat({ ...request, stream: true } as never) as unknown as AsyncIterable<unknown>, maxResponseBytes, stream)
249
+ : object(jsonValue(JSON.parse(JSON.stringify(await client.chat({ ...request, stream: false } as never))) as JsonValue, { maxBytes: maxResponseBytes * 2 }));
250
+ // Ollama leaves out the prompt count when the whole prompt was cached.
251
+ const prompt = payload['prompt_eval_count'] === undefined ? 0 : integer(payload['prompt_eval_count']); const completion = integer(payload['eval_count']);
252
+ knownCost = (knownCost ?? 0) + (tokenCostMicros(settings.pricing, prompt, completion) ?? failed());
253
+ inputTokens += prompt; outputTokens += completion;
254
+ if (payload['done'] !== true) return failed();
255
+ return payload;
256
+ };
257
+ const finalFrom = (payload: JsonObject): ModelResponse => {
258
+ const message = object(payload['message']); const finish = payload['done_reason'];
259
+ // Output cut off by the token limit is not an answer.
260
+ if (finish === 'length') return failed('refused');
261
+ if (finish !== 'stop' || typeof message['content'] !== 'string' || (Array.isArray(message['tool_calls']) && message['tool_calls'].length > 0)) return failed();
262
+ return { type: 'final', output: jsonValue(JSON.parse(message['content']) as JsonValue, { maxBytes: maxResponseBytes }), usage: { costMicros: knownCost!, inputTokens, outputTokens } };
263
+ };
264
+ if (tools.length === 0) return finalFrom(await chat(body, onDelta));
265
+
266
+ // The free reply is never streamed: it may be prose, which is not the answer.
267
+ const payload = await chat(body, onDelta ? () => undefined : undefined);
268
+ const message = object(payload['message']); const finish = payload['done_reason'];
269
+ const toolCalls = message['tool_calls'] ?? [];
270
+ if (!Array.isArray(toolCalls) || toolCalls.length > 128) return failed();
271
+ if (toolCalls.length > 0 && finish === 'stop') {
272
+ const given = callIds(request, toolCalls.length);
273
+ const calls: ModelToolCall[] = toolCalls.map((raw, index) => {
274
+ const fn = object(object(raw)['function']); const alias = fn['name']; const args = fn['arguments'];
275
+ if (typeof alias !== 'string' || !ids.has(alias)) return failed();
276
+ const input = typeof args === 'string' ? JSON.parse(args || '{}') as JsonValue : args === undefined ? {} : object(args);
277
+ return { id: given[index]!, toolId: ids.get(alias)!, input: jsonValue(input, { maxBytes: maxResponseBytes }) };
278
+ });
279
+ const thinking = typeof message['thinking'] === 'string' && message['thinking'] ? message['thinking'] : null;
280
+ const continuation = jsonValue({ provider: 'ollama.chat.v1', model: name, assistants: [...assistants, { thinking, calls: calls.map(entry => entry.id) }] }, { maxBytes: maxRequestBytes });
281
+ return { type: 'tool_calls', calls, usage: { costMicros: knownCost!, inputTokens, outputTokens }, continuation };
282
+ }
283
+ if (finish === 'length') return failed('refused');
284
+ if (finish !== 'stop') return failed();
285
+ return finalFrom(await chat(formatted, onDelta));
286
+ } catch (error) {
287
+ if (knownCost !== undefined) throw new ModelProviderError(reasonOf(error), { costMicros: knownCost });
288
+ if (request.signal.aborted || controller.signal.aborted || consumer?.aborted) throw new MayuraError('CANCELLED', 'Provider request was cancelled or timed out.');
289
+ if (error instanceof ModelProviderError) throw error;
290
+ if (error instanceof MayuraError && error.code === 'INVALID_CONFIG') return failed('configuration');
291
+ if (error instanceof HttpFailure) throw providerHttpFailure(error.status);
292
+ if (error instanceof ConnectionFailure) return failed('unavailable');
293
+ return failed();
294
+ } finally { clearTimeout(timer); }
295
+ };
296
+
297
+ return Object.freeze({
298
+ id: settings.id, maxCostMicros: settings.maxCostMicros,
299
+ capabilities: Object.freeze({ tools: true, structuredOutput: true, history: true, ...(media ? { media } : {}) }),
300
+ checkDefinition: (definition: ModelDefinitionCheck): void => checkStrictDefinition(definition),
301
+ generate: (request: ModelRequest): Promise<ModelResponse> => call(request),
302
+ stream: (request: ModelRequest): AsyncIterable<ModelStreamEvent> => streamModelCall((onDelta, consumer) => call(request, onDelta, consumer)),
303
+ });
304
+ },
305
+ });
306
+ }
307
+
308
+ export { ollamaEmbeddings, type EmbeddingsOptions } from './embeddings.js';