agentic-server 0.30.0 → 0.30.2
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 +20 -0
- package/errors.d.ts +10 -0
- package/errors.js +17 -0
- package/esm/errors.js +13 -0
- package/esm/index.js +2 -0
- package/esm/providers.js +34 -15
- package/esm/router.js +34 -5
- package/esm/transforms.js +142 -18
- package/index.d.ts +2 -0
- package/index.js +10 -1
- package/package.json +2 -2
- package/providers.d.ts +2 -1
- package/providers.js +34 -15
- package/router.js +33 -4
- package/transforms.d.ts +7 -0
- package/transforms.js +145 -18
- package/types.d.ts +6 -0
package/README.md
CHANGED
|
@@ -50,6 +50,26 @@ app.listen(3001, () => {
|
|
|
50
50
|
|
|
51
51
|
`POST /v1/chat/completions` with `stream: true` is relayed as a `text/event-stream`: the gateway forwards the provider's frames verbatim, so a client receives tokens as they are produced. It adds `stream_options: { include_usage: true }` unless the caller set `stream_options` itself, and meters the usage the final frame carries. Streaming is available for OpenAI-compatible providers; a provider whose stream would need translation (`ollama`, `anthropic`) is rejected `501` rather than answered with a non-streaming body.
|
|
52
52
|
|
|
53
|
+
## Providers and routing
|
|
54
|
+
|
|
55
|
+
`providers` is a registry; each entry has a `type` (the dialect: `openai`, `anthropic`, `ollama`) and an optional `name` it is addressed by, which defaults to the type. Two entries of one dialect — an in-cluster Ollama and one on a GPU host — are both reachable by name:
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
createAgenticServer({
|
|
59
|
+
providers: [
|
|
60
|
+
{ name: 'ollama', type: 'ollama', baseUrl: 'http://ollama:11434' },
|
|
61
|
+
{ name: 'host-ollama', type: 'ollama', baseUrl: 'http://host.docker.internal:11434' },
|
|
62
|
+
{ type: 'openai', baseUrl: 'https://api.openai.com', apiKey: process.env.OPENAI_API_KEY }
|
|
63
|
+
]
|
|
64
|
+
});
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
A request picks its provider, in this order: the `X-LLM-Provider` header (a name, or a type for an entry with no name); a `name/model` prefix such as `host-ollama/qwen3:8b` (stripped before the call goes upstream); a known model family (`claude*` → anthropic; `gpt-oss*`, `llama*`, `mistral*`, `gemma*`, `nomic*`, `qwen*`, `glm*` → ollama; `gpt*`, `o1*`, `o3*` → openai); otherwise the first entry.
|
|
68
|
+
|
|
69
|
+
### The Ollama dialect
|
|
70
|
+
|
|
71
|
+
A request to an `ollama` provider is rewritten for `/api/chat`: content parts are flattened to the string Ollama takes; `max_tokens` becomes `options.num_predict` and `num_ctx` becomes `options.num_ctx` (a client `options` object is merged under them); `tools`, `think` and `keep_alive` are forwarded as-is; `response_format` becomes `format` (`json_object` → `'json'`, `json_schema` → the schema; a native `format` is passed through). The reply comes back in the OpenAI shape, including `tool_calls` (arguments as a JSON string, `finish_reason: 'tool_calls'`) and `reasoning_content` for a `thinking` message, so a tool-calling harness can run on an Ollama-served model.
|
|
72
|
+
|
|
53
73
|
## Identity & tenancy
|
|
54
74
|
|
|
55
75
|
Requests carry tenant identity via headers: `X-Database-Id` (**required** — requests without it are rejected `400`), `X-Entity-Id`, and `X-Actor-Id`. Routing to a specific provider can be forced with `X-LLM-Provider`.
|
package/errors.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A request the gateway rejects before contacting any upstream: an unknown
|
|
3
|
+
* provider pinned by `X-LLM-Provider`, or a body the target dialect cannot
|
|
4
|
+
* express. The router answers it with `400` so a client mistake never reads
|
|
5
|
+
* as a provider outage.
|
|
6
|
+
*/
|
|
7
|
+
export declare class BadRequestError extends Error {
|
|
8
|
+
readonly status = 400;
|
|
9
|
+
constructor(message: string);
|
|
10
|
+
}
|
package/errors.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.BadRequestError = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* A request the gateway rejects before contacting any upstream: an unknown
|
|
6
|
+
* provider pinned by `X-LLM-Provider`, or a body the target dialect cannot
|
|
7
|
+
* express. The router answers it with `400` so a client mistake never reads
|
|
8
|
+
* as a provider outage.
|
|
9
|
+
*/
|
|
10
|
+
class BadRequestError extends Error {
|
|
11
|
+
status = 400;
|
|
12
|
+
constructor(message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = 'BadRequestError';
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
exports.BadRequestError = BadRequestError;
|
package/esm/errors.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A request the gateway rejects before contacting any upstream: an unknown
|
|
3
|
+
* provider pinned by `X-LLM-Provider`, or a body the target dialect cannot
|
|
4
|
+
* express. The router answers it with `400` so a client mistake never reads
|
|
5
|
+
* as a provider outage.
|
|
6
|
+
*/
|
|
7
|
+
export class BadRequestError extends Error {
|
|
8
|
+
status = 400;
|
|
9
|
+
constructor(message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = 'BadRequestError';
|
|
12
|
+
}
|
|
13
|
+
}
|
package/esm/index.js
CHANGED
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
* app.listen(3001);
|
|
22
22
|
* ```
|
|
23
23
|
*/
|
|
24
|
+
export { BadRequestError } from './errors';
|
|
24
25
|
export { buildProviderHeaders, resolveProvider, resolveUpstreamUrl } from './providers';
|
|
25
26
|
export { createRouter } from './router';
|
|
26
27
|
export { createAgenticServer } from './server';
|
|
28
|
+
export { providerName, transformChatRequest, transformChatResponse, transformEmbedRequest, transformEmbedResponse, upstreamModel } from './transforms';
|
package/esm/providers.js
CHANGED
|
@@ -1,40 +1,55 @@
|
|
|
1
|
+
import { BadRequestError } from './errors';
|
|
2
|
+
import { providerName } from './transforms';
|
|
3
|
+
/**
|
|
4
|
+
* Open-weights families Ollama serves. `gpt-oss` is listed because the
|
|
5
|
+
* `gpt` prefix would otherwise read as OpenAI's hosted models.
|
|
6
|
+
*/
|
|
7
|
+
const OLLAMA_MODEL_PREFIXES = ['gpt-oss', 'llama', 'mistral', 'gemma', 'nomic', 'qwen', 'glm'];
|
|
8
|
+
const startsWithAny = (model, prefixes) => prefixes.some((prefix) => model.startsWith(prefix));
|
|
9
|
+
/**
|
|
10
|
+
* The entry a request addresses: by registry name first, so two providers of
|
|
11
|
+
* one dialect are both reachable, then by dialect for an entry with no name of
|
|
12
|
+
* its own.
|
|
13
|
+
*/
|
|
14
|
+
const findNamed = (providers, name) => providers.find((p) => providerName(p) === name) ?? providers.find((p) => p.type === name);
|
|
1
15
|
/**
|
|
2
16
|
* Resolve which provider to use for a given request.
|
|
3
|
-
* Priority:
|
|
17
|
+
* Priority: explicit provider header → `name/model` prefix → known model
|
|
18
|
+
* families → the first configured provider.
|
|
4
19
|
*/
|
|
5
20
|
export function resolveProvider(options, requestModel, requestProvider) {
|
|
6
21
|
const providers = options.providers || [];
|
|
7
22
|
if (providers.length > 0) {
|
|
8
23
|
if (requestProvider) {
|
|
9
|
-
const match = providers
|
|
24
|
+
const match = findNamed(providers, requestProvider);
|
|
10
25
|
if (match)
|
|
11
26
|
return match;
|
|
27
|
+
// A request pinned to a provider that is not registered must not drift
|
|
28
|
+
// to whichever entry a heuristic picks.
|
|
29
|
+
throw new BadRequestError(`unknown provider '${requestProvider}'; registered: ${providers.map(providerName).join(', ')}`);
|
|
12
30
|
}
|
|
13
|
-
// Route by model prefix: "anthropic/claude-3" →
|
|
31
|
+
// Route by model prefix: "anthropic/claude-3" → the provider named anthropic
|
|
14
32
|
if (requestModel && requestModel.includes('/')) {
|
|
15
|
-
const prefix = requestModel.split('/')
|
|
16
|
-
const match = providers
|
|
33
|
+
const [prefix, ...rest] = requestModel.split('/');
|
|
34
|
+
const match = findNamed(providers, prefix);
|
|
17
35
|
if (match) {
|
|
18
|
-
return { ...match, defaultModel:
|
|
36
|
+
return { ...match, defaultModel: rest.join('/') };
|
|
19
37
|
}
|
|
20
38
|
}
|
|
21
|
-
// Route by known model
|
|
39
|
+
// Route by known model families
|
|
22
40
|
if (requestModel) {
|
|
23
41
|
if (requestModel.startsWith('claude')) {
|
|
24
42
|
const match = providers.find((p) => p.type === 'anthropic');
|
|
25
43
|
if (match)
|
|
26
44
|
return match;
|
|
27
45
|
}
|
|
28
|
-
if (
|
|
29
|
-
const match = providers.find((p) => p.type === '
|
|
46
|
+
if (startsWithAny(requestModel, OLLAMA_MODEL_PREFIXES)) {
|
|
47
|
+
const match = providers.find((p) => p.type === 'ollama');
|
|
30
48
|
if (match)
|
|
31
49
|
return match;
|
|
32
50
|
}
|
|
33
|
-
if (requestModel.startsWith('
|
|
34
|
-
|
|
35
|
-
requestModel.startsWith('gemma') ||
|
|
36
|
-
requestModel.startsWith('nomic')) {
|
|
37
|
-
const match = providers.find((p) => p.type === 'ollama');
|
|
51
|
+
if (requestModel.startsWith('gpt') || requestModel.startsWith('o1') || requestModel.startsWith('o3')) {
|
|
52
|
+
const match = providers.find((p) => p.type === 'openai');
|
|
38
53
|
if (match)
|
|
39
54
|
return match;
|
|
40
55
|
}
|
|
@@ -42,8 +57,12 @@ export function resolveProvider(options, requestModel, requestProvider) {
|
|
|
42
57
|
return providers[0];
|
|
43
58
|
}
|
|
44
59
|
// Single-provider mode (default: ollama for local dev)
|
|
60
|
+
const type = options.providerType || 'ollama';
|
|
61
|
+
if (requestProvider && requestProvider !== type) {
|
|
62
|
+
throw new BadRequestError(`unknown provider '${requestProvider}'; registered: ${type}`);
|
|
63
|
+
}
|
|
45
64
|
return {
|
|
46
|
-
type
|
|
65
|
+
type,
|
|
47
66
|
baseUrl: options.providerBaseUrl || 'http://localhost:11434',
|
|
48
67
|
apiKey: options.providerApiKey,
|
|
49
68
|
defaultModel: options.defaultModel
|
package/esm/router.js
CHANGED
|
@@ -11,10 +11,32 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { Logger } from '@pgpmjs/logger';
|
|
13
13
|
import { Router } from 'express';
|
|
14
|
+
import { BadRequestError } from './errors';
|
|
14
15
|
import { buildProviderHeaders, resolveProvider, resolveUpstreamUrl } from './providers';
|
|
15
16
|
import { relayEventStream, withUsageStreamOptions } from './streaming';
|
|
16
|
-
import { transformChatRequest, transformChatResponse, transformEmbedRequest, transformEmbedResponse } from './transforms';
|
|
17
|
+
import { providerName, transformChatRequest, transformChatResponse, transformEmbedRequest, transformEmbedResponse } from './transforms';
|
|
17
18
|
const log = new Logger('agentic-server');
|
|
19
|
+
/**
|
|
20
|
+
* Answer a request the gateway rejects itself — before any upstream call —
|
|
21
|
+
* with `400`, or report that `err` was something else. A client mistake must
|
|
22
|
+
* not be metered or reported as a provider failure.
|
|
23
|
+
*/
|
|
24
|
+
function rejectBadRequest(res, err) {
|
|
25
|
+
if (!(err instanceof BadRequestError))
|
|
26
|
+
return false;
|
|
27
|
+
res.status(err.status).json({ error: { message: err.message } });
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
function selectProvider(options, req, res) {
|
|
31
|
+
try {
|
|
32
|
+
return resolveProvider(options, req.body?.model, req.get('X-LLM-Provider'));
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
if (rejectBadRequest(res, err))
|
|
36
|
+
return undefined;
|
|
37
|
+
throw err;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
18
40
|
/** How long an upstream reason may be before it stops being a message. */
|
|
19
41
|
const UPSTREAM_REASON_LIMIT = 300;
|
|
20
42
|
/**
|
|
@@ -79,9 +101,10 @@ export const createRouter = (options) => {
|
|
|
79
101
|
}
|
|
80
102
|
const attribution = readAttribution(req);
|
|
81
103
|
const { entityId } = attribution;
|
|
82
|
-
const requestProvider = req.get('X-LLM-Provider');
|
|
83
104
|
const startTime = process.hrtime.bigint();
|
|
84
|
-
const provider =
|
|
105
|
+
const provider = selectProvider(options, req, res);
|
|
106
|
+
if (!provider)
|
|
107
|
+
return;
|
|
85
108
|
log.info('chat/completions', {
|
|
86
109
|
databaseId,
|
|
87
110
|
entityId,
|
|
@@ -199,6 +222,8 @@ export const createRouter = (options) => {
|
|
|
199
222
|
res.json(responseBody);
|
|
200
223
|
}
|
|
201
224
|
catch (err) {
|
|
225
|
+
if (!res.headersSent && rejectBadRequest(res, err))
|
|
226
|
+
return;
|
|
202
227
|
const latencyMs = Number(process.hrtime.bigint() - startTime) / 1e6;
|
|
203
228
|
log.error('chat/completions error', err);
|
|
204
229
|
if (sink) {
|
|
@@ -234,9 +259,10 @@ export const createRouter = (options) => {
|
|
|
234
259
|
}
|
|
235
260
|
const attribution = readAttribution(req);
|
|
236
261
|
const { entityId } = attribution;
|
|
237
|
-
const requestProvider = req.get('X-LLM-Provider');
|
|
238
262
|
const startTime = process.hrtime.bigint();
|
|
239
|
-
const provider =
|
|
263
|
+
const provider = selectProvider(options, req, res);
|
|
264
|
+
if (!provider)
|
|
265
|
+
return;
|
|
240
266
|
log.info('embeddings', { databaseId, entityId, provider: provider.type, model: req.body?.model });
|
|
241
267
|
try {
|
|
242
268
|
const upstreamUrl = resolveUpstreamUrl(provider, '/v1/embeddings');
|
|
@@ -290,6 +316,8 @@ export const createRouter = (options) => {
|
|
|
290
316
|
res.json(responseBody);
|
|
291
317
|
}
|
|
292
318
|
catch (err) {
|
|
319
|
+
if (rejectBadRequest(res, err))
|
|
320
|
+
return;
|
|
293
321
|
const latencyMs = Number(process.hrtime.bigint() - startTime) / 1e6;
|
|
294
322
|
log.error('embeddings error', err);
|
|
295
323
|
if (sink) {
|
|
@@ -349,6 +377,7 @@ export const createRouter = (options) => {
|
|
|
349
377
|
}];
|
|
350
378
|
res.json({
|
|
351
379
|
providers: providers.map((p) => ({
|
|
380
|
+
name: providerName(p),
|
|
352
381
|
type: p.type,
|
|
353
382
|
defaultModel: p.defaultModel
|
|
354
383
|
}))
|
package/esm/transforms.js
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
+
import { BadRequestError } from './errors';
|
|
2
|
+
/** The name a request routes with: the registry name, else the dialect. */
|
|
3
|
+
export const providerName = (provider) => provider.name ?? provider.type;
|
|
4
|
+
/**
|
|
5
|
+
* Strip the routing prefix a client uses to pick a provider (`anthropic/claude-…`,
|
|
6
|
+
* `host-ollama/qwen3`), which the upstream itself does not know.
|
|
7
|
+
*/
|
|
8
|
+
export function upstreamModel(provider, model) {
|
|
9
|
+
const requested = typeof model === 'string' && model ? model : provider.defaultModel;
|
|
10
|
+
if (!requested)
|
|
11
|
+
return undefined;
|
|
12
|
+
const [prefix, ...rest] = requested.split('/');
|
|
13
|
+
if (rest.length === 0)
|
|
14
|
+
return requested;
|
|
15
|
+
return prefix === providerName(provider) || prefix === provider.type ? rest.join('/') : requested;
|
|
16
|
+
}
|
|
1
17
|
/**
|
|
2
18
|
* Flatten OpenAI content parts into the single string Ollama's chat api takes.
|
|
3
19
|
*
|
|
@@ -11,7 +27,8 @@
|
|
|
11
27
|
function flattenContentParts(messages) {
|
|
12
28
|
if (!Array.isArray(messages))
|
|
13
29
|
return messages;
|
|
14
|
-
return messages.map((
|
|
30
|
+
return messages.map((original) => {
|
|
31
|
+
const message = ollamaToolCalls(original);
|
|
15
32
|
if (!Array.isArray(message.content))
|
|
16
33
|
return message;
|
|
17
34
|
const text = [];
|
|
@@ -24,16 +41,16 @@ function flattenContentParts(messages) {
|
|
|
24
41
|
if (part.type === 'image_url') {
|
|
25
42
|
const url = part.image_url?.url;
|
|
26
43
|
if (!url)
|
|
27
|
-
throw new
|
|
44
|
+
throw new BadRequestError('ollama: an image_url content part carries no url');
|
|
28
45
|
// Ollama takes base64 bytes, never a fetchable url.
|
|
29
46
|
const base64 = /^data:[^;]*;base64,(.*)$/.exec(url)?.[1];
|
|
30
47
|
if (!base64) {
|
|
31
|
-
throw new
|
|
48
|
+
throw new BadRequestError('ollama: an image content part must be a base64 data url');
|
|
32
49
|
}
|
|
33
50
|
images.push(base64);
|
|
34
51
|
continue;
|
|
35
52
|
}
|
|
36
|
-
throw new
|
|
53
|
+
throw new BadRequestError(`ollama: unsupported content part type '${part.type}'`);
|
|
37
54
|
}
|
|
38
55
|
return {
|
|
39
56
|
...message,
|
|
@@ -42,24 +59,74 @@ function flattenContentParts(messages) {
|
|
|
42
59
|
};
|
|
43
60
|
});
|
|
44
61
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
62
|
+
/**
|
|
63
|
+
* An earlier assistant turn replays its tool calls with `arguments` as the JSON
|
|
64
|
+
* string OpenAI returns them in; Ollama's struct wants the object, and answers
|
|
65
|
+
* the string with an unmarshal error.
|
|
66
|
+
*/
|
|
67
|
+
function ollamaToolCalls(message) {
|
|
68
|
+
if (!Array.isArray(message.tool_calls))
|
|
69
|
+
return message;
|
|
70
|
+
return {
|
|
71
|
+
...message,
|
|
72
|
+
tool_calls: message.tool_calls.map((call) => {
|
|
73
|
+
const args = call.function?.arguments;
|
|
74
|
+
if (typeof args !== 'string')
|
|
75
|
+
return call;
|
|
76
|
+
let parsed;
|
|
77
|
+
try {
|
|
78
|
+
parsed = JSON.parse(args);
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
throw new BadRequestError(`ollama: tool call '${call.function?.name ?? ''}' carries arguments that are not JSON: ${err.message}`);
|
|
82
|
+
}
|
|
83
|
+
return { ...call, function: { ...call.function, arguments: parsed } };
|
|
84
|
+
})
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Ollama's `format` from an OpenAI `response_format`: `json_object` is the
|
|
89
|
+
* `'json'` mode, `json_schema` is the schema itself. A native `format` wins
|
|
90
|
+
* when a caller already speaks the dialect.
|
|
91
|
+
*/
|
|
92
|
+
function ollamaFormat(body) {
|
|
93
|
+
if (body.format !== undefined)
|
|
94
|
+
return body.format;
|
|
95
|
+
const responseFormat = body.response_format;
|
|
96
|
+
if (!responseFormat || typeof responseFormat !== 'object')
|
|
97
|
+
return undefined;
|
|
98
|
+
if (responseFormat.type === 'json_object')
|
|
99
|
+
return 'json';
|
|
100
|
+
if (responseFormat.type === 'json_schema') {
|
|
101
|
+
if (responseFormat.json_schema?.schema === undefined) {
|
|
102
|
+
throw new BadRequestError('ollama: response_format json_schema carries no schema');
|
|
51
103
|
}
|
|
104
|
+
return responseFormat.json_schema.schema;
|
|
52
105
|
}
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
export function transformChatRequest(provider, body) {
|
|
109
|
+
const model = upstreamModel(provider, body.model);
|
|
53
110
|
if (provider.type === 'ollama') {
|
|
54
|
-
// Ollama takes sampling settings under `options`; `max_tokens`
|
|
111
|
+
// Ollama takes sampling and runtime settings under `options`; `max_tokens`
|
|
112
|
+
// is `num_predict`, and `num_ctx` (the context window the model is loaded
|
|
113
|
+
// with) has no OpenAI spelling, so it rides at the top level and moves here.
|
|
114
|
+
const clientOptions = (body.options && typeof body.options === 'object' ? body.options : {});
|
|
55
115
|
const options = {
|
|
116
|
+
...clientOptions,
|
|
56
117
|
...(body.temperature !== undefined && { temperature: body.temperature }),
|
|
57
|
-
...(body.max_tokens !== undefined && { num_predict: body.max_tokens })
|
|
118
|
+
...(body.max_tokens !== undefined && { num_predict: body.max_tokens }),
|
|
119
|
+
...(body.num_ctx !== undefined && { num_ctx: body.num_ctx })
|
|
58
120
|
};
|
|
121
|
+
const format = ollamaFormat(body);
|
|
59
122
|
return {
|
|
60
123
|
model: model || 'llama3',
|
|
61
124
|
messages: flattenContentParts(body.messages),
|
|
62
125
|
stream: false,
|
|
126
|
+
...(body.tools !== undefined && { tools: body.tools }),
|
|
127
|
+
...(format !== undefined && { format }),
|
|
128
|
+
...(body.think !== undefined && { think: body.think }),
|
|
129
|
+
...(body.keep_alive !== undefined && { keep_alive: body.keep_alive }),
|
|
63
130
|
...(Object.keys(options).length > 0 && { options })
|
|
64
131
|
};
|
|
65
132
|
}
|
|
@@ -78,12 +145,29 @@ export function transformChatRequest(provider, body) {
|
|
|
78
145
|
// OpenAI-compatible (default)
|
|
79
146
|
return { ...body, model: model || 'gpt-4o' };
|
|
80
147
|
}
|
|
148
|
+
// Anchored, so text that merely mentions a data url stays text. A media type
|
|
149
|
+
// may carry parameters before the encoding (`image/svg+xml;charset=utf-8;base64,`)
|
|
150
|
+
// and both are case-insensitive (RFC 2397).
|
|
151
|
+
const IMAGE_DATA_URL = /^data:image\/[^;,]+(?:;[^;,]+)*;base64,/i;
|
|
152
|
+
/**
|
|
153
|
+
* One embed input in Ollama's shape. An image arrives as a base64 `data:` url,
|
|
154
|
+
* the way OpenAI-style clients carry bytes; Ollama's multimodal embed takes it
|
|
155
|
+
* as `{ image: <base64> }`, and embeds the same url left as a string as text —
|
|
156
|
+
* a vector of the right length for the wrong thing, with no error.
|
|
157
|
+
*/
|
|
158
|
+
function ollamaEmbedInput(input) {
|
|
159
|
+
if (typeof input !== 'string')
|
|
160
|
+
return input;
|
|
161
|
+
const prefix = IMAGE_DATA_URL.exec(input)?.[0];
|
|
162
|
+
return prefix ? { image: input.slice(prefix.length) } : input;
|
|
163
|
+
}
|
|
81
164
|
export function transformEmbedRequest(provider, body) {
|
|
82
|
-
const model = body.model
|
|
165
|
+
const model = upstreamModel(provider, body.model);
|
|
83
166
|
if (provider.type === 'ollama') {
|
|
84
167
|
return {
|
|
85
168
|
model: model || 'nomic-embed-text',
|
|
86
|
-
input: body.input
|
|
169
|
+
input: Array.isArray(body.input) ? body.input.map(ollamaEmbedInput) : ollamaEmbedInput(body.input),
|
|
170
|
+
...(body.dimensions !== undefined && { dimensions: body.dimensions })
|
|
87
171
|
};
|
|
88
172
|
}
|
|
89
173
|
return { ...body, model: model || 'text-embedding-3-small' };
|
|
@@ -98,13 +182,23 @@ export function transformChatResponse(data, provider) {
|
|
|
98
182
|
completion_tokens: completionTokens,
|
|
99
183
|
total_tokens: promptTokens + completionTokens
|
|
100
184
|
};
|
|
185
|
+
const toolCalls = openAiToolCalls(msg?.tool_calls);
|
|
186
|
+
// A generation cut off by the token budget may hold half a tool call;
|
|
187
|
+
// only a completed turn is reported as `tool_calls`.
|
|
188
|
+
const reason = finishReason(data.done_reason);
|
|
189
|
+
const message = {
|
|
190
|
+
role: msg?.role || 'assistant',
|
|
191
|
+
content: msg?.content ?? '',
|
|
192
|
+
...(msg?.thinking ? { reasoning_content: msg.thinking } : {}),
|
|
193
|
+
...(toolCalls ? { tool_calls: toolCalls } : {})
|
|
194
|
+
};
|
|
101
195
|
return {
|
|
102
196
|
body: {
|
|
103
197
|
id: `chatcmpl-${Date.now()}`,
|
|
104
198
|
object: 'chat.completion',
|
|
105
199
|
choices: [{
|
|
106
|
-
message
|
|
107
|
-
finish_reason: 'stop',
|
|
200
|
+
message,
|
|
201
|
+
finish_reason: toolCalls && reason === 'stop' ? 'tool_calls' : reason,
|
|
108
202
|
index: 0
|
|
109
203
|
}],
|
|
110
204
|
usage
|
|
@@ -139,10 +233,40 @@ export function transformChatResponse(data, provider) {
|
|
|
139
233
|
const usage = (data.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 });
|
|
140
234
|
return { body: data, usage };
|
|
141
235
|
}
|
|
236
|
+
/**
|
|
237
|
+
* Ollama's tool calls in the OpenAI shape a harness reads: `arguments` as a JSON
|
|
238
|
+
* string, a `type`, and an `id` (Ollama gives none; the harness echoes the id
|
|
239
|
+
* back on the tool result, so any stable per-response id works).
|
|
240
|
+
*/
|
|
241
|
+
function openAiToolCalls(calls) {
|
|
242
|
+
if (!Array.isArray(calls) || calls.length === 0)
|
|
243
|
+
return undefined;
|
|
244
|
+
return calls.map((call, index) => {
|
|
245
|
+
const args = call.function?.arguments;
|
|
246
|
+
return {
|
|
247
|
+
id: call.id || `call_${index}`,
|
|
248
|
+
type: 'function',
|
|
249
|
+
function: {
|
|
250
|
+
name: call.function?.name ?? '',
|
|
251
|
+
arguments: typeof args === 'string' ? args : JSON.stringify(args ?? {})
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
function finishReason(doneReason) {
|
|
257
|
+
if (doneReason === 'length' || doneReason === 'max_tokens')
|
|
258
|
+
return 'length';
|
|
259
|
+
return 'stop';
|
|
260
|
+
}
|
|
142
261
|
export function transformEmbedResponse(data, provider) {
|
|
143
262
|
if (provider.type === 'ollama') {
|
|
144
|
-
const raw = (data.embeddings
|
|
145
|
-
const embeddings = Array.isArray(raw[0]) ? raw : [raw];
|
|
263
|
+
const raw = (data.embeddings ?? data.embedding);
|
|
264
|
+
const embeddings = (Array.isArray(raw) && Array.isArray(raw[0]) ? raw : [raw]);
|
|
265
|
+
// An answer with no vector in it is not an embedding of nothing: passing it
|
|
266
|
+
// on would hand the caller one empty vector to store.
|
|
267
|
+
if (!Array.isArray(raw) || raw.length === 0 || embeddings.some((e) => !Array.isArray(e) || e.length === 0)) {
|
|
268
|
+
throw new Error(`ollama: the embed response carries no embedding${typeof data.error === 'string' ? ` (${data.error})` : ''}`);
|
|
269
|
+
}
|
|
146
270
|
// Ollama reports the prompt tokens of an embed as `prompt_eval_count`.
|
|
147
271
|
const promptTokens = data.prompt_eval_count || 0;
|
|
148
272
|
const usage = { prompt_tokens: promptTokens, completion_tokens: 0, total_tokens: promptTokens };
|
package/index.d.ts
CHANGED
|
@@ -21,8 +21,10 @@
|
|
|
21
21
|
* app.listen(3001);
|
|
22
22
|
* ```
|
|
23
23
|
*/
|
|
24
|
+
export { BadRequestError } from './errors';
|
|
24
25
|
export { buildProviderHeaders, resolveProvider, resolveUpstreamUrl } from './providers';
|
|
25
26
|
export { createRouter } from './router';
|
|
26
27
|
export type { AgenticServerStartOptions } from './server';
|
|
27
28
|
export { createAgenticServer } from './server';
|
|
29
|
+
export { providerName, transformChatRequest, transformChatResponse, transformEmbedRequest, transformEmbedResponse, upstreamModel } from './transforms';
|
|
28
30
|
export type { AgenticServerOptions, InferenceAttribution, InferenceEntry, InferenceSink, ProviderConfig, ResolvedProvider, UsageResult } from './types';
|
package/index.js
CHANGED
|
@@ -23,7 +23,9 @@
|
|
|
23
23
|
* ```
|
|
24
24
|
*/
|
|
25
25
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
-
exports.createAgenticServer = exports.createRouter = exports.resolveUpstreamUrl = exports.resolveProvider = exports.buildProviderHeaders = void 0;
|
|
26
|
+
exports.upstreamModel = exports.transformEmbedResponse = exports.transformEmbedRequest = exports.transformChatResponse = exports.transformChatRequest = exports.providerName = exports.createAgenticServer = exports.createRouter = exports.resolveUpstreamUrl = exports.resolveProvider = exports.buildProviderHeaders = exports.BadRequestError = void 0;
|
|
27
|
+
var errors_1 = require("./errors");
|
|
28
|
+
Object.defineProperty(exports, "BadRequestError", { enumerable: true, get: function () { return errors_1.BadRequestError; } });
|
|
27
29
|
var providers_1 = require("./providers");
|
|
28
30
|
Object.defineProperty(exports, "buildProviderHeaders", { enumerable: true, get: function () { return providers_1.buildProviderHeaders; } });
|
|
29
31
|
Object.defineProperty(exports, "resolveProvider", { enumerable: true, get: function () { return providers_1.resolveProvider; } });
|
|
@@ -32,3 +34,10 @@ var router_1 = require("./router");
|
|
|
32
34
|
Object.defineProperty(exports, "createRouter", { enumerable: true, get: function () { return router_1.createRouter; } });
|
|
33
35
|
var server_1 = require("./server");
|
|
34
36
|
Object.defineProperty(exports, "createAgenticServer", { enumerable: true, get: function () { return server_1.createAgenticServer; } });
|
|
37
|
+
var transforms_1 = require("./transforms");
|
|
38
|
+
Object.defineProperty(exports, "providerName", { enumerable: true, get: function () { return transforms_1.providerName; } });
|
|
39
|
+
Object.defineProperty(exports, "transformChatRequest", { enumerable: true, get: function () { return transforms_1.transformChatRequest; } });
|
|
40
|
+
Object.defineProperty(exports, "transformChatResponse", { enumerable: true, get: function () { return transforms_1.transformChatResponse; } });
|
|
41
|
+
Object.defineProperty(exports, "transformEmbedRequest", { enumerable: true, get: function () { return transforms_1.transformEmbedRequest; } });
|
|
42
|
+
Object.defineProperty(exports, "transformEmbedResponse", { enumerable: true, get: function () { return transforms_1.transformEmbedResponse; } });
|
|
43
|
+
Object.defineProperty(exports, "upstreamModel", { enumerable: true, get: function () { return transforms_1.upstreamModel; } });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentic-server",
|
|
3
|
-
"version": "0.30.
|
|
3
|
+
"version": "0.30.2",
|
|
4
4
|
"description": "Standalone OpenAI-compatible LLM gateway — multi-provider proxy with pluggable inference metering",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"module": "esm/index.js",
|
|
@@ -51,5 +51,5 @@
|
|
|
51
51
|
"metering",
|
|
52
52
|
"constructive"
|
|
53
53
|
],
|
|
54
|
-
"gitHead": "
|
|
54
|
+
"gitHead": "1dceb60e5be9ff31a9455f48a8a50399f0b9262c"
|
|
55
55
|
}
|
package/providers.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { AgenticServerOptions, ResolvedProvider } from './types';
|
|
2
2
|
/**
|
|
3
3
|
* Resolve which provider to use for a given request.
|
|
4
|
-
* Priority:
|
|
4
|
+
* Priority: explicit provider header → `name/model` prefix → known model
|
|
5
|
+
* families → the first configured provider.
|
|
5
6
|
*/
|
|
6
7
|
export declare function resolveProvider(options: AgenticServerOptions, requestModel?: string, requestProvider?: string): ResolvedProvider;
|
|
7
8
|
export declare function resolveUpstreamUrl(provider: ResolvedProvider, path: string): string;
|
package/providers.js
CHANGED
|
@@ -3,43 +3,58 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.resolveProvider = resolveProvider;
|
|
4
4
|
exports.resolveUpstreamUrl = resolveUpstreamUrl;
|
|
5
5
|
exports.buildProviderHeaders = buildProviderHeaders;
|
|
6
|
+
const errors_1 = require("./errors");
|
|
7
|
+
const transforms_1 = require("./transforms");
|
|
8
|
+
/**
|
|
9
|
+
* Open-weights families Ollama serves. `gpt-oss` is listed because the
|
|
10
|
+
* `gpt` prefix would otherwise read as OpenAI's hosted models.
|
|
11
|
+
*/
|
|
12
|
+
const OLLAMA_MODEL_PREFIXES = ['gpt-oss', 'llama', 'mistral', 'gemma', 'nomic', 'qwen', 'glm'];
|
|
13
|
+
const startsWithAny = (model, prefixes) => prefixes.some((prefix) => model.startsWith(prefix));
|
|
14
|
+
/**
|
|
15
|
+
* The entry a request addresses: by registry name first, so two providers of
|
|
16
|
+
* one dialect are both reachable, then by dialect for an entry with no name of
|
|
17
|
+
* its own.
|
|
18
|
+
*/
|
|
19
|
+
const findNamed = (providers, name) => providers.find((p) => (0, transforms_1.providerName)(p) === name) ?? providers.find((p) => p.type === name);
|
|
6
20
|
/**
|
|
7
21
|
* Resolve which provider to use for a given request.
|
|
8
|
-
* Priority:
|
|
22
|
+
* Priority: explicit provider header → `name/model` prefix → known model
|
|
23
|
+
* families → the first configured provider.
|
|
9
24
|
*/
|
|
10
25
|
function resolveProvider(options, requestModel, requestProvider) {
|
|
11
26
|
const providers = options.providers || [];
|
|
12
27
|
if (providers.length > 0) {
|
|
13
28
|
if (requestProvider) {
|
|
14
|
-
const match = providers
|
|
29
|
+
const match = findNamed(providers, requestProvider);
|
|
15
30
|
if (match)
|
|
16
31
|
return match;
|
|
32
|
+
// A request pinned to a provider that is not registered must not drift
|
|
33
|
+
// to whichever entry a heuristic picks.
|
|
34
|
+
throw new errors_1.BadRequestError(`unknown provider '${requestProvider}'; registered: ${providers.map(transforms_1.providerName).join(', ')}`);
|
|
17
35
|
}
|
|
18
|
-
// Route by model prefix: "anthropic/claude-3" →
|
|
36
|
+
// Route by model prefix: "anthropic/claude-3" → the provider named anthropic
|
|
19
37
|
if (requestModel && requestModel.includes('/')) {
|
|
20
|
-
const prefix = requestModel.split('/')
|
|
21
|
-
const match = providers
|
|
38
|
+
const [prefix, ...rest] = requestModel.split('/');
|
|
39
|
+
const match = findNamed(providers, prefix);
|
|
22
40
|
if (match) {
|
|
23
|
-
return { ...match, defaultModel:
|
|
41
|
+
return { ...match, defaultModel: rest.join('/') };
|
|
24
42
|
}
|
|
25
43
|
}
|
|
26
|
-
// Route by known model
|
|
44
|
+
// Route by known model families
|
|
27
45
|
if (requestModel) {
|
|
28
46
|
if (requestModel.startsWith('claude')) {
|
|
29
47
|
const match = providers.find((p) => p.type === 'anthropic');
|
|
30
48
|
if (match)
|
|
31
49
|
return match;
|
|
32
50
|
}
|
|
33
|
-
if (
|
|
34
|
-
const match = providers.find((p) => p.type === '
|
|
51
|
+
if (startsWithAny(requestModel, OLLAMA_MODEL_PREFIXES)) {
|
|
52
|
+
const match = providers.find((p) => p.type === 'ollama');
|
|
35
53
|
if (match)
|
|
36
54
|
return match;
|
|
37
55
|
}
|
|
38
|
-
if (requestModel.startsWith('
|
|
39
|
-
|
|
40
|
-
requestModel.startsWith('gemma') ||
|
|
41
|
-
requestModel.startsWith('nomic')) {
|
|
42
|
-
const match = providers.find((p) => p.type === 'ollama');
|
|
56
|
+
if (requestModel.startsWith('gpt') || requestModel.startsWith('o1') || requestModel.startsWith('o3')) {
|
|
57
|
+
const match = providers.find((p) => p.type === 'openai');
|
|
43
58
|
if (match)
|
|
44
59
|
return match;
|
|
45
60
|
}
|
|
@@ -47,8 +62,12 @@ function resolveProvider(options, requestModel, requestProvider) {
|
|
|
47
62
|
return providers[0];
|
|
48
63
|
}
|
|
49
64
|
// Single-provider mode (default: ollama for local dev)
|
|
65
|
+
const type = options.providerType || 'ollama';
|
|
66
|
+
if (requestProvider && requestProvider !== type) {
|
|
67
|
+
throw new errors_1.BadRequestError(`unknown provider '${requestProvider}'; registered: ${type}`);
|
|
68
|
+
}
|
|
50
69
|
return {
|
|
51
|
-
type
|
|
70
|
+
type,
|
|
52
71
|
baseUrl: options.providerBaseUrl || 'http://localhost:11434',
|
|
53
72
|
apiKey: options.providerApiKey,
|
|
54
73
|
defaultModel: options.defaultModel
|
package/router.js
CHANGED
|
@@ -14,10 +14,32 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
14
14
|
exports.createRouter = exports.readAttribution = void 0;
|
|
15
15
|
const logger_1 = require("@pgpmjs/logger");
|
|
16
16
|
const express_1 = require("express");
|
|
17
|
+
const errors_1 = require("./errors");
|
|
17
18
|
const providers_1 = require("./providers");
|
|
18
19
|
const streaming_1 = require("./streaming");
|
|
19
20
|
const transforms_1 = require("./transforms");
|
|
20
21
|
const log = new logger_1.Logger('agentic-server');
|
|
22
|
+
/**
|
|
23
|
+
* Answer a request the gateway rejects itself — before any upstream call —
|
|
24
|
+
* with `400`, or report that `err` was something else. A client mistake must
|
|
25
|
+
* not be metered or reported as a provider failure.
|
|
26
|
+
*/
|
|
27
|
+
function rejectBadRequest(res, err) {
|
|
28
|
+
if (!(err instanceof errors_1.BadRequestError))
|
|
29
|
+
return false;
|
|
30
|
+
res.status(err.status).json({ error: { message: err.message } });
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
function selectProvider(options, req, res) {
|
|
34
|
+
try {
|
|
35
|
+
return (0, providers_1.resolveProvider)(options, req.body?.model, req.get('X-LLM-Provider'));
|
|
36
|
+
}
|
|
37
|
+
catch (err) {
|
|
38
|
+
if (rejectBadRequest(res, err))
|
|
39
|
+
return undefined;
|
|
40
|
+
throw err;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
21
43
|
/** How long an upstream reason may be before it stops being a message. */
|
|
22
44
|
const UPSTREAM_REASON_LIMIT = 300;
|
|
23
45
|
/**
|
|
@@ -83,9 +105,10 @@ const createRouter = (options) => {
|
|
|
83
105
|
}
|
|
84
106
|
const attribution = (0, exports.readAttribution)(req);
|
|
85
107
|
const { entityId } = attribution;
|
|
86
|
-
const requestProvider = req.get('X-LLM-Provider');
|
|
87
108
|
const startTime = process.hrtime.bigint();
|
|
88
|
-
const provider = (
|
|
109
|
+
const provider = selectProvider(options, req, res);
|
|
110
|
+
if (!provider)
|
|
111
|
+
return;
|
|
89
112
|
log.info('chat/completions', {
|
|
90
113
|
databaseId,
|
|
91
114
|
entityId,
|
|
@@ -203,6 +226,8 @@ const createRouter = (options) => {
|
|
|
203
226
|
res.json(responseBody);
|
|
204
227
|
}
|
|
205
228
|
catch (err) {
|
|
229
|
+
if (!res.headersSent && rejectBadRequest(res, err))
|
|
230
|
+
return;
|
|
206
231
|
const latencyMs = Number(process.hrtime.bigint() - startTime) / 1e6;
|
|
207
232
|
log.error('chat/completions error', err);
|
|
208
233
|
if (sink) {
|
|
@@ -238,9 +263,10 @@ const createRouter = (options) => {
|
|
|
238
263
|
}
|
|
239
264
|
const attribution = (0, exports.readAttribution)(req);
|
|
240
265
|
const { entityId } = attribution;
|
|
241
|
-
const requestProvider = req.get('X-LLM-Provider');
|
|
242
266
|
const startTime = process.hrtime.bigint();
|
|
243
|
-
const provider = (
|
|
267
|
+
const provider = selectProvider(options, req, res);
|
|
268
|
+
if (!provider)
|
|
269
|
+
return;
|
|
244
270
|
log.info('embeddings', { databaseId, entityId, provider: provider.type, model: req.body?.model });
|
|
245
271
|
try {
|
|
246
272
|
const upstreamUrl = (0, providers_1.resolveUpstreamUrl)(provider, '/v1/embeddings');
|
|
@@ -294,6 +320,8 @@ const createRouter = (options) => {
|
|
|
294
320
|
res.json(responseBody);
|
|
295
321
|
}
|
|
296
322
|
catch (err) {
|
|
323
|
+
if (rejectBadRequest(res, err))
|
|
324
|
+
return;
|
|
297
325
|
const latencyMs = Number(process.hrtime.bigint() - startTime) / 1e6;
|
|
298
326
|
log.error('embeddings error', err);
|
|
299
327
|
if (sink) {
|
|
@@ -353,6 +381,7 @@ const createRouter = (options) => {
|
|
|
353
381
|
}];
|
|
354
382
|
res.json({
|
|
355
383
|
providers: providers.map((p) => ({
|
|
384
|
+
name: (0, transforms_1.providerName)(p),
|
|
356
385
|
type: p.type,
|
|
357
386
|
defaultModel: p.defaultModel
|
|
358
387
|
}))
|
package/transforms.d.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
import type { ResolvedProvider, UsageResult } from './types';
|
|
2
|
+
/** The name a request routes with: the registry name, else the dialect. */
|
|
3
|
+
export declare const providerName: (provider: ResolvedProvider) => string;
|
|
4
|
+
/**
|
|
5
|
+
* Strip the routing prefix a client uses to pick a provider (`anthropic/claude-…`,
|
|
6
|
+
* `host-ollama/qwen3`), which the upstream itself does not know.
|
|
7
|
+
*/
|
|
8
|
+
export declare function upstreamModel(provider: ResolvedProvider, model: unknown): string | undefined;
|
|
2
9
|
export declare function transformChatRequest(provider: ResolvedProvider, body: Record<string, unknown>): Record<string, unknown>;
|
|
3
10
|
export declare function transformEmbedRequest(provider: ResolvedProvider, body: Record<string, unknown>): Record<string, unknown>;
|
|
4
11
|
export declare function transformChatResponse(data: Record<string, unknown>, provider: ResolvedProvider): {
|
package/transforms.js
CHANGED
|
@@ -1,9 +1,28 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.providerName = void 0;
|
|
4
|
+
exports.upstreamModel = upstreamModel;
|
|
3
5
|
exports.transformChatRequest = transformChatRequest;
|
|
4
6
|
exports.transformEmbedRequest = transformEmbedRequest;
|
|
5
7
|
exports.transformChatResponse = transformChatResponse;
|
|
6
8
|
exports.transformEmbedResponse = transformEmbedResponse;
|
|
9
|
+
const errors_1 = require("./errors");
|
|
10
|
+
/** The name a request routes with: the registry name, else the dialect. */
|
|
11
|
+
const providerName = (provider) => provider.name ?? provider.type;
|
|
12
|
+
exports.providerName = providerName;
|
|
13
|
+
/**
|
|
14
|
+
* Strip the routing prefix a client uses to pick a provider (`anthropic/claude-…`,
|
|
15
|
+
* `host-ollama/qwen3`), which the upstream itself does not know.
|
|
16
|
+
*/
|
|
17
|
+
function upstreamModel(provider, model) {
|
|
18
|
+
const requested = typeof model === 'string' && model ? model : provider.defaultModel;
|
|
19
|
+
if (!requested)
|
|
20
|
+
return undefined;
|
|
21
|
+
const [prefix, ...rest] = requested.split('/');
|
|
22
|
+
if (rest.length === 0)
|
|
23
|
+
return requested;
|
|
24
|
+
return prefix === (0, exports.providerName)(provider) || prefix === provider.type ? rest.join('/') : requested;
|
|
25
|
+
}
|
|
7
26
|
/**
|
|
8
27
|
* Flatten OpenAI content parts into the single string Ollama's chat api takes.
|
|
9
28
|
*
|
|
@@ -17,7 +36,8 @@ exports.transformEmbedResponse = transformEmbedResponse;
|
|
|
17
36
|
function flattenContentParts(messages) {
|
|
18
37
|
if (!Array.isArray(messages))
|
|
19
38
|
return messages;
|
|
20
|
-
return messages.map((
|
|
39
|
+
return messages.map((original) => {
|
|
40
|
+
const message = ollamaToolCalls(original);
|
|
21
41
|
if (!Array.isArray(message.content))
|
|
22
42
|
return message;
|
|
23
43
|
const text = [];
|
|
@@ -30,16 +50,16 @@ function flattenContentParts(messages) {
|
|
|
30
50
|
if (part.type === 'image_url') {
|
|
31
51
|
const url = part.image_url?.url;
|
|
32
52
|
if (!url)
|
|
33
|
-
throw new
|
|
53
|
+
throw new errors_1.BadRequestError('ollama: an image_url content part carries no url');
|
|
34
54
|
// Ollama takes base64 bytes, never a fetchable url.
|
|
35
55
|
const base64 = /^data:[^;]*;base64,(.*)$/.exec(url)?.[1];
|
|
36
56
|
if (!base64) {
|
|
37
|
-
throw new
|
|
57
|
+
throw new errors_1.BadRequestError('ollama: an image content part must be a base64 data url');
|
|
38
58
|
}
|
|
39
59
|
images.push(base64);
|
|
40
60
|
continue;
|
|
41
61
|
}
|
|
42
|
-
throw new
|
|
62
|
+
throw new errors_1.BadRequestError(`ollama: unsupported content part type '${part.type}'`);
|
|
43
63
|
}
|
|
44
64
|
return {
|
|
45
65
|
...message,
|
|
@@ -48,24 +68,74 @@ function flattenContentParts(messages) {
|
|
|
48
68
|
};
|
|
49
69
|
});
|
|
50
70
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
71
|
+
/**
|
|
72
|
+
* An earlier assistant turn replays its tool calls with `arguments` as the JSON
|
|
73
|
+
* string OpenAI returns them in; Ollama's struct wants the object, and answers
|
|
74
|
+
* the string with an unmarshal error.
|
|
75
|
+
*/
|
|
76
|
+
function ollamaToolCalls(message) {
|
|
77
|
+
if (!Array.isArray(message.tool_calls))
|
|
78
|
+
return message;
|
|
79
|
+
return {
|
|
80
|
+
...message,
|
|
81
|
+
tool_calls: message.tool_calls.map((call) => {
|
|
82
|
+
const args = call.function?.arguments;
|
|
83
|
+
if (typeof args !== 'string')
|
|
84
|
+
return call;
|
|
85
|
+
let parsed;
|
|
86
|
+
try {
|
|
87
|
+
parsed = JSON.parse(args);
|
|
88
|
+
}
|
|
89
|
+
catch (err) {
|
|
90
|
+
throw new errors_1.BadRequestError(`ollama: tool call '${call.function?.name ?? ''}' carries arguments that are not JSON: ${err.message}`);
|
|
91
|
+
}
|
|
92
|
+
return { ...call, function: { ...call.function, arguments: parsed } };
|
|
93
|
+
})
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Ollama's `format` from an OpenAI `response_format`: `json_object` is the
|
|
98
|
+
* `'json'` mode, `json_schema` is the schema itself. A native `format` wins
|
|
99
|
+
* when a caller already speaks the dialect.
|
|
100
|
+
*/
|
|
101
|
+
function ollamaFormat(body) {
|
|
102
|
+
if (body.format !== undefined)
|
|
103
|
+
return body.format;
|
|
104
|
+
const responseFormat = body.response_format;
|
|
105
|
+
if (!responseFormat || typeof responseFormat !== 'object')
|
|
106
|
+
return undefined;
|
|
107
|
+
if (responseFormat.type === 'json_object')
|
|
108
|
+
return 'json';
|
|
109
|
+
if (responseFormat.type === 'json_schema') {
|
|
110
|
+
if (responseFormat.json_schema?.schema === undefined) {
|
|
111
|
+
throw new errors_1.BadRequestError('ollama: response_format json_schema carries no schema');
|
|
57
112
|
}
|
|
113
|
+
return responseFormat.json_schema.schema;
|
|
58
114
|
}
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
function transformChatRequest(provider, body) {
|
|
118
|
+
const model = upstreamModel(provider, body.model);
|
|
59
119
|
if (provider.type === 'ollama') {
|
|
60
|
-
// Ollama takes sampling settings under `options`; `max_tokens`
|
|
120
|
+
// Ollama takes sampling and runtime settings under `options`; `max_tokens`
|
|
121
|
+
// is `num_predict`, and `num_ctx` (the context window the model is loaded
|
|
122
|
+
// with) has no OpenAI spelling, so it rides at the top level and moves here.
|
|
123
|
+
const clientOptions = (body.options && typeof body.options === 'object' ? body.options : {});
|
|
61
124
|
const options = {
|
|
125
|
+
...clientOptions,
|
|
62
126
|
...(body.temperature !== undefined && { temperature: body.temperature }),
|
|
63
|
-
...(body.max_tokens !== undefined && { num_predict: body.max_tokens })
|
|
127
|
+
...(body.max_tokens !== undefined && { num_predict: body.max_tokens }),
|
|
128
|
+
...(body.num_ctx !== undefined && { num_ctx: body.num_ctx })
|
|
64
129
|
};
|
|
130
|
+
const format = ollamaFormat(body);
|
|
65
131
|
return {
|
|
66
132
|
model: model || 'llama3',
|
|
67
133
|
messages: flattenContentParts(body.messages),
|
|
68
134
|
stream: false,
|
|
135
|
+
...(body.tools !== undefined && { tools: body.tools }),
|
|
136
|
+
...(format !== undefined && { format }),
|
|
137
|
+
...(body.think !== undefined && { think: body.think }),
|
|
138
|
+
...(body.keep_alive !== undefined && { keep_alive: body.keep_alive }),
|
|
69
139
|
...(Object.keys(options).length > 0 && { options })
|
|
70
140
|
};
|
|
71
141
|
}
|
|
@@ -84,12 +154,29 @@ function transformChatRequest(provider, body) {
|
|
|
84
154
|
// OpenAI-compatible (default)
|
|
85
155
|
return { ...body, model: model || 'gpt-4o' };
|
|
86
156
|
}
|
|
157
|
+
// Anchored, so text that merely mentions a data url stays text. A media type
|
|
158
|
+
// may carry parameters before the encoding (`image/svg+xml;charset=utf-8;base64,`)
|
|
159
|
+
// and both are case-insensitive (RFC 2397).
|
|
160
|
+
const IMAGE_DATA_URL = /^data:image\/[^;,]+(?:;[^;,]+)*;base64,/i;
|
|
161
|
+
/**
|
|
162
|
+
* One embed input in Ollama's shape. An image arrives as a base64 `data:` url,
|
|
163
|
+
* the way OpenAI-style clients carry bytes; Ollama's multimodal embed takes it
|
|
164
|
+
* as `{ image: <base64> }`, and embeds the same url left as a string as text —
|
|
165
|
+
* a vector of the right length for the wrong thing, with no error.
|
|
166
|
+
*/
|
|
167
|
+
function ollamaEmbedInput(input) {
|
|
168
|
+
if (typeof input !== 'string')
|
|
169
|
+
return input;
|
|
170
|
+
const prefix = IMAGE_DATA_URL.exec(input)?.[0];
|
|
171
|
+
return prefix ? { image: input.slice(prefix.length) } : input;
|
|
172
|
+
}
|
|
87
173
|
function transformEmbedRequest(provider, body) {
|
|
88
|
-
const model = body.model
|
|
174
|
+
const model = upstreamModel(provider, body.model);
|
|
89
175
|
if (provider.type === 'ollama') {
|
|
90
176
|
return {
|
|
91
177
|
model: model || 'nomic-embed-text',
|
|
92
|
-
input: body.input
|
|
178
|
+
input: Array.isArray(body.input) ? body.input.map(ollamaEmbedInput) : ollamaEmbedInput(body.input),
|
|
179
|
+
...(body.dimensions !== undefined && { dimensions: body.dimensions })
|
|
93
180
|
};
|
|
94
181
|
}
|
|
95
182
|
return { ...body, model: model || 'text-embedding-3-small' };
|
|
@@ -104,13 +191,23 @@ function transformChatResponse(data, provider) {
|
|
|
104
191
|
completion_tokens: completionTokens,
|
|
105
192
|
total_tokens: promptTokens + completionTokens
|
|
106
193
|
};
|
|
194
|
+
const toolCalls = openAiToolCalls(msg?.tool_calls);
|
|
195
|
+
// A generation cut off by the token budget may hold half a tool call;
|
|
196
|
+
// only a completed turn is reported as `tool_calls`.
|
|
197
|
+
const reason = finishReason(data.done_reason);
|
|
198
|
+
const message = {
|
|
199
|
+
role: msg?.role || 'assistant',
|
|
200
|
+
content: msg?.content ?? '',
|
|
201
|
+
...(msg?.thinking ? { reasoning_content: msg.thinking } : {}),
|
|
202
|
+
...(toolCalls ? { tool_calls: toolCalls } : {})
|
|
203
|
+
};
|
|
107
204
|
return {
|
|
108
205
|
body: {
|
|
109
206
|
id: `chatcmpl-${Date.now()}`,
|
|
110
207
|
object: 'chat.completion',
|
|
111
208
|
choices: [{
|
|
112
|
-
message
|
|
113
|
-
finish_reason: 'stop',
|
|
209
|
+
message,
|
|
210
|
+
finish_reason: toolCalls && reason === 'stop' ? 'tool_calls' : reason,
|
|
114
211
|
index: 0
|
|
115
212
|
}],
|
|
116
213
|
usage
|
|
@@ -145,10 +242,40 @@ function transformChatResponse(data, provider) {
|
|
|
145
242
|
const usage = (data.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 });
|
|
146
243
|
return { body: data, usage };
|
|
147
244
|
}
|
|
245
|
+
/**
|
|
246
|
+
* Ollama's tool calls in the OpenAI shape a harness reads: `arguments` as a JSON
|
|
247
|
+
* string, a `type`, and an `id` (Ollama gives none; the harness echoes the id
|
|
248
|
+
* back on the tool result, so any stable per-response id works).
|
|
249
|
+
*/
|
|
250
|
+
function openAiToolCalls(calls) {
|
|
251
|
+
if (!Array.isArray(calls) || calls.length === 0)
|
|
252
|
+
return undefined;
|
|
253
|
+
return calls.map((call, index) => {
|
|
254
|
+
const args = call.function?.arguments;
|
|
255
|
+
return {
|
|
256
|
+
id: call.id || `call_${index}`,
|
|
257
|
+
type: 'function',
|
|
258
|
+
function: {
|
|
259
|
+
name: call.function?.name ?? '',
|
|
260
|
+
arguments: typeof args === 'string' ? args : JSON.stringify(args ?? {})
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
function finishReason(doneReason) {
|
|
266
|
+
if (doneReason === 'length' || doneReason === 'max_tokens')
|
|
267
|
+
return 'length';
|
|
268
|
+
return 'stop';
|
|
269
|
+
}
|
|
148
270
|
function transformEmbedResponse(data, provider) {
|
|
149
271
|
if (provider.type === 'ollama') {
|
|
150
|
-
const raw = (data.embeddings
|
|
151
|
-
const embeddings = Array.isArray(raw[0]) ? raw : [raw];
|
|
272
|
+
const raw = (data.embeddings ?? data.embedding);
|
|
273
|
+
const embeddings = (Array.isArray(raw) && Array.isArray(raw[0]) ? raw : [raw]);
|
|
274
|
+
// An answer with no vector in it is not an embedding of nothing: passing it
|
|
275
|
+
// on would hand the caller one empty vector to store.
|
|
276
|
+
if (!Array.isArray(raw) || raw.length === 0 || embeddings.some((e) => !Array.isArray(e) || e.length === 0)) {
|
|
277
|
+
throw new Error(`ollama: the embed response carries no embedding${typeof data.error === 'string' ? ` (${data.error})` : ''}`);
|
|
278
|
+
}
|
|
152
279
|
// Ollama reports the prompt tokens of an embed as `prompt_eval_count`.
|
|
153
280
|
const promptTokens = data.prompt_eval_count || 0;
|
|
154
281
|
const usage = { prompt_tokens: promptTokens, completion_tokens: 0, total_tokens: promptTokens };
|
package/types.d.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
export interface ProviderConfig {
|
|
2
|
+
/** Registry name a request addresses this entry by (`X-LLM-Provider`, a
|
|
3
|
+
* `name/model` prefix). Defaults to `type`, so a deployment with one entry
|
|
4
|
+
* per dialect needs no names. */
|
|
5
|
+
name?: string;
|
|
6
|
+
/** Dialect: 'openai' | 'anthropic' | 'ollama'. Chooses URL, auth and body shape. */
|
|
2
7
|
type: string;
|
|
3
8
|
baseUrl: string;
|
|
4
9
|
apiKey?: string;
|
|
@@ -30,6 +35,7 @@ export interface AgenticServerOptions {
|
|
|
30
35
|
isPublic?: boolean;
|
|
31
36
|
}
|
|
32
37
|
export interface ResolvedProvider {
|
|
38
|
+
name?: string;
|
|
33
39
|
type: string;
|
|
34
40
|
baseUrl: string;
|
|
35
41
|
apiKey?: string;
|