@mayurajs/provider-ollama 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/dist/embeddings.d.ts +13 -0
- package/dist/embeddings.d.ts.map +1 -0
- package/dist/embeddings.js +33 -0
- package/dist/embeddings.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +28 -5
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/embeddings.ts +21 -0
- package/src/index.ts +26 -6
package/README.md
CHANGED
|
@@ -27,7 +27,12 @@ const agent = defineAgent({
|
|
|
27
27
|
- `host` is http only on a loopback address, https anywhere else. For Ollama's cloud, use `ollama({ host: 'https://ollama.com', apiKey })`.
|
|
28
28
|
- Nothing is read from the environment (not `OLLAMA_HOST` or `OLLAMA_API_KEY`) or the file system.
|
|
29
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.
|
|
30
31
|
- Models see no media unless you say so: pass `media: { types: ['image/png', 'image/jpeg'], urls: false }` for a vision model.
|
|
31
32
|
- The default time limit is 120 seconds, since a local model may need loading first.
|
|
32
33
|
|
|
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
|
+
}
|
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AC;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"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -37,4 +37,5 @@ export interface OllamaProviderOptions {
|
|
|
37
37
|
* next call of the run and never released. Nothing is read from the environment or the file system.
|
|
38
38
|
*/
|
|
39
39
|
export declare function ollama(options?: OllamaProviderOptions): ModelProvider;
|
|
40
|
+
export { ollamaEmbeddings, type EmbeddingsOptions } from './embeddings.js';
|
|
40
41
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,
|
|
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
CHANGED
|
@@ -101,10 +101,32 @@ const withNames = (text, media) => {
|
|
|
101
101
|
const names = (media ?? []).flatMap(item => item.name === undefined ? [] : [item.name]);
|
|
102
102
|
return names.length ? `${text}\n\nImages, in order: ${names.join(', ')}` : text;
|
|
103
103
|
};
|
|
104
|
-
/**
|
|
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
|
+
*/
|
|
105
127
|
function messagesFor(request, aliases, assistants) {
|
|
106
128
|
let turn = 0;
|
|
107
|
-
return [{ role: 'system', content: request.instructions }, ...request.messages.map((message) => {
|
|
129
|
+
return [{ role: 'system', content: request.instructions }, ...request.history ? historyMessages(request, request.history) : [], ...request.messages.map((message) => {
|
|
108
130
|
if (message.role === 'user')
|
|
109
131
|
return { role: 'user', content: withNames(JSON.stringify(message.content), message.media), ...images(message.media) };
|
|
110
132
|
if (message.role === 'tool') {
|
|
@@ -125,9 +147,9 @@ function messagesFor(request, aliases, assistants) {
|
|
|
125
147
|
return { role: 'assistant', content: '', ...(own?.thinking ? { thinking: own.thinking } : {}), tool_calls: toolCalls };
|
|
126
148
|
})];
|
|
127
149
|
}
|
|
128
|
-
/** Ids for a response's tool calls, which Ollama does not give: unique within the
|
|
150
|
+
/** Ids for a response's tool calls, which Ollama does not give: unique within the conversation, its history included. */
|
|
129
151
|
function callIds(request, count) {
|
|
130
|
-
const used = new Set(request.messages.flatMap(message => message.role === 'assistant' ? message.calls.map(call => call.id) : message.role === 'tool' ? [message.callId] : []));
|
|
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] : []));
|
|
131
153
|
const ids = [];
|
|
132
154
|
for (let next = used.size + 1; ids.length < count; next++)
|
|
133
155
|
if (!used.has(`call_${next}`))
|
|
@@ -332,7 +354,7 @@ export function ollama(options = {}) {
|
|
|
332
354
|
};
|
|
333
355
|
return Object.freeze({
|
|
334
356
|
id: settings.id, maxCostMicros: settings.maxCostMicros,
|
|
335
|
-
capabilities: Object.freeze({ tools: true, structuredOutput: true, ...(media ? { media } : {}) }),
|
|
357
|
+
capabilities: Object.freeze({ tools: true, structuredOutput: true, history: true, ...(media ? { media } : {}) }),
|
|
336
358
|
checkDefinition: (definition) => checkStrictDefinition(definition),
|
|
337
359
|
generate: (request) => call(request),
|
|
338
360
|
stream: (request) => streamModelCall((onDelta, consumer) => call(request, onDelta, consumer)),
|
|
@@ -340,4 +362,5 @@ export function ollama(options = {}) {
|
|
|
340
362
|
},
|
|
341
363
|
});
|
|
342
364
|
}
|
|
365
|
+
export { ollamaEmbeddings } from './embeddings.js';
|
|
343
366
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +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,iBAAiB,EAAE,cAAc,EAAE,eAAe,EAAE,mBAAmB,EAAE,eAAe,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAwBrM,MAAM,YAAY,GAAyB,MAAM,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC,CAAC;AACtF,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC,CAAC;AAE9D,MAAM,MAAM,GAAG,CAAC,MAAM,GAAuB,kBAAkB,EAAS,EAAE,GAAG,MAAM,IAAI,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AACrH,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAsB,EAAE,CAAC,KAAK,YAAY,kBAAkB,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,kBAAkB,CAAC;AACjI,SAAS,MAAM,CAAC,KAA4B;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BACrE,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,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;gBACjG,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","sourcesContent":["import { Ollama } from 'ollama/browser';\nimport { assertPositiveInteger, jsonValue, MayuraError, ModelProviderError, type JsonObject, type JsonValue, type Media, type MediaType, type ModelAdapter,\n type ModelDefinitionCheck, type ModelFailureReason, type ModelMediaCapability, type ModelMessage, type ModelProvider, type ModelRequest, type ModelResponse,\n type ModelStreamEvent, type ModelToolCall, type ProviderModelSettings } from 'mayura';\nimport { bytesToBase64, checkStrictDefinition, encodedMediaBytes, modelToolNames, providerHeaders, providerHttpFailure, streamModelCall, strictJsonSchema, tokenCostMicros } from 'mayura/core/host';\n\nexport interface OllamaProviderOptions {\n /**\n * The Ollama server: a loopback address over http (the default is http://127.0.0.1:11434), or any https URL, such as\n * https://ollama.com for Ollama's cloud models or a gateway.\n */\n readonly host?: string;\n /** An API key, sent as a bearer token. Required for https://ollama.com: the provider never reads OLLAMA_API_KEY. */\n readonly apiKey?: string;\n /** Extra headers, such as a gateway's credential. Treated as credentials. They cannot replace Authorization. */\n readonly headers?: Readonly<Record<string, string>>;\n /** Whether and how hard thinking models think. Leave it unset for a model that does not think. */\n readonly think?: boolean | 'low' | 'medium' | 'high';\n /** What the models can see. The default is nothing; give PNG or JPEG images (as bytes) for a vision model. */\n readonly media?: ModelMediaCapability | false;\n readonly maxRequestBytes?: number;\n readonly maxResponseBytes?: number;\n /** How long one call may take unless the registry sets `timeoutMs` (default 120 s, as a local model may need loading first). */\n readonly timeoutMs?: number;\n /** A trusted transport for tests or proxies. Never selected from model output. */\n readonly fetch?: typeof globalThis.fetch;\n}\n\nconst OLLAMA_MEDIA: readonly MediaType[] = Object.freeze(['image/png', 'image/jpeg']);\nconst LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nconst failed = (reason: ModelFailureReason = 'invalid_response'): never => { throw new ModelProviderError(reason); };\nconst reasonOf = (error: unknown): ModelFailureReason => error instanceof ModelProviderError ? error.reason : 'invalid_response';\nfunction object(value: JsonValue | undefined): JsonObject {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return failed();\n return value;\n}\nfunction integer(value: JsonValue | undefined): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) return failed();\n return value;\n}\nfunction mediaOption(value: ModelMediaCapability | false | undefined): ModelMediaCapability | undefined {\n if (value === undefined || value === false) return undefined;\n if (!Array.isArray(value.types) || value.types.length === 0 || value.types.some(type => !OLLAMA_MEDIA.includes(type)) || value.urls !== false) {\n throw new MayuraError('INVALID_CONFIG', 'media must list PNG or JPEG images, sent as bytes (urls: false).');\n }\n return Object.freeze({ types: Object.freeze([...new Set(value.types)] as MediaType[]), urls: false });\n}\n/** The server's base URL: http only on a loopback address, https anywhere; no credentials, query or fragment. */\nfunction hostOf(value: unknown): string {\n if (value === undefined) return 'http://127.0.0.1:11434';\n let url: URL;\n try { url = new URL(typeof value === 'string' ? value : ''); } catch { throw new MayuraError('INVALID_CONFIG', 'ollama(): host must be an absolute URL.'); }\n if (!(url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK.has(url.hostname))) || url.username || url.password || url.search || url.hash || url.href.length > 2_048) {\n throw new MayuraError('INVALID_CONFIG', 'ollama(): host must be http on a loopback address or https, without credentials, query or fragment.');\n }\n return url.href.replace(/\\/+$/u, '');\n}\n\n/** A response larger than the configured limit; reported as an unusable response. */\nclass ResponseTooLarge extends Error {}\n/** The server could not be reached, for example because Ollama is not running. */\nclass ConnectionFailure extends Error {}\n/** An error status; its body, which may echo the request, is never read. */\nclass HttpFailure extends Error { constructor(readonly status: number) { super('HTTP failure'); } }\n/**\n * One call's transport: cancelled by the call's signal (the SDK passes none for a non-streamed call), no redirects, an\n * error status reported without reading its body, and a body larger than `limit` (four times that for a stream) fails.\n */\nfunction callFetch(transport: typeof globalThis.fetch, limit: number, signal: AbortSignal): typeof globalThis.fetch {\n return async (input, init) => {\n let response: Response;\n try {\n response = await transport(input, { ...init, signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal, redirect: 'error' });\n } catch (error) {\n if (signal.aborted) throw error;\n throw new ConnectionFailure('Ollama could not be reached.', { cause: error });\n }\n if (!response.ok) { void response.body?.cancel().catch(() => undefined); throw new HttpFailure(response.status); }\n const max = (response.headers.get('content-type') ?? '').includes('ndjson') ? limit * 4 : limit;\n const length = response.headers.get('content-length');\n if (length !== null && (!/^\\d+$/u.test(length) || Number(length) > max)) { void response.body?.cancel().catch(() => undefined); throw new ResponseTooLarge(); }\n if (!response.body) return response;\n let size = 0;\n const counted = response.body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) { size += chunk.byteLength; if (size > max) controller.error(new ResponseTooLarge()); else controller.enqueue(chunk); },\n }));\n return new Response(counted, { status: response.status, statusText: response.statusText, headers: response.headers });\n };\n}\n\n/** Images as base64, as Ollama takes them. */\nfunction images(media: readonly Media[] | undefined): { images?: string[] } {\n if (!media?.length) return {};\n return { images: media.map(item => 'data' in item && OLLAMA_MEDIA.includes(item.mediaType) ? bytesToBase64(item.data) : failed('configuration')) };\n}\n/** Image names, which Ollama's image list cannot carry, follow the text. */\nconst withNames = (text: string, media: readonly Media[] | undefined): string => {\n const names = (media ?? []).flatMap(item => item.name === undefined ? [] : [item.name]);\n return names.length ? `${text}\\n\\nImages, in order: ${names.join(', ')}` : text;\n};\n\n/** One of the model's own tool-call turns in this run: its thinking and the ids given to its calls. */\ntype OwnTurn = { thinking: string | null; calls: string[] };\n/** The conversation as Ollama chat messages; `assistants` are the model's own earlier tool-call turns. */\nfunction messagesFor(request: ModelRequest, aliases: ReadonlyMap<string, string>, assistants: readonly OwnTurn[]): JsonValue[] {\n let turn = 0;\n return [{ role: 'system', content: request.instructions }, ...(request.messages as readonly ModelMessage[]).map((message): JsonValue => {\n if (message.role === 'user') return { role: 'user', content: withNames(JSON.stringify(message.content), message.media), ...images(message.media) };\n if (message.role === 'tool') {\n const name = aliases.get(message.toolId); if (!name) return failed();\n return { role: 'tool', tool_name: name, content: withNames(JSON.stringify(message.result), message.media), ...images(message.media) };\n }\n const toolCalls = message.calls.map(call => {\n const name = aliases.get(call.toolId); if (!name) return failed();\n return { function: { name, arguments: call.input } };\n });\n const own = assistants[turn++];\n if (own && (own.calls.length !== message.calls.length || own.calls.some((id, index) => id !== message.calls[index]!.id))) return failed();\n return { role: 'assistant', content: '', ...(own?.thinking ? { thinking: own.thinking } : {}), tool_calls: toolCalls };\n })];\n}\n/** Ids for a response's tool calls, which Ollama does not give: unique within the run. */\nfunction callIds(request: ModelRequest, count: number): string[] {\n const used = new Set(request.messages.flatMap(message => message.role === 'assistant' ? message.calls.map(call => call.id) : message.role === 'tool' ? [message.callId] : []));\n const ids: string[] = [];\n for (let next = used.size + 1; ids.length < count; next++) if (!used.has(`call_${next}`)) ids.push(`call_${next}`);\n return ids;\n}\n\n/** Rebuilds the response a non-streamed call returns from Ollama's stream, reporting text as it arrives. */\nasync function assemble(chunks: AsyncIterable<unknown>, maxResponseBytes: number, onDelta: (text: string) => void): Promise<JsonObject> {\n let content = ''; let thinking = ''; const toolCalls: JsonValue[] = []; let last: JsonObject | undefined;\n try {\n for await (const raw of chunks) {\n const data = object(jsonValue(JSON.parse(JSON.stringify(raw)) as JsonValue, { maxBytes: maxResponseBytes }));\n const message = data['message'] === undefined ? {} : object(data['message']);\n if (typeof message['content'] === 'string' && message['content']) { content += message['content']; onDelta(message['content']); }\n if (typeof message['thinking'] === 'string') thinking += message['thinking'];\n if (Array.isArray(message['tool_calls'])) { toolCalls.push(...message['tool_calls']); if (toolCalls.length > 128) return failed(); }\n if (data['done'] === true) last = data;\n }\n } catch (error) {\n // The server reported an error mid-answer, or ended the stream without finishing it.\n if (error instanceof ModelProviderError || error instanceof ResponseTooLarge || error instanceof SyntaxError) throw error;\n return failed('unavailable');\n }\n if (!last) return failed();\n return { ...last, message: { role: 'assistant', content, ...(thinking ? { thinking } : {}), ...(toolCalls.length ? { tool_calls: toolCalls } : {}) } };\n}\n\n/**\n * Ollama models for a Mayura model registry, local or in Ollama's cloud, through the official Ollama SDK:\n *\n * ```ts\n * const models = createModels({\n * providers: [ollama()],\n * prices: { 'ollama/gpt-oss:20b': { inputMicrosPerMillionTokens: 0, outputMicrosPerMillionTokens: 0 } },\n * maxCallCostMicros: 1,\n * });\n * const model = models.model('ollama/gpt-oss:20b'); // granted as model:ollama/gpt-oss:20b\n * ```\n *\n * Local models cost nothing, so there is no catalog: give each model's price, zero or your own. Structured output\n * and tool inputs use JSON Schema; streaming reports output text as it arrives; the model's thinking is kept for the\n * next call of the run and never released. Nothing is read from the environment or the file system.\n */\nexport function ollama(options: OllamaProviderOptions = {}): ModelProvider {\n if (!options || typeof options !== 'object') throw new MayuraError('INVALID_CONFIG', 'ollama() options must be an object.');\n const host = hostOf(options.host);\n if (options.apiKey !== undefined && (typeof options.apiKey !== 'string' || !options.apiKey.trim() || /[\\r\\n]/u.test(options.apiKey) || options.apiKey.length > 4096)) {\n throw new MayuraError('INVALID_CONFIG', 'ollama(): apiKey must be a non-empty string.');\n }\n // The SDK falls back to OLLAMA_API_KEY for ollama.com; the key must be given instead.\n if (new URL(host).hostname === 'ollama.com' && options.apiKey === undefined) throw new MayuraError('INVALID_CONFIG', 'ollama(): https://ollama.com needs an apiKey.');\n const headers = { ...providerHeaders(options.headers, ['Authorization', 'Accept', 'User-Agent'], 'ollama()'), ...(options.apiKey === undefined ? {} : { Authorization: `Bearer ${options.apiKey}` }) };\n if (options.think !== undefined && ![true, false, 'low', 'medium', 'high'].includes(options.think)) throw new MayuraError('INVALID_CONFIG', 'ollama(): think must be true, false, low, medium or high.');\n const maxRequestBytes = options.maxRequestBytes ?? 1_048_576; const maxResponseBytes = options.maxResponseBytes ?? 1_048_576;\n const defaultTimeout = options.timeoutMs ?? 120_000;\n for (const [value, name] of [[maxRequestBytes, 'maxRequestBytes'], [maxResponseBytes, 'maxResponseBytes'], [defaultTimeout, 'timeoutMs']] as const) assertPositiveInteger(value, name);\n const media = mediaOption(options.media);\n\n return Object.freeze({\n id: 'ollama',\n model(name: string, settings: ProviderModelSettings): ModelAdapter {\n if (typeof name !== 'string' || !name.trim() || name.length > 128) throw new MayuraError('INVALID_CONFIG', 'An Ollama model name is required.');\n const timeoutMs = settings.timeoutMs ?? defaultTimeout;\n\n const call = async (request: ModelRequest, onDelta?: (text: string) => void, consumer?: AbortSignal): Promise<ModelResponse> => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n let knownCost: number | undefined; let inputTokens = 0; let outputTokens = 0;\n try {\n const signal = AbortSignal.any([request.signal, controller.signal, ...(consumer ? [consumer] : [])]);\n if (signal.aborted) throw new MayuraError('CANCELLED', 'Provider request was cancelled.');\n let assistants: OwnTurn[] = [];\n if (request.continuation !== undefined) {\n const previous = object(request.continuation);\n if (previous['provider'] !== 'ollama.chat.v1' || previous['model'] !== name || !Array.isArray(previous['assistants'])) return failed();\n assistants = previous['assistants'].map(raw => {\n const turn = object(raw);\n if ((turn['thinking'] !== null && typeof turn['thinking'] !== 'string') || !Array.isArray(turn['calls']) || turn['calls'].some(id => typeof id !== 'string')) return failed();\n return { thinking: turn['thinking'], calls: turn['calls'] as string[] };\n });\n }\n if (assistants.length > request.messages.filter(message => message.role === 'assistant').length) return failed();\n assertPositiveInteger(request.maxOutputTokens, 'maxOutputTokens');\n const aliases = new Map(modelToolNames(request.tools.map(tool => tool.id)));\n const ids = new Map([...aliases].map(([toolId, alias]) => [alias, toolId]));\n if (aliases.size !== request.tools.length || aliases.size > 128) return failed();\n const tools = request.tools.map(tool => {\n if (!tool.inputJsonSchema) throw new MayuraError('INVALID_CONFIG', `Tool \"${tool.id}\" has no inputJsonSchema.`);\n return { type: 'function', function: { name: aliases.get(tool.id)!, description: tool.description, parameters: strictJsonSchema(tool.inputJsonSchema, `Tool \"${tool.id}\" input schema`) } };\n });\n const outputSchema = request.outputJsonSchema === undefined ? failed('configuration') : strictJsonSchema(request.outputJsonSchema, 'The output schema');\n // A format constrains a reply to the answer, which leaves no way to call a tool. So with tools, the model first\n // answers freely; once it calls no more tools, one more call without tools asks for the answer in the format.\n const messages = messagesFor(request, aliases, assistants);\n const common = { model: name, messages, options: { num_predict: request.maxOutputTokens }, ...(options.think === undefined ? {} : { think: options.think }) };\n // Ollama's cloud accepts a format without enforcing it, so a request with one also gives the schema in its instructions.\n const formatted: JsonObject = { ...common, format: outputSchema, messages: [\n { role: 'system', content: `${request.instructions}\\n\\nAnswer with one JSON object, and nothing else, that matches this JSON Schema:\\n${JSON.stringify(outputSchema)}` }, ...messages.slice(1)] };\n const body: JsonObject = tools.length > 0 ? { ...common, tools } : formatted;\n jsonValue(body, { maxBytes: maxRequestBytes + encodedMediaBytes(request.messages) });\n\n // A client per call, so the call's signal reaches every request it makes.\n const client = new Ollama({ host, headers, fetch: callFetch(options.fetch ?? globalThis.fetch, maxResponseBytes, signal) });\n const chat = async (request: JsonObject, stream: ((text: string) => void) | undefined): Promise<JsonObject> => {\n const payload = stream\n ? await assemble(await client.chat({ ...request, stream: true } as never) as unknown as AsyncIterable<unknown>, maxResponseBytes, stream)\n : object(jsonValue(JSON.parse(JSON.stringify(await client.chat({ ...request, stream: false } as never))) as JsonValue, { maxBytes: maxResponseBytes * 2 }));\n // Ollama leaves out the prompt count when the whole prompt was cached.\n const prompt = payload['prompt_eval_count'] === undefined ? 0 : integer(payload['prompt_eval_count']); const completion = integer(payload['eval_count']);\n knownCost = (knownCost ?? 0) + (tokenCostMicros(settings.pricing, prompt, completion) ?? failed());\n inputTokens += prompt; outputTokens += completion;\n if (payload['done'] !== true) return failed();\n return payload;\n };\n const finalFrom = (payload: JsonObject): ModelResponse => {\n const message = object(payload['message']); const finish = payload['done_reason'];\n // Output cut off by the token limit is not an answer.\n if (finish === 'length') return failed('refused');\n if (finish !== 'stop' || typeof message['content'] !== 'string' || (Array.isArray(message['tool_calls']) && message['tool_calls'].length > 0)) return failed();\n return { type: 'final', output: jsonValue(JSON.parse(message['content']) as JsonValue, { maxBytes: maxResponseBytes }), usage: { costMicros: knownCost!, inputTokens, outputTokens } };\n };\n if (tools.length === 0) return finalFrom(await chat(body, onDelta));\n\n // The free reply is never streamed: it may be prose, which is not the answer.\n const payload = await chat(body, onDelta ? () => undefined : undefined);\n const message = object(payload['message']); const finish = payload['done_reason'];\n const toolCalls = message['tool_calls'] ?? [];\n if (!Array.isArray(toolCalls) || toolCalls.length > 128) return failed();\n if (toolCalls.length > 0 && finish === 'stop') {\n const given = callIds(request, toolCalls.length);\n const calls: ModelToolCall[] = toolCalls.map((raw, index) => {\n const fn = object(object(raw)['function']); const alias = fn['name']; const args = fn['arguments'];\n if (typeof alias !== 'string' || !ids.has(alias)) return failed();\n const input = typeof args === 'string' ? JSON.parse(args || '{}') as JsonValue : args === undefined ? {} : object(args);\n return { id: given[index]!, toolId: ids.get(alias)!, input: jsonValue(input, { maxBytes: maxResponseBytes }) };\n });\n const thinking = typeof message['thinking'] === 'string' && message['thinking'] ? message['thinking'] : null;\n const continuation = jsonValue({ provider: 'ollama.chat.v1', model: name, assistants: [...assistants, { thinking, calls: calls.map(entry => entry.id) }] }, { maxBytes: maxRequestBytes });\n return { type: 'tool_calls', calls, usage: { costMicros: knownCost!, inputTokens, outputTokens }, continuation };\n }\n if (finish === 'length') return failed('refused');\n if (finish !== 'stop') return failed();\n return finalFrom(await chat(formatted, onDelta));\n } catch (error) {\n if (knownCost !== undefined) throw new ModelProviderError(reasonOf(error), { costMicros: knownCost });\n if (request.signal.aborted || controller.signal.aborted || consumer?.aborted) throw new MayuraError('CANCELLED', 'Provider request was cancelled or timed out.');\n if (error instanceof ModelProviderError) throw error;\n if (error instanceof MayuraError && error.code === 'INVALID_CONFIG') return failed('configuration');\n if (error instanceof HttpFailure) throw providerHttpFailure(error.status);\n if (error instanceof ConnectionFailure) return failed('unavailable');\n return failed();\n } finally { clearTimeout(timer); }\n };\n\n return Object.freeze({\n id: settings.id, maxCostMicros: settings.maxCostMicros,\n capabilities: Object.freeze({ tools: true, structuredOutput: true, ...(media ? { media } : {}) }),\n checkDefinition: (definition: ModelDefinitionCheck): void => checkStrictDefinition(definition),\n generate: (request: ModelRequest): Promise<ModelResponse> => call(request),\n stream: (request: ModelRequest): AsyncIterable<ModelStreamEvent> => streamModelCall((onDelta, consumer) => call(request, onDelta, consumer)),\n });\n },\n });\n}\n"]}
|
|
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,iBAAiB,EAAE,cAAc,EAAE,eAAe,EAAE,mBAAmB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C;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,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mayurajs/provider-ollama",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "Ollama models for Mayura, local or in Ollama's cloud, through the official Ollama SDK.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Aryabh",
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"ollama": "0.6.3"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
|
-
"mayura": "^1.
|
|
41
|
+
"mayura": "^1.2.0"
|
|
42
42
|
},
|
|
43
43
|
"publishConfig": {
|
|
44
44
|
"access": "public",
|
|
@@ -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
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Ollama } from 'ollama/browser';
|
|
2
2
|
import { assertPositiveInteger, jsonValue, MayuraError, ModelProviderError, type JsonObject, type JsonValue, type Media, type MediaType, type ModelAdapter,
|
|
3
|
-
type ModelDefinitionCheck, type ModelFailureReason, type ModelMediaCapability, type ModelMessage, type ModelProvider, type ModelRequest, type ModelResponse,
|
|
3
|
+
type ModelDefinitionCheck, type ModelFailureReason, type ModelHistoryMessage, type ModelMediaCapability, type ModelMessage, type ModelProvider, type ModelRequest, type ModelResponse,
|
|
4
4
|
type ModelStreamEvent, type ModelToolCall, type ProviderModelSettings } from 'mayura';
|
|
5
5
|
import { bytesToBase64, checkStrictDefinition, encodedMediaBytes, modelToolNames, providerHeaders, providerHttpFailure, streamModelCall, strictJsonSchema, tokenCostMicros } from 'mayura/core/host';
|
|
6
6
|
|
|
@@ -102,10 +102,28 @@ const withNames = (text: string, media: readonly Media[] | undefined): string =>
|
|
|
102
102
|
|
|
103
103
|
/** One of the model's own tool-call turns in this run: its thinking and the ids given to its calls. */
|
|
104
104
|
type OwnTurn = { thinking: string | null; calls: string[] };
|
|
105
|
-
/**
|
|
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
|
+
*/
|
|
106
124
|
function messagesFor(request: ModelRequest, aliases: ReadonlyMap<string, string>, assistants: readonly OwnTurn[]): JsonValue[] {
|
|
107
125
|
let turn = 0;
|
|
108
|
-
return [{ role: 'system', content: request.instructions }, ...(request.messages as readonly ModelMessage[]).map((message): JsonValue => {
|
|
126
|
+
return [{ role: 'system', content: request.instructions }, ...request.history ? historyMessages(request, request.history) : [], ...(request.messages as readonly ModelMessage[]).map((message): JsonValue => {
|
|
109
127
|
if (message.role === 'user') return { role: 'user', content: withNames(JSON.stringify(message.content), message.media), ...images(message.media) };
|
|
110
128
|
if (message.role === 'tool') {
|
|
111
129
|
const name = aliases.get(message.toolId); if (!name) return failed();
|
|
@@ -120,9 +138,9 @@ function messagesFor(request: ModelRequest, aliases: ReadonlyMap<string, string>
|
|
|
120
138
|
return { role: 'assistant', content: '', ...(own?.thinking ? { thinking: own.thinking } : {}), tool_calls: toolCalls };
|
|
121
139
|
})];
|
|
122
140
|
}
|
|
123
|
-
/** Ids for a response's tool calls, which Ollama does not give: unique within the
|
|
141
|
+
/** Ids for a response's tool calls, which Ollama does not give: unique within the conversation, its history included. */
|
|
124
142
|
function callIds(request: ModelRequest, count: number): string[] {
|
|
125
|
-
const used = new Set(request.messages.flatMap(message => message.role === 'assistant' ? message.calls.map(call => call.id) : message.role === 'tool' ? [message.callId] : []));
|
|
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] : []));
|
|
126
144
|
const ids: string[] = [];
|
|
127
145
|
for (let next = used.size + 1; ids.length < count; next++) if (!used.has(`call_${next}`)) ids.push(`call_${next}`);
|
|
128
146
|
return ids;
|
|
@@ -278,7 +296,7 @@ export function ollama(options: OllamaProviderOptions = {}): ModelProvider {
|
|
|
278
296
|
|
|
279
297
|
return Object.freeze({
|
|
280
298
|
id: settings.id, maxCostMicros: settings.maxCostMicros,
|
|
281
|
-
capabilities: Object.freeze({ tools: true, structuredOutput: true, ...(media ? { media } : {}) }),
|
|
299
|
+
capabilities: Object.freeze({ tools: true, structuredOutput: true, history: true, ...(media ? { media } : {}) }),
|
|
282
300
|
checkDefinition: (definition: ModelDefinitionCheck): void => checkStrictDefinition(definition),
|
|
283
301
|
generate: (request: ModelRequest): Promise<ModelResponse> => call(request),
|
|
284
302
|
stream: (request: ModelRequest): AsyncIterable<ModelStreamEvent> => streamModelCall((onDelta, consumer) => call(request, onDelta, consumer)),
|
|
@@ -286,3 +304,5 @@ export function ollama(options: OllamaProviderOptions = {}): ModelProvider {
|
|
|
286
304
|
},
|
|
287
305
|
});
|
|
288
306
|
}
|
|
307
|
+
|
|
308
|
+
export { ollamaEmbeddings, type EmbeddingsOptions } from './embeddings.js';
|