@axemere/gateway 0.2.1 → 1.0.3

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/dist/client.d.ts CHANGED
@@ -46,3 +46,5 @@ export declare class AiGatewayClient {
46
46
  }): Promise<AsyncIterable<StreamChunk>>;
47
47
  execute(params: ExecuteParams): Promise<ExecuteResponse | AsyncIterable<StreamChunk>>;
48
48
  }
49
+ export declare function translateAnthropicTools(tools: unknown): unknown;
50
+ export declare function translateGeminiTools(tools: unknown): unknown;
package/dist/client.js CHANGED
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AiGatewayClient = void 0;
4
+ exports.translateAnthropicTools = translateAnthropicTools;
5
+ exports.translateGeminiTools = translateGeminiTools;
6
+ const node_crypto_1 = require("node:crypto");
4
7
  const uuidv7_1 = require("uuidv7");
5
8
  const errors_1 = require("./errors");
6
9
  const providers_1 = require("./providers");
@@ -52,12 +55,21 @@ class AiGatewayClient {
52
55
  const target_path = route.path.replace("{model}", model);
53
56
  // Build provider_params: strip known SDK fields, pass remaining through.
54
57
  const { messages, provider: _p, model: _m, target_host: _th, workload_id: _wl, project_id: _pi, account_id: _ai, customer_id: _ci, labels: _lb, provider_api_key: _pak, delegation_token, stream, ...extra_params } = params;
55
- const provider_params = {
56
- model,
57
- messages,
58
- max_tokens: extra_params["max_tokens"] ?? 256,
59
- ...extra_params,
60
- };
58
+ let provider_params;
59
+ if (route.format === "anthropic") {
60
+ provider_params = buildAnthropicParams(model, messages, extra_params);
61
+ }
62
+ else if (route.format === "gemini") {
63
+ provider_params = buildGeminiParams(messages, extra_params);
64
+ }
65
+ else {
66
+ provider_params = {
67
+ model,
68
+ messages,
69
+ max_tokens: extra_params["max_tokens"] ?? 256,
70
+ ...extra_params,
71
+ };
72
+ }
61
73
  if (stream) {
62
74
  provider_params["stream"] = true;
63
75
  }
@@ -136,6 +148,204 @@ class AiGatewayClient {
136
148
  }
137
149
  }
138
150
  exports.AiGatewayClient = AiGatewayClient;
151
+ // Anthropic's Messages API rejects a "system"-role entry inside `messages` —
152
+ // it requires the system prompt lifted out into a separate top-level `system`
153
+ // field — and requires `max_tokens` to be present at all.
154
+ function buildAnthropicParams(model, messages, extra) {
155
+ const nonSystemMessages = messages.filter((m) => m.role !== "system");
156
+ const systemMessage = messages.find((m) => m.role === "system");
157
+ const params = {
158
+ model,
159
+ messages: nonSystemMessages,
160
+ max_tokens: extra["max_tokens"] ?? 256,
161
+ ...extra,
162
+ };
163
+ if (systemMessage && params["system"] === undefined) {
164
+ params["system"] = systemMessage.content;
165
+ }
166
+ if (params["tools"] !== undefined) {
167
+ params["tools"] = translateAnthropicTools(params["tools"]);
168
+ }
169
+ if (params["tool_choice"] !== undefined) {
170
+ params["tool_choice"] = translateAnthropicToolChoice(params["tool_choice"]);
171
+ }
172
+ return params;
173
+ }
174
+ // Converts OpenAI-shaped function tools into Anthropic's custom-tool shape.
175
+ // Anthropic's "type" field is a discriminator for its own built-in tools
176
+ // (bash_20250124, web_search_20250305, etc.) plus "custom" — it has no
177
+ // "type": "function" convention, and its schema field is "input_schema",
178
+ // not "parameters". A caller sending OpenAI-shaped tools gets a hard 400
179
+ // from Anthropic's real API today. Native Anthropic tool blocks (anything
180
+ // without "type": "function") pass through unchanged, so callers who
181
+ // already speak Anthropic's format directly aren't double-converted.
182
+ //
183
+ // Exported so @axemere/gateway-langchain can apply the identical
184
+ // translation instead of maintaining its own copy.
185
+ function translateAnthropicTools(tools) {
186
+ if (!Array.isArray(tools))
187
+ return tools;
188
+ return tools.map((tool) => {
189
+ if (!tool || typeof tool !== "object")
190
+ return tool;
191
+ const t = tool;
192
+ const fn = t["function"];
193
+ if (t["type"] !== "function" || !fn || typeof fn !== "object")
194
+ return tool;
195
+ const fnObj = fn;
196
+ const entry = { name: fnObj["name"] ?? "" };
197
+ if ("description" in fnObj)
198
+ entry["description"] = fnObj["description"];
199
+ if ("parameters" in fnObj)
200
+ entry["input_schema"] = fnObj["parameters"];
201
+ return entry;
202
+ });
203
+ }
204
+ // Converts OpenAI-shaped tool_choice into Anthropic's shape. OpenAI: "auto"
205
+ // | "required" | "none" | {type:"function",function:{name}}. Anthropic:
206
+ // {type:"auto"} | {type:"any"} | {type:"none"} | {type:"tool",name}. A
207
+ // value already shaped like Anthropic's (no "function" key) passes through
208
+ // unchanged.
209
+ //
210
+ // "auto", "required", and forcing a specific tool are live-verified:
211
+ // Anthropic returns the expected tool_use behavior for each. "none" is
212
+ // syntactically accepted by Anthropic's API (no error) but, in testing, did
213
+ // NOT suppress tool use the way OpenAI's "none" does — the model still
214
+ // called the tool. That looks like a real semantic difference on
215
+ // Anthropic's side (it may not support true tool suppression while tools
216
+ // are listed), not a bug in this translation, but treat "none" as
217
+ // best-effort until confirmed further.
218
+ function translateAnthropicToolChoice(choice) {
219
+ if (choice === "auto")
220
+ return { type: "auto" };
221
+ if (choice === "required")
222
+ return { type: "any" };
223
+ if (choice === "none")
224
+ return { type: "none" };
225
+ if (choice && typeof choice === "object") {
226
+ const c = choice;
227
+ if (c["type"] === "function" && c["function"] && typeof c["function"] === "object") {
228
+ const fn = c["function"];
229
+ if ("name" in fn)
230
+ return { type: "tool", name: fn["name"] };
231
+ }
232
+ }
233
+ return choice;
234
+ }
235
+ // Converts OpenAI-shaped tool_choice into Gemini's toolConfig shape. Gemini's
236
+ // real API has no top-level tool_choice field at all — sending one gets a
237
+ // flat 400 ("Unknown name \"tool_choice\": Cannot find field."). Tool-use
238
+ // steering lives at toolConfig.functionCallingConfig.mode (AUTO | ANY |
239
+ // NONE), plus allowedFunctionNames to force a specific tool. The caller is
240
+ // responsible for moving the key from "tool_choice" to "toolConfig" in the
241
+ // outgoing params — this only translates the value. Live-verified: all four
242
+ // shapes below produce the expected behavior, including "none" genuinely
243
+ // suppressing tool use (unlike Anthropic's tool_choice="none", which
244
+ // doesn't).
245
+ function translateGeminiToolChoice(choice) {
246
+ if (choice === "auto")
247
+ return { functionCallingConfig: { mode: "AUTO" } };
248
+ if (choice === "required")
249
+ return { functionCallingConfig: { mode: "ANY" } };
250
+ if (choice === "none")
251
+ return { functionCallingConfig: { mode: "NONE" } };
252
+ if (choice && typeof choice === "object") {
253
+ const c = choice;
254
+ if (c["type"] === "function" && c["function"] && typeof c["function"] === "object") {
255
+ const fn = c["function"];
256
+ if ("name" in fn) {
257
+ return {
258
+ functionCallingConfig: { mode: "ANY", allowedFunctionNames: [fn["name"]] },
259
+ };
260
+ }
261
+ }
262
+ }
263
+ return choice;
264
+ }
265
+ // Gemini's generateContent API has no "messages" field at all — only
266
+ // "contents" (role "model" instead of "assistant", each turn's text wrapped
267
+ // in a "parts" array) — and rejects unrecognized top-level fields, so
268
+ // temperature/max_tokens must be nested under "generationConfig" instead of
269
+ // landing at the top level the way every other provider accepts them.
270
+ function buildGeminiParams(messages, extra) {
271
+ const contents = messages.map((m) => ({
272
+ role: m.role === "assistant" ? "model" : "user",
273
+ parts: [{ text: m.content }],
274
+ }));
275
+ const { temperature, max_tokens, ...rest } = extra;
276
+ const params = { contents, ...rest };
277
+ const generationConfig = {};
278
+ if (temperature !== undefined)
279
+ generationConfig["temperature"] = temperature;
280
+ if (max_tokens !== undefined)
281
+ generationConfig["maxOutputTokens"] = max_tokens;
282
+ if (Object.keys(generationConfig).length > 0) {
283
+ params["generationConfig"] = generationConfig;
284
+ }
285
+ if (params["tools"] !== undefined) {
286
+ params["tools"] = translateGeminiTools(params["tools"]);
287
+ }
288
+ if (params["tool_choice"] !== undefined) {
289
+ const toolChoice = params["tool_choice"];
290
+ delete params["tool_choice"];
291
+ params["toolConfig"] = translateGeminiToolChoice(toolChoice);
292
+ }
293
+ return params;
294
+ }
295
+ // Recursively strips JSON Schema fields Gemini's API rejects (e.g. additionalProperties, strict).
296
+ function stripUnsupportedSchemaFields(schema) {
297
+ if (Array.isArray(schema)) {
298
+ return schema.map(stripUnsupportedSchemaFields);
299
+ }
300
+ if (schema && typeof schema === "object") {
301
+ const result = {};
302
+ for (const [key, value] of Object.entries(schema)) {
303
+ if (key === "additionalProperties" || key === "strict")
304
+ continue;
305
+ result[key] = stripUnsupportedSchemaFields(value);
306
+ }
307
+ return result;
308
+ }
309
+ return schema;
310
+ }
311
+ // Converts OpenAI-shaped function tools into Gemini's functionDeclarations shape.
312
+ // Native Gemini tool blocks (already containing "functionDeclarations") pass
313
+ // through unchanged, so callers who already speak Gemini's format directly
314
+ // aren't double-converted.
315
+ //
316
+ // Exported so @axemere/gateway-langchain can apply the identical
317
+ // translation instead of maintaining its own copy.
318
+ function translateGeminiTools(tools) {
319
+ if (!Array.isArray(tools))
320
+ return tools;
321
+ const declarations = [];
322
+ const passthrough = [];
323
+ for (const tool of tools) {
324
+ if (!tool || typeof tool !== "object" || "functionDeclarations" in tool) {
325
+ passthrough.push(tool);
326
+ continue;
327
+ }
328
+ const t = tool;
329
+ const fn = t["function"];
330
+ if (t["type"] !== "function" || !fn || typeof fn !== "object") {
331
+ passthrough.push(tool);
332
+ continue;
333
+ }
334
+ const fnObj = fn;
335
+ const declaration = { name: fnObj["name"] ?? "" };
336
+ if ("description" in fnObj)
337
+ declaration["description"] = fnObj["description"];
338
+ if ("parameters" in fnObj) {
339
+ declaration["parameters"] = stripUnsupportedSchemaFields(fnObj["parameters"]);
340
+ }
341
+ declarations.push(declaration);
342
+ }
343
+ const result = [...passthrough];
344
+ if (declarations.length > 0) {
345
+ result.push({ functionDeclarations: declarations });
346
+ }
347
+ return result;
348
+ }
139
349
  async function parseResponse(response, provider) {
140
350
  let data;
141
351
  try {
@@ -185,6 +395,24 @@ async function parseResponse(response, provider) {
185
395
  const textBlocks = contentArr?.filter((b) => b.type === "text").map((b) => b.text ?? "") ?? [];
186
396
  content = textBlocks.join("");
187
397
  }
398
+ else if (provider === "gemini" || provider === "google") {
399
+ // Gemini: candidates[0].content.parts[].text, concatenated.
400
+ const candidates = providerBody["candidates"];
401
+ const parts = candidates?.[0]?.content?.parts ?? [];
402
+ content = parts.map((p) => p.text ?? "").join("");
403
+ }
404
+ else if (provider === "cohere") {
405
+ // Cohere's v2 /v2/chat has no "choices" array at all — message
406
+ // sits at the top level, and its content is an array of blocks
407
+ // (like Anthropic), not a plain string like OpenAI. Fixture-
408
+ // verified against mvgc's own captured response
409
+ // (internal/connectors/cohere/testdata/chat_plain.json); the
410
+ // connector is pure passthrough, so this is exactly what callers
411
+ // receive.
412
+ const message = providerBody["message"];
413
+ const blocks = message?.content ?? [];
414
+ content = blocks.filter((b) => b.type === "text").map((b) => b.text ?? "").join("");
415
+ }
188
416
  else {
189
417
  // OpenAI-compatible format
190
418
  const choices = providerBody["choices"];
@@ -199,8 +427,60 @@ async function parseResponse(response, provider) {
199
427
  model: String((providerBody?.["model"]) ?? (obj["model"]) ?? ""),
200
428
  record_hash: typeof obj["record_hash"] === "string" ? obj["record_hash"] : undefined,
201
429
  provider_response: providerBody,
430
+ tool_calls: extractToolCalls(providerBody, provider),
202
431
  };
203
432
  }
433
+ function extractToolCalls(providerBody, provider) {
434
+ if (!providerBody)
435
+ return [];
436
+ if (provider === "anthropic") {
437
+ const contentArr = providerBody["content"];
438
+ return (contentArr ?? [])
439
+ .filter((b) => b.type === "tool_use")
440
+ .map((b) => ({
441
+ id: b.id ?? "",
442
+ name: b.name ?? "",
443
+ arguments: JSON.stringify(b.input ?? {}),
444
+ }));
445
+ }
446
+ if (provider === "gemini" || provider === "google") {
447
+ const candidates = providerBody["candidates"];
448
+ const parts = candidates?.[0]?.content?.parts ?? [];
449
+ return parts
450
+ .filter((p) => p.functionCall)
451
+ .map((p) => ({
452
+ id: p.functionCall?.id || `call_${randomId()}`,
453
+ name: p.functionCall?.name ?? "",
454
+ arguments: JSON.stringify(p.functionCall?.args ?? {}),
455
+ }));
456
+ }
457
+ if (provider === "cohere") {
458
+ // NOT fixture-verified (no live Cohere credential was available to
459
+ // capture a real tool-calling response) — based on Cohere's
460
+ // documented v2 API, which deliberately mirrors OpenAI's tool_calls
461
+ // shape at message.tool_calls[]. Re-verify against a live response
462
+ // if this ever becomes available; see axemere-sdks#11 Group C.
463
+ const message = providerBody["message"];
464
+ const rawCalls = message?.tool_calls ?? [];
465
+ return rawCalls.map((c) => ({
466
+ id: c.id ?? "",
467
+ name: c.function?.name ?? "",
468
+ arguments: c.function?.arguments ?? "",
469
+ }));
470
+ }
471
+ const choices = providerBody["choices"];
472
+ const rawCalls = choices?.[0]?.message?.tool_calls ?? [];
473
+ return rawCalls.map((c) => ({
474
+ id: c.id ?? "",
475
+ name: c.function?.name ?? "",
476
+ arguments: c.function?.arguments ?? "",
477
+ }));
478
+ }
479
+ // Generates an id for a Gemini functionCall that didn't supply one, so every
480
+ // tool call has a stable id regardless of provider.
481
+ function randomId() {
482
+ return (0, node_crypto_1.randomUUID)().replace(/-/g, "");
483
+ }
204
484
  function parseStreamResponse(response, provider) {
205
485
  if (!response.ok) {
206
486
  return {
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  export { AiGatewayConfig } from "./config";
2
2
  export type { AiGatewayOptions } from "./config";
3
3
  export { PLACEHOLDER_API_KEY, aiGatewayHeaders } from "./headers";
4
- export { AiGatewayClient } from "./client";
4
+ export { AiGatewayClient, translateAnthropicTools, translateGeminiTools } from "./client";
5
5
  export { GatewayError, PolicyDeniedError, QuotaExceededError, GatewayTimeoutError } from "./errors";
6
6
  export { PROVIDER_ROUTES } from "./providers";
7
7
  export type { ProviderRoute } from "./providers";
8
- export type { Message, CostBreakdownItem, Metering, ExecuteResponse, StreamChunk, ExecuteParams, } from "./types";
8
+ export type { Message, CostBreakdownItem, Metering, ExecuteResponse, StreamChunk, ExecuteParams, ToolCall, } from "./types";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PROVIDER_ROUTES = exports.GatewayTimeoutError = exports.QuotaExceededError = exports.PolicyDeniedError = exports.GatewayError = exports.AiGatewayClient = exports.aiGatewayHeaders = exports.PLACEHOLDER_API_KEY = exports.AiGatewayConfig = void 0;
3
+ exports.PROVIDER_ROUTES = exports.GatewayTimeoutError = exports.QuotaExceededError = exports.PolicyDeniedError = exports.GatewayError = exports.translateGeminiTools = exports.translateAnthropicTools = exports.AiGatewayClient = exports.aiGatewayHeaders = exports.PLACEHOLDER_API_KEY = exports.AiGatewayConfig = void 0;
4
4
  var config_1 = require("./config");
5
5
  Object.defineProperty(exports, "AiGatewayConfig", { enumerable: true, get: function () { return config_1.AiGatewayConfig; } });
6
6
  var headers_1 = require("./headers");
@@ -8,6 +8,8 @@ Object.defineProperty(exports, "PLACEHOLDER_API_KEY", { enumerable: true, get: f
8
8
  Object.defineProperty(exports, "aiGatewayHeaders", { enumerable: true, get: function () { return headers_1.aiGatewayHeaders; } });
9
9
  var client_1 = require("./client");
10
10
  Object.defineProperty(exports, "AiGatewayClient", { enumerable: true, get: function () { return client_1.AiGatewayClient; } });
11
+ Object.defineProperty(exports, "translateAnthropicTools", { enumerable: true, get: function () { return client_1.translateAnthropicTools; } });
12
+ Object.defineProperty(exports, "translateGeminiTools", { enumerable: true, get: function () { return client_1.translateGeminiTools; } });
11
13
  var errors_1 = require("./errors");
12
14
  Object.defineProperty(exports, "GatewayError", { enumerable: true, get: function () { return errors_1.GatewayError; } });
13
15
  Object.defineProperty(exports, "PolicyDeniedError", { enumerable: true, get: function () { return errors_1.PolicyDeniedError; } });
package/dist/providers.js CHANGED
@@ -26,6 +26,11 @@ exports.PROVIDER_ROUTES = {
26
26
  bedrock: { host: "bedrock-runtime.us-east-1.amazonaws.com", path: "", format: "openai" },
27
27
  vertex: { host: "us-central1-aiplatform.googleapis.com", path: "", format: "openai" },
28
28
  // azure_openai has no static host — the registry gives only HostSuffixes,
29
- // so callers must supply target_host explicitly.
30
- azure_openai: { host: "", path: "/v1/chat/completions", format: "openai" },
29
+ // so callers must supply target_host explicitly. Path is Azure's own
30
+ // REST shape, not the generic OpenAI-compatible path: the deployment
31
+ // name goes in the path and api-version is a required query parameter
32
+ // the azure_openai connector never adds itself
33
+ // (internal/connectors/azure_openai/connector.go just concatenates
34
+ // host+TargetPath verbatim, no rewriting).
35
+ azure_openai: { host: "", path: "/openai/deployments/{model}/chat/completions?api-version=2024-12-01-preview", format: "openai" },
31
36
  };
package/dist/types.d.ts CHANGED
@@ -23,6 +23,18 @@ export interface Metering {
23
23
  markup_multiplier_applied?: string;
24
24
  cost_breakdown?: CostBreakdownItem[];
25
25
  }
26
+ /**
27
+ * A single tool/function call requested by the model, normalized across providers.
28
+ *
29
+ * `arguments` is always a JSON-encoded string (matching OpenAI's own
30
+ * `function.arguments` convention), regardless of the source provider's
31
+ * native shape.
32
+ */
33
+ export interface ToolCall {
34
+ id: string;
35
+ name: string;
36
+ arguments: string;
37
+ }
26
38
  export interface ExecuteResponse {
27
39
  content: string;
28
40
  record_id: string;
@@ -31,6 +43,7 @@ export interface ExecuteResponse {
31
43
  model: string;
32
44
  record_hash?: string;
33
45
  provider_response?: unknown;
46
+ tool_calls: ToolCall[];
34
47
  }
35
48
  export interface StreamChunk {
36
49
  content: string;
package/package.json CHANGED
@@ -1,13 +1,10 @@
1
1
  {
2
2
  "name": "@axemere/gateway",
3
- "version": "0.2.1",
3
+ "version": "1.0.3",
4
4
  "description": "Axemere AI Gateway SDK — core client, config, and proxy URL builder",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
- "files": [
8
- "dist",
9
- "README.md"
10
- ],
7
+ "files": ["dist", "README.md"],
11
8
  "license": "MIT",
12
9
  "engines": {
13
10
  "node": ">=18"
@@ -20,6 +17,10 @@
20
17
  "publishConfig": {
21
18
  "access": "public"
22
19
  },
20
+ "scripts": {
21
+ "build": "tsc",
22
+ "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
23
+ },
23
24
  "dependencies": {
24
25
  "uuidv7": "^1.0.2"
25
26
  },
@@ -35,16 +36,7 @@
35
36
  "testEnvironment": "node",
36
37
  "extensionsToTreatAsEsm": [],
37
38
  "transform": {
38
- "^.+\\.tsx?$": [
39
- "ts-jest",
40
- {
41
- "useESM": false
42
- }
43
- ]
39
+ "^.+\\.tsx?$": ["ts-jest", { "useESM": false }]
44
40
  }
45
- },
46
- "scripts": {
47
- "build": "tsc",
48
- "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
49
41
  }
50
- }
42
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Axemere LLC
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.