@axemere/gateway-langchain 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +41 -0
- package/dist/index.d.ts +56 -0
- package/dist/index.js +506 -0
- package/dist/index.test.d.ts +1 -0
- package/dist/index.test.js +116 -0
- package/package.json +55 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# @axemere/gateway-langchain
|
|
2
|
+
|
|
3
|
+
LangChain `BaseChatModel` integration for the [Axemere AI Gateway](https://axemere.ai).
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @axemere/gateway-langchain @langchain/core
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { ChatAiGateway } from "@axemere/gateway-langchain";
|
|
15
|
+
import { HumanMessage } from "@langchain/core/messages";
|
|
16
|
+
|
|
17
|
+
const llm = new ChatAiGateway({ provider: "openai", model: "gpt-4o-mini" });
|
|
18
|
+
const res = await llm.invoke([new HumanMessage("Explain monads in one sentence.")]);
|
|
19
|
+
console.log(res.content);
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Supported providers
|
|
23
|
+
|
|
24
|
+
`openai`, `anthropic`, `mistral`, `google`, `xai`, `deepseek`, `groq`, `together`, `fireworks`,
|
|
25
|
+
`perplexity`, `openrouter`, `cohere`
|
|
26
|
+
|
|
27
|
+
## Proxy-mode convenience re-exports
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { aiGatewayOpenAIClient, aiGatewayAnthropicClient } from "@axemere/gateway-langchain";
|
|
31
|
+
|
|
32
|
+
const openai = aiGatewayOpenAIClient();
|
|
33
|
+
const anthropic = aiGatewayAnthropicClient();
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Configuration
|
|
37
|
+
|
|
38
|
+
Reads `AXEMERE_GATEWAY_URL` and `AXEMERE_GATEWAY_TOKEN` from the environment, or pass a
|
|
39
|
+
`config` field to the constructor.
|
|
40
|
+
|
|
41
|
+
See [@axemere/gateway](https://www.npmjs.com/package/@axemere/gateway) for all configuration options.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { BaseChatModel, BaseChatModelParams } from "@langchain/core/language_models/chat_models";
|
|
2
|
+
import type { BaseMessage } from "@langchain/core/messages";
|
|
3
|
+
import type { ChatResult } from "@langchain/core/outputs";
|
|
4
|
+
import { ChatGenerationChunk } from "@langchain/core/outputs";
|
|
5
|
+
import type { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
|
|
6
|
+
import { AiGatewayConfig, GatewayError, PolicyDeniedError } from "@axemere/gateway";
|
|
7
|
+
import { openaiClient } from "@axemere/gateway-openai";
|
|
8
|
+
import { anthropicClient } from "@axemere/gateway-anthropic";
|
|
9
|
+
export { AiGatewayConfig, GatewayError, PolicyDeniedError };
|
|
10
|
+
export { openaiClient as aiGatewayOpenAIClient };
|
|
11
|
+
export { anthropicClient as aiGatewayAnthropicClient };
|
|
12
|
+
export interface ChatAiGatewayFields extends BaseChatModelParams {
|
|
13
|
+
provider: string;
|
|
14
|
+
model: string;
|
|
15
|
+
config?: AiGatewayConfig;
|
|
16
|
+
maxTokens?: number;
|
|
17
|
+
temperature?: number;
|
|
18
|
+
workloadId?: string;
|
|
19
|
+
projectId?: string;
|
|
20
|
+
accountId?: string;
|
|
21
|
+
customerId?: string;
|
|
22
|
+
labels?: Record<string, string>;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* LangChain chat model that routes through the Axemere AI Gateway explicit action API.
|
|
26
|
+
*
|
|
27
|
+
* Supports buffered and streaming completions via `_generate()` and `_stream()`.
|
|
28
|
+
* Use {@link aiGatewayOpenAIClient} or {@link aiGatewayAnthropicClient} for proxy mode.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```ts
|
|
32
|
+
* const llm = new ChatAiGateway({ provider: "openai", model: "gpt-4o-mini" });
|
|
33
|
+
* const res = await llm.invoke("Hello");
|
|
34
|
+
* console.log(res.content);
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export declare class ChatAiGateway extends BaseChatModel {
|
|
38
|
+
readonly provider: string;
|
|
39
|
+
readonly model: string;
|
|
40
|
+
readonly maxTokens: number;
|
|
41
|
+
readonly temperature: number | undefined;
|
|
42
|
+
readonly workloadId: string | undefined;
|
|
43
|
+
readonly projectId: string | undefined;
|
|
44
|
+
readonly accountId: string | undefined;
|
|
45
|
+
readonly customerId: string | undefined;
|
|
46
|
+
readonly labels: Record<string, string> | undefined;
|
|
47
|
+
private readonly _config;
|
|
48
|
+
constructor(fields: ChatAiGatewayFields);
|
|
49
|
+
_llmType(): string;
|
|
50
|
+
private _getConfig;
|
|
51
|
+
private _effectiveLabels;
|
|
52
|
+
private _buildActionRequest;
|
|
53
|
+
private _requestHeaders;
|
|
54
|
+
_generate(messages: BaseMessage[], _options: this["ParsedCallOptions"], _runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;
|
|
55
|
+
_stream(messages: BaseMessage[], _options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;
|
|
56
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ChatAiGateway = exports.aiGatewayAnthropicClient = exports.aiGatewayOpenAIClient = exports.PolicyDeniedError = exports.GatewayError = exports.AiGatewayConfig = void 0;
|
|
4
|
+
const chat_models_1 = require("@langchain/core/language_models/chat_models");
|
|
5
|
+
const messages_1 = require("@langchain/core/messages");
|
|
6
|
+
const messages_2 = require("@langchain/core/messages");
|
|
7
|
+
const outputs_1 = require("@langchain/core/outputs");
|
|
8
|
+
const gateway_1 = require("@axemere/gateway");
|
|
9
|
+
Object.defineProperty(exports, "AiGatewayConfig", { enumerable: true, get: function () { return gateway_1.AiGatewayConfig; } });
|
|
10
|
+
Object.defineProperty(exports, "GatewayError", { enumerable: true, get: function () { return gateway_1.GatewayError; } });
|
|
11
|
+
Object.defineProperty(exports, "PolicyDeniedError", { enumerable: true, get: function () { return gateway_1.PolicyDeniedError; } });
|
|
12
|
+
const gateway_openai_1 = require("@axemere/gateway-openai");
|
|
13
|
+
Object.defineProperty(exports, "aiGatewayOpenAIClient", { enumerable: true, get: function () { return gateway_openai_1.openaiClient; } });
|
|
14
|
+
const gateway_anthropic_1 = require("@axemere/gateway-anthropic");
|
|
15
|
+
Object.defineProperty(exports, "aiGatewayAnthropicClient", { enumerable: true, get: function () { return gateway_anthropic_1.anthropicClient; } });
|
|
16
|
+
const PROVIDER_ROUTES = {
|
|
17
|
+
openai: { target_host: "api.openai.com", target_path: "/v1/chat/completions", format: "openai" },
|
|
18
|
+
anthropic: { target_host: "api.anthropic.com", target_path: "/v1/messages", format: "anthropic" },
|
|
19
|
+
mistral: { target_host: "api.mistral.ai", target_path: "/v1/chat/completions", format: "openai" },
|
|
20
|
+
google: { target_host: "generativelanguage.googleapis.com", target_path: "/v1beta/models/{model}:generateContent", format: "gemini" },
|
|
21
|
+
xai: { target_host: "api.x.ai", target_path: "/v1/chat/completions", format: "openai" },
|
|
22
|
+
deepseek: { target_host: "api.deepseek.com", target_path: "/v1/chat/completions", format: "openai" },
|
|
23
|
+
groq: { target_host: "api.groq.com", target_path: "/openai/v1/chat/completions", format: "openai" },
|
|
24
|
+
together: { target_host: "api.together.ai", target_path: "/v1/chat/completions", format: "openai" },
|
|
25
|
+
fireworks: { target_host: "api.fireworks.ai", target_path: "/inference/v1/chat/completions", format: "openai" },
|
|
26
|
+
perplexity: { target_host: "api.perplexity.ai", target_path: "/chat/completions", format: "openai" },
|
|
27
|
+
openrouter: { target_host: "openrouter.ai", target_path: "/api/v1/chat/completions", format: "openai" },
|
|
28
|
+
cohere: { target_host: "api.cohere.com", target_path: "/v2/chat", format: "openai" },
|
|
29
|
+
};
|
|
30
|
+
function messageToString(content) {
|
|
31
|
+
if (typeof content === "string")
|
|
32
|
+
return content;
|
|
33
|
+
return content
|
|
34
|
+
.filter((b) => b.type === "text")
|
|
35
|
+
.map((b) => b.text)
|
|
36
|
+
.join("");
|
|
37
|
+
}
|
|
38
|
+
function messagesToOpenAI(messages) {
|
|
39
|
+
return messages.map((msg) => {
|
|
40
|
+
if (msg instanceof messages_1.SystemMessage) {
|
|
41
|
+
return { role: "system", content: messageToString(msg.content) };
|
|
42
|
+
}
|
|
43
|
+
if (msg instanceof messages_1.HumanMessage) {
|
|
44
|
+
return { role: "user", content: messageToString(msg.content) };
|
|
45
|
+
}
|
|
46
|
+
if (msg instanceof messages_1.AIMessage) {
|
|
47
|
+
const entry = {
|
|
48
|
+
role: "assistant",
|
|
49
|
+
content: messageToString(msg.content) || null,
|
|
50
|
+
};
|
|
51
|
+
const toolCalls = msg.tool_calls;
|
|
52
|
+
if (toolCalls && toolCalls.length > 0) {
|
|
53
|
+
entry["tool_calls"] = toolCalls.map((tc) => ({
|
|
54
|
+
id: tc.id ?? "",
|
|
55
|
+
type: "function",
|
|
56
|
+
function: {
|
|
57
|
+
name: tc.name,
|
|
58
|
+
arguments: JSON.stringify(tc.args ?? {}),
|
|
59
|
+
},
|
|
60
|
+
}));
|
|
61
|
+
}
|
|
62
|
+
return entry;
|
|
63
|
+
}
|
|
64
|
+
if (msg instanceof messages_1.ToolMessage) {
|
|
65
|
+
return {
|
|
66
|
+
role: "tool",
|
|
67
|
+
tool_call_id: msg.tool_call_id,
|
|
68
|
+
content: messageToString(msg.content),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
return { role: "user", content: messageToString(msg.content) };
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
function messagesToAnthropic(messages) {
|
|
75
|
+
let system;
|
|
76
|
+
const result = [];
|
|
77
|
+
for (const msg of messages) {
|
|
78
|
+
if (msg instanceof messages_1.SystemMessage) {
|
|
79
|
+
system = messageToString(msg.content);
|
|
80
|
+
}
|
|
81
|
+
else if (msg instanceof messages_1.HumanMessage) {
|
|
82
|
+
result.push({ role: "user", content: messageToString(msg.content) });
|
|
83
|
+
}
|
|
84
|
+
else if (msg instanceof messages_1.AIMessage) {
|
|
85
|
+
const toolCalls = msg.tool_calls;
|
|
86
|
+
if (toolCalls && toolCalls.length > 0) {
|
|
87
|
+
const blocks = [];
|
|
88
|
+
const text = messageToString(msg.content);
|
|
89
|
+
if (text)
|
|
90
|
+
blocks.push({ type: "text", text });
|
|
91
|
+
for (const tc of toolCalls) {
|
|
92
|
+
blocks.push({
|
|
93
|
+
type: "tool_use",
|
|
94
|
+
id: tc.id ?? "",
|
|
95
|
+
name: tc.name,
|
|
96
|
+
input: tc.args ?? {},
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
result.push({ role: "assistant", content: blocks });
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
result.push({ role: "assistant", content: messageToString(msg.content) });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
else if (msg instanceof messages_1.ToolMessage) {
|
|
106
|
+
result.push({
|
|
107
|
+
role: "user",
|
|
108
|
+
content: [
|
|
109
|
+
{
|
|
110
|
+
type: "tool_result",
|
|
111
|
+
tool_use_id: msg.tool_call_id,
|
|
112
|
+
content: messageToString(msg.content),
|
|
113
|
+
},
|
|
114
|
+
],
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
result.push({ role: "user", content: messageToString(msg.content) });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return { system, messages: result };
|
|
122
|
+
}
|
|
123
|
+
function messagesToGemini(messages, maxTokens, temperature) {
|
|
124
|
+
let systemInstruction;
|
|
125
|
+
const contents = [];
|
|
126
|
+
const generationConfig = { maxOutputTokens: maxTokens };
|
|
127
|
+
if (temperature !== undefined)
|
|
128
|
+
generationConfig["temperature"] = temperature;
|
|
129
|
+
for (const msg of messages) {
|
|
130
|
+
if (msg instanceof messages_1.SystemMessage) {
|
|
131
|
+
systemInstruction = { parts: [{ text: messageToString(msg.content) }] };
|
|
132
|
+
}
|
|
133
|
+
else if (msg instanceof messages_1.HumanMessage) {
|
|
134
|
+
contents.push({ role: "user", parts: [{ text: messageToString(msg.content) }] });
|
|
135
|
+
}
|
|
136
|
+
else if (msg instanceof messages_1.AIMessage) {
|
|
137
|
+
contents.push({ role: "model", parts: [{ text: messageToString(msg.content) }] });
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
contents.push({ role: "user", parts: [{ text: messageToString(msg.content) }] });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return { systemInstruction, contents, generationConfig };
|
|
144
|
+
}
|
|
145
|
+
// ---------------------------------------------------------------------------
|
|
146
|
+
// Response parsing
|
|
147
|
+
// ---------------------------------------------------------------------------
|
|
148
|
+
function parseOpenAIBody(body) {
|
|
149
|
+
const choices = body["choices"];
|
|
150
|
+
if (!choices?.length)
|
|
151
|
+
return new messages_1.AIMessage({ content: "" });
|
|
152
|
+
const message = choices[0].message ?? {};
|
|
153
|
+
const content = message.content ?? "";
|
|
154
|
+
const rawToolCalls = message.tool_calls;
|
|
155
|
+
if (!rawToolCalls?.length)
|
|
156
|
+
return new messages_1.AIMessage({ content });
|
|
157
|
+
const toolCalls = rawToolCalls.map((tc) => {
|
|
158
|
+
const t = tc;
|
|
159
|
+
const argsStr = t.function?.arguments ?? "{}";
|
|
160
|
+
let args;
|
|
161
|
+
try {
|
|
162
|
+
args = JSON.parse(argsStr);
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
args = { _raw: argsStr };
|
|
166
|
+
}
|
|
167
|
+
return { id: t.id ?? "", name: t.function?.name ?? "", args, type: "tool_call" };
|
|
168
|
+
});
|
|
169
|
+
return new messages_1.AIMessage({ content, tool_calls: toolCalls });
|
|
170
|
+
}
|
|
171
|
+
function parseAnthropicBody(body) {
|
|
172
|
+
const blocks = body["content"] ?? [];
|
|
173
|
+
const textParts = [];
|
|
174
|
+
const toolCalls = [];
|
|
175
|
+
for (const block of blocks) {
|
|
176
|
+
if (block.type === "text")
|
|
177
|
+
textParts.push(block.text ?? "");
|
|
178
|
+
else if (block.type === "tool_use") {
|
|
179
|
+
toolCalls.push({
|
|
180
|
+
id: block.id ?? "",
|
|
181
|
+
name: block.name ?? "",
|
|
182
|
+
args: block.input ?? {},
|
|
183
|
+
type: "tool_call",
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const text = textParts.join("");
|
|
188
|
+
return toolCalls.length > 0
|
|
189
|
+
? new messages_1.AIMessage({ content: text, tool_calls: toolCalls })
|
|
190
|
+
: new messages_1.AIMessage({ content: text });
|
|
191
|
+
}
|
|
192
|
+
function parseGeminiBody(body) {
|
|
193
|
+
const candidates = body["candidates"] ?? [];
|
|
194
|
+
if (!candidates.length)
|
|
195
|
+
return new messages_1.AIMessage({ content: "" });
|
|
196
|
+
const parts = candidates[0].content?.parts ?? [];
|
|
197
|
+
const text = parts.map((p) => p.text ?? "").join("");
|
|
198
|
+
return new messages_1.AIMessage({ content: text });
|
|
199
|
+
}
|
|
200
|
+
// ---------------------------------------------------------------------------
|
|
201
|
+
// SSE stream text extraction
|
|
202
|
+
// ---------------------------------------------------------------------------
|
|
203
|
+
function extractStreamText(format, chunk) {
|
|
204
|
+
if (format === "openai") {
|
|
205
|
+
const choices = chunk["choices"] ?? [];
|
|
206
|
+
return choices[0]?.delta?.content ?? "";
|
|
207
|
+
}
|
|
208
|
+
if (format === "anthropic") {
|
|
209
|
+
if (chunk["type"] === "content_block_delta") {
|
|
210
|
+
return chunk["delta"]?.text ?? "";
|
|
211
|
+
}
|
|
212
|
+
return "";
|
|
213
|
+
}
|
|
214
|
+
// gemini
|
|
215
|
+
const candidates = chunk["candidates"] ?? [];
|
|
216
|
+
return (candidates[0]?.content?.parts ?? []).map((p) => p.text ?? "").join("");
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* LangChain chat model that routes through the Axemere AI Gateway explicit action API.
|
|
220
|
+
*
|
|
221
|
+
* Supports buffered and streaming completions via `_generate()` and `_stream()`.
|
|
222
|
+
* Use {@link aiGatewayOpenAIClient} or {@link aiGatewayAnthropicClient} for proxy mode.
|
|
223
|
+
*
|
|
224
|
+
* @example
|
|
225
|
+
* ```ts
|
|
226
|
+
* const llm = new ChatAiGateway({ provider: "openai", model: "gpt-4o-mini" });
|
|
227
|
+
* const res = await llm.invoke("Hello");
|
|
228
|
+
* console.log(res.content);
|
|
229
|
+
* ```
|
|
230
|
+
*/
|
|
231
|
+
class ChatAiGateway extends chat_models_1.BaseChatModel {
|
|
232
|
+
constructor(fields) {
|
|
233
|
+
super(fields);
|
|
234
|
+
if (!PROVIDER_ROUTES[fields.provider]) {
|
|
235
|
+
throw new gateway_1.GatewayError(`Unsupported provider "${fields.provider}". Supported: ${Object.keys(PROVIDER_ROUTES).sort().join(", ")}`);
|
|
236
|
+
}
|
|
237
|
+
this.provider = fields.provider;
|
|
238
|
+
this.model = fields.model;
|
|
239
|
+
this.maxTokens = fields.maxTokens ?? 256;
|
|
240
|
+
this.temperature = fields.temperature;
|
|
241
|
+
this.workloadId = fields.workloadId;
|
|
242
|
+
this.projectId = fields.projectId;
|
|
243
|
+
this.accountId = fields.accountId;
|
|
244
|
+
this.customerId = fields.customerId;
|
|
245
|
+
this.labels = fields.labels;
|
|
246
|
+
this._config = fields.config;
|
|
247
|
+
}
|
|
248
|
+
_llmType() {
|
|
249
|
+
return "axemere-gateway";
|
|
250
|
+
}
|
|
251
|
+
_getConfig() {
|
|
252
|
+
return this._config ?? new gateway_1.AiGatewayConfig();
|
|
253
|
+
}
|
|
254
|
+
_effectiveLabels(cfg) {
|
|
255
|
+
const base = { source: "langchain" };
|
|
256
|
+
if (cfg.labels)
|
|
257
|
+
Object.assign(base, cfg.labels);
|
|
258
|
+
if (this.labels)
|
|
259
|
+
Object.assign(base, this.labels);
|
|
260
|
+
return base;
|
|
261
|
+
}
|
|
262
|
+
_buildActionRequest(messages, cfg, stream, tools) {
|
|
263
|
+
const route = PROVIDER_ROUTES[this.provider];
|
|
264
|
+
const targetPath = route.target_path.replace("{model}", this.model);
|
|
265
|
+
let params;
|
|
266
|
+
if (route.format === "openai") {
|
|
267
|
+
params = {
|
|
268
|
+
model: this.model,
|
|
269
|
+
messages: messagesToOpenAI(messages),
|
|
270
|
+
max_tokens: this.maxTokens,
|
|
271
|
+
};
|
|
272
|
+
if (this.temperature !== undefined)
|
|
273
|
+
params["temperature"] = this.temperature;
|
|
274
|
+
if (tools?.length)
|
|
275
|
+
params["tools"] = tools;
|
|
276
|
+
}
|
|
277
|
+
else if (route.format === "anthropic") {
|
|
278
|
+
const { system, messages: anthropicMessages } = messagesToAnthropic(messages);
|
|
279
|
+
params = {
|
|
280
|
+
model: this.model,
|
|
281
|
+
messages: anthropicMessages,
|
|
282
|
+
max_tokens: this.maxTokens,
|
|
283
|
+
};
|
|
284
|
+
if (system)
|
|
285
|
+
params["system"] = system;
|
|
286
|
+
if (this.temperature !== undefined)
|
|
287
|
+
params["temperature"] = this.temperature;
|
|
288
|
+
if (tools?.length)
|
|
289
|
+
params["tools"] = tools;
|
|
290
|
+
}
|
|
291
|
+
else {
|
|
292
|
+
// gemini
|
|
293
|
+
const { systemInstruction, contents, generationConfig } = messagesToGemini(messages, this.maxTokens, this.temperature);
|
|
294
|
+
params = { contents, generationConfig };
|
|
295
|
+
if (systemInstruction)
|
|
296
|
+
params["systemInstruction"] = systemInstruction;
|
|
297
|
+
}
|
|
298
|
+
if (stream)
|
|
299
|
+
params["stream"] = true;
|
|
300
|
+
const workloadId = this.workloadId ?? cfg.workload_id ?? undefined;
|
|
301
|
+
return {
|
|
302
|
+
schema: "mvgc.action_request.v2",
|
|
303
|
+
request_id: crypto.randomUUID(),
|
|
304
|
+
org_id: "",
|
|
305
|
+
caller_id: "langchain",
|
|
306
|
+
workload_id: workloadId ?? "",
|
|
307
|
+
ingress_mode: "explicit_action_request",
|
|
308
|
+
action: {
|
|
309
|
+
type: "llm_chat",
|
|
310
|
+
method: "POST",
|
|
311
|
+
target_host: route.target_host,
|
|
312
|
+
target_path: targetPath,
|
|
313
|
+
params,
|
|
314
|
+
},
|
|
315
|
+
attribution: {
|
|
316
|
+
project_id: this.projectId ?? cfg.project_id ?? undefined,
|
|
317
|
+
customer_id: this.customerId ?? cfg.customer_id ?? undefined,
|
|
318
|
+
account_id: this.accountId ?? cfg.account_id ?? undefined,
|
|
319
|
+
labels: this._effectiveLabels(cfg),
|
|
320
|
+
},
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
_requestHeaders(cfg) {
|
|
324
|
+
const headers = { "Content-Type": "application/json" };
|
|
325
|
+
if (cfg.gateway_token)
|
|
326
|
+
headers["Authorization"] = `Bearer ${cfg.gateway_token}`;
|
|
327
|
+
return headers;
|
|
328
|
+
}
|
|
329
|
+
async _generate(messages, _options, _runManager) {
|
|
330
|
+
const cfg = this._getConfig();
|
|
331
|
+
const actionRequest = this._buildActionRequest(messages, cfg, false);
|
|
332
|
+
let response;
|
|
333
|
+
try {
|
|
334
|
+
response = await fetch(`${cfg.gateway_url}/v1/actions:execute`, {
|
|
335
|
+
method: "POST",
|
|
336
|
+
headers: this._requestHeaders(cfg),
|
|
337
|
+
body: JSON.stringify(actionRequest),
|
|
338
|
+
signal: AbortSignal.timeout(cfg.timeout * 1000),
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
catch (err) {
|
|
342
|
+
throw new gateway_1.GatewayError(`Gateway connection failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
343
|
+
}
|
|
344
|
+
let data;
|
|
345
|
+
try {
|
|
346
|
+
data = (await response.json());
|
|
347
|
+
}
|
|
348
|
+
catch {
|
|
349
|
+
throw new gateway_1.GatewayError(`Invalid JSON from gateway (HTTP ${response.status})`);
|
|
350
|
+
}
|
|
351
|
+
if (data["decision"] === "deny" || response.status === 403) {
|
|
352
|
+
const reason = String(data["reason"] ?? data["message"] ?? data["error"] ?? `HTTP ${response.status}`);
|
|
353
|
+
const err = new gateway_1.PolicyDeniedError(reason);
|
|
354
|
+
err.reason = reason;
|
|
355
|
+
err.trace = data["trace"];
|
|
356
|
+
throw err;
|
|
357
|
+
}
|
|
358
|
+
if (response.status === 429)
|
|
359
|
+
throw new gateway_1.GatewayError("Request rate limited by gateway");
|
|
360
|
+
if (response.status >= 400) {
|
|
361
|
+
throw new gateway_1.GatewayError(`Gateway returned HTTP ${response.status}: ${JSON.stringify(data)}`);
|
|
362
|
+
}
|
|
363
|
+
const result = data["result"];
|
|
364
|
+
if (!result)
|
|
365
|
+
throw new gateway_1.GatewayError("No 'result' field in gateway response");
|
|
366
|
+
const body = result["body"];
|
|
367
|
+
if (!body)
|
|
368
|
+
throw new gateway_1.GatewayError("No 'body' field in connector result");
|
|
369
|
+
const upstreamStatus = result["status_code"] ?? 200;
|
|
370
|
+
if (upstreamStatus >= 400) {
|
|
371
|
+
const errObj = body["error"] ?? {};
|
|
372
|
+
const msg = errObj.message ??
|
|
373
|
+
body["message"] ??
|
|
374
|
+
JSON.stringify(body);
|
|
375
|
+
throw new gateway_1.GatewayError(`Upstream ${this.provider} returned HTTP ${upstreamStatus}: ${msg}`);
|
|
376
|
+
}
|
|
377
|
+
const route = PROVIDER_ROUTES[this.provider];
|
|
378
|
+
let aiMessage;
|
|
379
|
+
if (route.format === "openai")
|
|
380
|
+
aiMessage = parseOpenAIBody(body);
|
|
381
|
+
else if (route.format === "anthropic")
|
|
382
|
+
aiMessage = parseAnthropicBody(body);
|
|
383
|
+
else
|
|
384
|
+
aiMessage = parseGeminiBody(body);
|
|
385
|
+
const text = typeof aiMessage.content === "string" ? aiMessage.content : "";
|
|
386
|
+
return {
|
|
387
|
+
generations: [
|
|
388
|
+
{
|
|
389
|
+
message: aiMessage,
|
|
390
|
+
text,
|
|
391
|
+
generationInfo: {
|
|
392
|
+
record_id: data["record_id"],
|
|
393
|
+
metering: data["metering"],
|
|
394
|
+
provider: this.provider,
|
|
395
|
+
model: this.model,
|
|
396
|
+
},
|
|
397
|
+
},
|
|
398
|
+
],
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
async *_stream(messages, _options, runManager) {
|
|
402
|
+
const cfg = this._getConfig();
|
|
403
|
+
const route = PROVIDER_ROUTES[this.provider];
|
|
404
|
+
const actionRequest = this._buildActionRequest(messages, cfg, true);
|
|
405
|
+
let response;
|
|
406
|
+
try {
|
|
407
|
+
response = await fetch(`${cfg.gateway_url}/v1/actions:execute`, {
|
|
408
|
+
method: "POST",
|
|
409
|
+
headers: this._requestHeaders(cfg),
|
|
410
|
+
body: JSON.stringify(actionRequest),
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
catch (err) {
|
|
414
|
+
throw new gateway_1.GatewayError(`Gateway connection failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
415
|
+
}
|
|
416
|
+
if (!response.ok) {
|
|
417
|
+
let errData;
|
|
418
|
+
try {
|
|
419
|
+
errData = await response.json();
|
|
420
|
+
}
|
|
421
|
+
catch {
|
|
422
|
+
errData = undefined;
|
|
423
|
+
}
|
|
424
|
+
if (response.status === 403) {
|
|
425
|
+
const d = errData ?? {};
|
|
426
|
+
const reason = String(d["reason"] ?? d["message"] ?? `HTTP ${response.status}`);
|
|
427
|
+
const err = new gateway_1.PolicyDeniedError(reason);
|
|
428
|
+
err.reason = reason;
|
|
429
|
+
throw err;
|
|
430
|
+
}
|
|
431
|
+
throw new gateway_1.GatewayError(`Gateway returned HTTP ${response.status}`);
|
|
432
|
+
}
|
|
433
|
+
const responseBody = response.body;
|
|
434
|
+
if (!responseBody)
|
|
435
|
+
throw new gateway_1.GatewayError("Empty response body on streaming request");
|
|
436
|
+
const reader = responseBody.getReader();
|
|
437
|
+
const decoder = new TextDecoder();
|
|
438
|
+
let buffer = "";
|
|
439
|
+
let recordId;
|
|
440
|
+
let metering;
|
|
441
|
+
let done = false;
|
|
442
|
+
try {
|
|
443
|
+
while (!done) {
|
|
444
|
+
const { done: streamDone, value } = await reader.read();
|
|
445
|
+
if (streamDone)
|
|
446
|
+
break;
|
|
447
|
+
buffer += decoder.decode(value, { stream: true });
|
|
448
|
+
const lines = buffer.split("\n");
|
|
449
|
+
buffer = lines.pop() ?? "";
|
|
450
|
+
for (const line of lines) {
|
|
451
|
+
const trimmed = line.trim();
|
|
452
|
+
if (!trimmed || trimmed.startsWith(":") || !trimmed.startsWith("data: ")) {
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
const payload = trimmed.slice(6).trim();
|
|
456
|
+
if (payload === "[DONE]") {
|
|
457
|
+
done = true;
|
|
458
|
+
break;
|
|
459
|
+
}
|
|
460
|
+
let chunk;
|
|
461
|
+
try {
|
|
462
|
+
chunk = JSON.parse(payload);
|
|
463
|
+
}
|
|
464
|
+
catch {
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
if (chunk["type"] === "mvgc_metering") {
|
|
468
|
+
metering = chunk["metering"];
|
|
469
|
+
if (!recordId && typeof chunk["record_id"] === "string") {
|
|
470
|
+
recordId = chunk["record_id"];
|
|
471
|
+
}
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
if (chunk["type"] === "message_stop") {
|
|
475
|
+
done = true;
|
|
476
|
+
break;
|
|
477
|
+
}
|
|
478
|
+
const text = extractStreamText(route.format, chunk);
|
|
479
|
+
if (text) {
|
|
480
|
+
const genChunk = new outputs_1.ChatGenerationChunk({
|
|
481
|
+
message: new messages_2.AIMessageChunk({ content: text }),
|
|
482
|
+
text,
|
|
483
|
+
});
|
|
484
|
+
if (runManager)
|
|
485
|
+
await runManager.handleLLMNewToken(text);
|
|
486
|
+
yield genChunk;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
finally {
|
|
492
|
+
reader.releaseLock();
|
|
493
|
+
}
|
|
494
|
+
yield new outputs_1.ChatGenerationChunk({
|
|
495
|
+
message: new messages_2.AIMessageChunk({ content: "" }),
|
|
496
|
+
text: "",
|
|
497
|
+
generationInfo: {
|
|
498
|
+
record_id: recordId,
|
|
499
|
+
metering,
|
|
500
|
+
provider: this.provider,
|
|
501
|
+
model: this.model,
|
|
502
|
+
},
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
exports.ChatAiGateway = ChatAiGateway;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const gateway_1 = require("@axemere/gateway");
|
|
4
|
+
const index_1 = require("./index");
|
|
5
|
+
describe("ChatAiGateway — construction", () => {
|
|
6
|
+
it("can be instantiated with a valid provider", () => {
|
|
7
|
+
expect(() => new index_1.ChatAiGateway({
|
|
8
|
+
provider: "openai",
|
|
9
|
+
model: "gpt-4o-mini",
|
|
10
|
+
config: new gateway_1.AiGatewayConfig({ gateway_url: "http://localhost:7080" }),
|
|
11
|
+
})).not.toThrow();
|
|
12
|
+
});
|
|
13
|
+
it("throws on unsupported provider", () => {
|
|
14
|
+
expect(() => new index_1.ChatAiGateway({
|
|
15
|
+
provider: "not-a-real-provider",
|
|
16
|
+
model: "some-model",
|
|
17
|
+
})).toThrow(/Unsupported provider/);
|
|
18
|
+
});
|
|
19
|
+
it("defaults maxTokens to 256", () => {
|
|
20
|
+
const llm = new index_1.ChatAiGateway({ provider: "openai", model: "gpt-4o-mini" });
|
|
21
|
+
expect(llm.maxTokens).toBe(256);
|
|
22
|
+
});
|
|
23
|
+
it("respects caller-supplied maxTokens", () => {
|
|
24
|
+
const llm = new index_1.ChatAiGateway({ provider: "openai", model: "gpt-4o-mini", maxTokens: 1024 });
|
|
25
|
+
expect(llm.maxTokens).toBe(1024);
|
|
26
|
+
});
|
|
27
|
+
it("_llmType returns 'axemere-gateway'", () => {
|
|
28
|
+
const llm = new index_1.ChatAiGateway({ provider: "anthropic", model: "claude-haiku-4-5-20251001" });
|
|
29
|
+
expect(llm._llmType()).toBe("axemere-gateway");
|
|
30
|
+
});
|
|
31
|
+
it("supports all documented providers", () => {
|
|
32
|
+
const providers = [
|
|
33
|
+
"openai", "anthropic", "mistral", "google",
|
|
34
|
+
"xai", "deepseek", "groq", "together",
|
|
35
|
+
"fireworks", "perplexity", "openrouter", "cohere",
|
|
36
|
+
];
|
|
37
|
+
for (const provider of providers) {
|
|
38
|
+
expect(() => new index_1.ChatAiGateway({ provider, model: "some-model" })).not.toThrow();
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
describe("ChatAiGateway — _generate wire body", () => {
|
|
43
|
+
function mockFetch(body, status = 200) {
|
|
44
|
+
return jest.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify(body), {
|
|
45
|
+
status,
|
|
46
|
+
headers: { "Content-Type": "application/json" },
|
|
47
|
+
}));
|
|
48
|
+
}
|
|
49
|
+
afterEach(() => jest.restoreAllMocks());
|
|
50
|
+
const cfg = new gateway_1.AiGatewayConfig({
|
|
51
|
+
gateway_url: "http://localhost:7080",
|
|
52
|
+
gateway_token: "tok_test",
|
|
53
|
+
});
|
|
54
|
+
it("sends correct action type and target_host for openai", async () => {
|
|
55
|
+
let capturedBody = {};
|
|
56
|
+
jest.spyOn(globalThis, "fetch").mockImplementation((_, init) => {
|
|
57
|
+
capturedBody = JSON.parse(init?.body);
|
|
58
|
+
return Promise.resolve(new Response(JSON.stringify({
|
|
59
|
+
decision: "allow",
|
|
60
|
+
record_id: "rec_1",
|
|
61
|
+
metering: {},
|
|
62
|
+
result: {
|
|
63
|
+
status_code: 200,
|
|
64
|
+
body: { choices: [{ message: { content: "Hello!" } }] },
|
|
65
|
+
},
|
|
66
|
+
}), { status: 200 }));
|
|
67
|
+
});
|
|
68
|
+
const llm = new index_1.ChatAiGateway({ provider: "openai", model: "gpt-4o-mini", config: cfg });
|
|
69
|
+
await llm.invoke("hi");
|
|
70
|
+
const action = capturedBody["action"];
|
|
71
|
+
expect(action["target_host"]).toBe("api.openai.com");
|
|
72
|
+
expect(action["target_path"]).toBe("/v1/chat/completions");
|
|
73
|
+
expect(action["params"]["model"]).toBe("gpt-4o-mini");
|
|
74
|
+
});
|
|
75
|
+
it("sends correct target_host for anthropic", async () => {
|
|
76
|
+
let capturedBody = {};
|
|
77
|
+
jest.spyOn(globalThis, "fetch").mockImplementation((_, init) => {
|
|
78
|
+
capturedBody = JSON.parse(init?.body);
|
|
79
|
+
return Promise.resolve(new Response(JSON.stringify({
|
|
80
|
+
decision: "allow",
|
|
81
|
+
record_id: "rec_2",
|
|
82
|
+
metering: {},
|
|
83
|
+
result: {
|
|
84
|
+
status_code: 200,
|
|
85
|
+
body: { content: [{ type: "text", text: "Hi!" }] },
|
|
86
|
+
},
|
|
87
|
+
}), { status: 200 }));
|
|
88
|
+
});
|
|
89
|
+
const llm = new index_1.ChatAiGateway({
|
|
90
|
+
provider: "anthropic",
|
|
91
|
+
model: "claude-haiku-4-5-20251001",
|
|
92
|
+
config: cfg,
|
|
93
|
+
});
|
|
94
|
+
await llm.invoke("hi");
|
|
95
|
+
const action = capturedBody["action"];
|
|
96
|
+
expect(action["target_host"]).toBe("api.anthropic.com");
|
|
97
|
+
});
|
|
98
|
+
it("throws PolicyDeniedError on decision=deny", async () => {
|
|
99
|
+
mockFetch({ decision: "deny", reason: "budget exceeded", record_id: "rec_3" });
|
|
100
|
+
const llm = new index_1.ChatAiGateway({ provider: "openai", model: "gpt-4o-mini", config: cfg });
|
|
101
|
+
await expect(llm.invoke("hi")).rejects.toMatchObject({ reason: "budget exceeded" });
|
|
102
|
+
});
|
|
103
|
+
it("throws GatewayError on HTTP 500", async () => {
|
|
104
|
+
mockFetch({ error: "internal" }, 500);
|
|
105
|
+
const llm = new index_1.ChatAiGateway({ provider: "openai", model: "gpt-4o-mini", config: cfg });
|
|
106
|
+
await expect(llm.invoke("hi")).rejects.toBeInstanceOf(Error);
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
describe("proxy re-exports", () => {
|
|
110
|
+
it("aiGatewayOpenAIClient is a function", () => {
|
|
111
|
+
expect(typeof index_1.aiGatewayOpenAIClient).toBe("function");
|
|
112
|
+
});
|
|
113
|
+
it("aiGatewayAnthropicClient is a function", () => {
|
|
114
|
+
expect(typeof index_1.aiGatewayAnthropicClient).toBe("function");
|
|
115
|
+
});
|
|
116
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@axemere/gateway-langchain",
|
|
3
|
+
"version": "0.1.9",
|
|
4
|
+
"description": "Axemere AI Gateway SDK — LangChain BaseChatModel integration",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist",
|
|
9
|
+
"README.md"
|
|
10
|
+
],
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=18"
|
|
14
|
+
},
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/Axemere-LLC/axemere-node.git",
|
|
18
|
+
"directory": "packages/gateway-langchain"
|
|
19
|
+
},
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"@langchain/core": ">=0.3.0"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@axemere/gateway-openai": "0.1.9",
|
|
28
|
+
"@axemere/gateway-anthropic": "0.1.9",
|
|
29
|
+
"@axemere/gateway": "0.1.9"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@langchain/core": "^0.3.0",
|
|
33
|
+
"typescript": "^5.4.0",
|
|
34
|
+
"@types/node": "^20.0.0",
|
|
35
|
+
"@types/jest": "^29.0.0",
|
|
36
|
+
"jest": "^29.0.0",
|
|
37
|
+
"ts-jest": "^29.0.0"
|
|
38
|
+
},
|
|
39
|
+
"jest": {
|
|
40
|
+
"preset": "ts-jest",
|
|
41
|
+
"testEnvironment": "node",
|
|
42
|
+
"transform": {
|
|
43
|
+
"^.+\\.tsx?$": [
|
|
44
|
+
"ts-jest",
|
|
45
|
+
{
|
|
46
|
+
"useESM": false
|
|
47
|
+
}
|
|
48
|
+
]
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build": "tsc",
|
|
53
|
+
"test": "jest"
|
|
54
|
+
}
|
|
55
|
+
}
|