agentic-server 0.29.0 → 0.30.1
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 +24 -3
- 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 +124 -17
- 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 +127 -17
- 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`.
|
|
@@ -138,9 +158,10 @@ Install skills for AI coding agents:
|
|
|
138
158
|
# All platform skills (security, blueprints, codegen, billing, etc.)
|
|
139
159
|
npx skills add constructive-io/constructive-skills
|
|
140
160
|
|
|
141
|
-
# Individual repo skills (pgpm, testing, CLI, search, etc.)
|
|
142
|
-
npx skills add
|
|
143
|
-
npx skills add
|
|
161
|
+
# Individual repo skills (pgpm, safegres, testing, CLI, search, etc.)
|
|
162
|
+
npx skills add constructive-io/constructive --skill pgpm
|
|
163
|
+
npx skills add constructive-io/constructive --skill safegres
|
|
164
|
+
npx skills add constructive-io/constructive --skill constructive-testing
|
|
144
165
|
```
|
|
145
166
|
|
|
146
167
|
## Credits
|
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,22 +59,75 @@ 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') {
|
|
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 : {});
|
|
115
|
+
const options = {
|
|
116
|
+
...clientOptions,
|
|
117
|
+
...(body.temperature !== undefined && { temperature: body.temperature }),
|
|
118
|
+
...(body.max_tokens !== undefined && { num_predict: body.max_tokens }),
|
|
119
|
+
...(body.num_ctx !== undefined && { num_ctx: body.num_ctx })
|
|
120
|
+
};
|
|
121
|
+
const format = ollamaFormat(body);
|
|
54
122
|
return {
|
|
55
123
|
model: model || 'llama3',
|
|
56
124
|
messages: flattenContentParts(body.messages),
|
|
57
125
|
stream: false,
|
|
58
|
-
...(body.
|
|
59
|
-
|
|
60
|
-
})
|
|
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 }),
|
|
130
|
+
...(Object.keys(options).length > 0 && { options })
|
|
61
131
|
};
|
|
62
132
|
}
|
|
63
133
|
if (provider.type === 'anthropic') {
|
|
@@ -76,7 +146,7 @@ export function transformChatRequest(provider, body) {
|
|
|
76
146
|
return { ...body, model: model || 'gpt-4o' };
|
|
77
147
|
}
|
|
78
148
|
export function transformEmbedRequest(provider, body) {
|
|
79
|
-
const model = body.model
|
|
149
|
+
const model = upstreamModel(provider, body.model);
|
|
80
150
|
if (provider.type === 'ollama') {
|
|
81
151
|
return {
|
|
82
152
|
model: model || 'nomic-embed-text',
|
|
@@ -95,13 +165,23 @@ export function transformChatResponse(data, provider) {
|
|
|
95
165
|
completion_tokens: completionTokens,
|
|
96
166
|
total_tokens: promptTokens + completionTokens
|
|
97
167
|
};
|
|
168
|
+
const toolCalls = openAiToolCalls(msg?.tool_calls);
|
|
169
|
+
// A generation cut off by the token budget may hold half a tool call;
|
|
170
|
+
// only a completed turn is reported as `tool_calls`.
|
|
171
|
+
const reason = finishReason(data.done_reason);
|
|
172
|
+
const message = {
|
|
173
|
+
role: msg?.role || 'assistant',
|
|
174
|
+
content: msg?.content ?? '',
|
|
175
|
+
...(msg?.thinking ? { reasoning_content: msg.thinking } : {}),
|
|
176
|
+
...(toolCalls ? { tool_calls: toolCalls } : {})
|
|
177
|
+
};
|
|
98
178
|
return {
|
|
99
179
|
body: {
|
|
100
180
|
id: `chatcmpl-${Date.now()}`,
|
|
101
181
|
object: 'chat.completion',
|
|
102
182
|
choices: [{
|
|
103
|
-
message
|
|
104
|
-
finish_reason: 'stop',
|
|
183
|
+
message,
|
|
184
|
+
finish_reason: toolCalls && reason === 'stop' ? 'tool_calls' : reason,
|
|
105
185
|
index: 0
|
|
106
186
|
}],
|
|
107
187
|
usage
|
|
@@ -136,11 +216,38 @@ export function transformChatResponse(data, provider) {
|
|
|
136
216
|
const usage = (data.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 });
|
|
137
217
|
return { body: data, usage };
|
|
138
218
|
}
|
|
219
|
+
/**
|
|
220
|
+
* Ollama's tool calls in the OpenAI shape a harness reads: `arguments` as a JSON
|
|
221
|
+
* string, a `type`, and an `id` (Ollama gives none; the harness echoes the id
|
|
222
|
+
* back on the tool result, so any stable per-response id works).
|
|
223
|
+
*/
|
|
224
|
+
function openAiToolCalls(calls) {
|
|
225
|
+
if (!Array.isArray(calls) || calls.length === 0)
|
|
226
|
+
return undefined;
|
|
227
|
+
return calls.map((call, index) => {
|
|
228
|
+
const args = call.function?.arguments;
|
|
229
|
+
return {
|
|
230
|
+
id: call.id || `call_${index}`,
|
|
231
|
+
type: 'function',
|
|
232
|
+
function: {
|
|
233
|
+
name: call.function?.name ?? '',
|
|
234
|
+
arguments: typeof args === 'string' ? args : JSON.stringify(args ?? {})
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
function finishReason(doneReason) {
|
|
240
|
+
if (doneReason === 'length' || doneReason === 'max_tokens')
|
|
241
|
+
return 'length';
|
|
242
|
+
return 'stop';
|
|
243
|
+
}
|
|
139
244
|
export function transformEmbedResponse(data, provider) {
|
|
140
245
|
if (provider.type === 'ollama') {
|
|
141
246
|
const raw = (data.embeddings || data.embedding || []);
|
|
142
247
|
const embeddings = Array.isArray(raw[0]) ? raw : [raw];
|
|
143
|
-
|
|
248
|
+
// Ollama reports the prompt tokens of an embed as `prompt_eval_count`.
|
|
249
|
+
const promptTokens = data.prompt_eval_count || 0;
|
|
250
|
+
const usage = { prompt_tokens: promptTokens, completion_tokens: 0, total_tokens: promptTokens };
|
|
144
251
|
return {
|
|
145
252
|
body: {
|
|
146
253
|
object: 'list',
|
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.
|
|
3
|
+
"version": "0.30.1",
|
|
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": "eb44afc5ecdfa6e91aeb7ad8e24c9021b97ec027"
|
|
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,22 +68,75 @@ 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') {
|
|
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 : {});
|
|
124
|
+
const options = {
|
|
125
|
+
...clientOptions,
|
|
126
|
+
...(body.temperature !== undefined && { temperature: body.temperature }),
|
|
127
|
+
...(body.max_tokens !== undefined && { num_predict: body.max_tokens }),
|
|
128
|
+
...(body.num_ctx !== undefined && { num_ctx: body.num_ctx })
|
|
129
|
+
};
|
|
130
|
+
const format = ollamaFormat(body);
|
|
60
131
|
return {
|
|
61
132
|
model: model || 'llama3',
|
|
62
133
|
messages: flattenContentParts(body.messages),
|
|
63
134
|
stream: false,
|
|
64
|
-
...(body.
|
|
65
|
-
|
|
66
|
-
})
|
|
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 }),
|
|
139
|
+
...(Object.keys(options).length > 0 && { options })
|
|
67
140
|
};
|
|
68
141
|
}
|
|
69
142
|
if (provider.type === 'anthropic') {
|
|
@@ -82,7 +155,7 @@ function transformChatRequest(provider, body) {
|
|
|
82
155
|
return { ...body, model: model || 'gpt-4o' };
|
|
83
156
|
}
|
|
84
157
|
function transformEmbedRequest(provider, body) {
|
|
85
|
-
const model = body.model
|
|
158
|
+
const model = upstreamModel(provider, body.model);
|
|
86
159
|
if (provider.type === 'ollama') {
|
|
87
160
|
return {
|
|
88
161
|
model: model || 'nomic-embed-text',
|
|
@@ -101,13 +174,23 @@ function transformChatResponse(data, provider) {
|
|
|
101
174
|
completion_tokens: completionTokens,
|
|
102
175
|
total_tokens: promptTokens + completionTokens
|
|
103
176
|
};
|
|
177
|
+
const toolCalls = openAiToolCalls(msg?.tool_calls);
|
|
178
|
+
// A generation cut off by the token budget may hold half a tool call;
|
|
179
|
+
// only a completed turn is reported as `tool_calls`.
|
|
180
|
+
const reason = finishReason(data.done_reason);
|
|
181
|
+
const message = {
|
|
182
|
+
role: msg?.role || 'assistant',
|
|
183
|
+
content: msg?.content ?? '',
|
|
184
|
+
...(msg?.thinking ? { reasoning_content: msg.thinking } : {}),
|
|
185
|
+
...(toolCalls ? { tool_calls: toolCalls } : {})
|
|
186
|
+
};
|
|
104
187
|
return {
|
|
105
188
|
body: {
|
|
106
189
|
id: `chatcmpl-${Date.now()}`,
|
|
107
190
|
object: 'chat.completion',
|
|
108
191
|
choices: [{
|
|
109
|
-
message
|
|
110
|
-
finish_reason: 'stop',
|
|
192
|
+
message,
|
|
193
|
+
finish_reason: toolCalls && reason === 'stop' ? 'tool_calls' : reason,
|
|
111
194
|
index: 0
|
|
112
195
|
}],
|
|
113
196
|
usage
|
|
@@ -142,11 +225,38 @@ function transformChatResponse(data, provider) {
|
|
|
142
225
|
const usage = (data.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 });
|
|
143
226
|
return { body: data, usage };
|
|
144
227
|
}
|
|
228
|
+
/**
|
|
229
|
+
* Ollama's tool calls in the OpenAI shape a harness reads: `arguments` as a JSON
|
|
230
|
+
* string, a `type`, and an `id` (Ollama gives none; the harness echoes the id
|
|
231
|
+
* back on the tool result, so any stable per-response id works).
|
|
232
|
+
*/
|
|
233
|
+
function openAiToolCalls(calls) {
|
|
234
|
+
if (!Array.isArray(calls) || calls.length === 0)
|
|
235
|
+
return undefined;
|
|
236
|
+
return calls.map((call, index) => {
|
|
237
|
+
const args = call.function?.arguments;
|
|
238
|
+
return {
|
|
239
|
+
id: call.id || `call_${index}`,
|
|
240
|
+
type: 'function',
|
|
241
|
+
function: {
|
|
242
|
+
name: call.function?.name ?? '',
|
|
243
|
+
arguments: typeof args === 'string' ? args : JSON.stringify(args ?? {})
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
function finishReason(doneReason) {
|
|
249
|
+
if (doneReason === 'length' || doneReason === 'max_tokens')
|
|
250
|
+
return 'length';
|
|
251
|
+
return 'stop';
|
|
252
|
+
}
|
|
145
253
|
function transformEmbedResponse(data, provider) {
|
|
146
254
|
if (provider.type === 'ollama') {
|
|
147
255
|
const raw = (data.embeddings || data.embedding || []);
|
|
148
256
|
const embeddings = Array.isArray(raw[0]) ? raw : [raw];
|
|
149
|
-
|
|
257
|
+
// Ollama reports the prompt tokens of an embed as `prompt_eval_count`.
|
|
258
|
+
const promptTokens = data.prompt_eval_count || 0;
|
|
259
|
+
const usage = { prompt_tokens: promptTokens, completion_tokens: 0, total_tokens: promptTokens };
|
|
150
260
|
return {
|
|
151
261
|
body: {
|
|
152
262
|
object: 'list',
|
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;
|