@ax-llm/ax-ai-sdk-provider 25.0.0 → 25.0.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/index.cjs CHANGED
@@ -1,654 +1,559 @@
1
- "use strict";
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ //#region \0rolldown/runtime.js
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
7
  var __getProtoOf = Object.getPrototypeOf;
7
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
9
  var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
+ key = keys[i];
13
+ if (!__hasOwnProp.call(to, key) && key !== except) {
14
+ __defProp(to, key, {
15
+ get: ((k) => from[k]).bind(null, key),
16
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
+ });
18
+ }
19
+ }
20
+ }
21
+ return to;
19
22
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
29
27
 
30
- // index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- AxAIProvider: () => AxAIProvider,
34
- AxAgentProvider: () => AxAgentProvider
35
- });
36
- module.exports = __toCommonJS(index_exports);
28
+ //#endregion
29
+ let crypto = require("crypto");
30
+ crypto = __toESM(crypto, 1);
31
+ let zod = require("zod");
37
32
 
38
- // ../../node_modules/nanoid/index.js
39
- var import_crypto = __toESM(require("crypto"), 1);
40
- var POOL_SIZE_MULTIPLIER = 128;
41
- var pool;
42
- var poolOffset;
43
- var fillPool = (bytes) => {
44
- if (!pool || pool.length < bytes) {
45
- pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
46
- import_crypto.default.randomFillSync(pool);
47
- poolOffset = 0;
48
- } else if (poolOffset + bytes > pool.length) {
49
- import_crypto.default.randomFillSync(pool);
50
- poolOffset = 0;
51
- }
52
- poolOffset += bytes;
33
+ //#region ../../node_modules/nanoid/index.js
34
+ const POOL_SIZE_MULTIPLIER = 128;
35
+ let pool;
36
+ let poolOffset;
37
+ let fillPool = (bytes) => {
38
+ if (bytes < 0 || bytes > 1024) throw new RangeError("Wrong ID size");
39
+ try {
40
+ if (!pool || pool.length < bytes) {
41
+ pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
42
+ crypto.default.randomFillSync(pool);
43
+ poolOffset = 0;
44
+ } else if (poolOffset + bytes > pool.length) {
45
+ crypto.default.randomFillSync(pool);
46
+ poolOffset = 0;
47
+ }
48
+ } catch (e) {
49
+ pool = void 0;
50
+ throw e;
51
+ }
52
+ poolOffset += bytes;
53
53
  };
54
- var random = (bytes) => {
55
- fillPool(bytes |= 0);
56
- return pool.subarray(poolOffset - bytes, poolOffset);
54
+ let random = (bytes) => {
55
+ fillPool(bytes |= 0);
56
+ return pool.subarray(poolOffset - bytes, poolOffset);
57
57
  };
58
- var customRandom = (alphabet, defaultSize, getRandom) => {
59
- let mask = (2 << 31 - Math.clz32(alphabet.length - 1 | 1)) - 1;
60
- let step = Math.ceil(1.6 * mask * defaultSize / alphabet.length);
61
- return (size = defaultSize) => {
62
- let id = "";
63
- while (true) {
64
- let bytes = getRandom(step);
65
- let i = step;
66
- while (i--) {
67
- id += alphabet[bytes[i] & mask] || "";
68
- if (id.length === size) return id;
69
- }
70
- }
71
- };
58
+ let customRandom = (alphabet, defaultSize, getRandom) => {
59
+ let mask = (2 << 31 - Math.clz32(alphabet.length - 1 | 1)) - 1;
60
+ let step = Math.ceil(1.6 * mask * defaultSize / alphabet.length);
61
+ return (size = defaultSize) => {
62
+ if (size <= 0) return "";
63
+ let id = "";
64
+ while (true) {
65
+ let bytes = getRandom(step);
66
+ let i = step;
67
+ while (i--) {
68
+ id += alphabet[bytes[i] & mask] || "";
69
+ if (id.length === size) return id;
70
+ }
71
+ }
72
+ };
72
73
  };
73
- var customAlphabet = (alphabet, size = 21) => customRandom(alphabet, size, random);
74
+ let customAlphabet = (alphabet, size = 21) => customRandom(alphabet, size, random);
74
75
 
75
- // provider.ts
76
- var import_zod = require("zod");
76
+ //#endregion
77
+ //#region provider.ts
77
78
  function toJSONValue(value) {
78
- if (value === null) return null;
79
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
80
- return value;
81
- }
82
- if (Array.isArray(value)) {
83
- return value.map((item) => toJSONValue(item)).filter((item) => item !== void 0);
84
- }
85
- if (value && typeof value === "object") {
86
- const entries = Object.entries(value).map(([key, nested]) => [key, toJSONValue(nested)]).filter((entry) => {
87
- return entry[1] !== void 0;
88
- });
89
- return Object.fromEntries(entries);
90
- }
91
- return void 0;
79
+ if (value === null) return null;
80
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
81
+ if (Array.isArray(value)) return value.map((item) => toJSONValue(item)).filter((item) => item !== void 0);
82
+ if (value && typeof value === "object") {
83
+ const entries = Object.entries(value).map(([key, nested]) => [key, toJSONValue(nested)]).filter((entry) => {
84
+ return entry[1] !== void 0;
85
+ });
86
+ return Object.fromEntries(entries);
87
+ }
92
88
  }
93
89
  function mergeProviderMetadata(base, next) {
94
- if (!base && !next) return void 0;
95
- const merged = {};
96
- for (const source of [base, next]) {
97
- if (!source) continue;
98
- for (const [provider, metadata] of Object.entries(source)) {
99
- merged[provider] = {
100
- ...merged[provider] ?? {},
101
- ...metadata
102
- };
103
- }
104
- }
105
- return merged;
90
+ if (!base && !next) return void 0;
91
+ const merged = {};
92
+ for (const source of [base, next]) {
93
+ if (!source) continue;
94
+ for (const [provider, metadata] of Object.entries(source)) merged[provider] = {
95
+ ...merged[provider] ?? {},
96
+ ...metadata
97
+ };
98
+ }
99
+ return merged;
106
100
  }
107
101
  function createProviderMetadata(res, provider) {
108
- let metadata;
109
- if (res.providerMetadata) {
110
- metadata = {};
111
- for (const [providerName, providerMetadata] of Object.entries(
112
- res.providerMetadata
113
- )) {
114
- const jsonProviderMetadata = toJSONValue(providerMetadata);
115
- if (jsonProviderMetadata && typeof jsonProviderMetadata === "object" && !Array.isArray(jsonProviderMetadata)) {
116
- metadata[providerName] = jsonProviderMetadata;
117
- }
118
- }
119
- }
120
- const axMetadata = {
121
- ...res.sessionId ? { sessionId: res.sessionId } : {},
122
- ...res.remoteRequestId ? { requestId: res.remoteRequestId } : {},
123
- ...res.remoteSessionId ? { remoteSessionId: res.remoteSessionId } : {}
124
- };
125
- if (Object.keys(axMetadata).length > 0) {
126
- metadata = mergeProviderMetadata(metadata, {
127
- [provider]: axMetadata
128
- });
129
- }
130
- return metadata;
102
+ let metadata;
103
+ if (res.providerMetadata) {
104
+ metadata = {};
105
+ for (const [providerName, providerMetadata] of Object.entries(res.providerMetadata)) {
106
+ const jsonProviderMetadata = toJSONValue(providerMetadata);
107
+ if (jsonProviderMetadata && typeof jsonProviderMetadata === "object" && !Array.isArray(jsonProviderMetadata)) metadata[providerName] = jsonProviderMetadata;
108
+ }
109
+ }
110
+ const axMetadata = {
111
+ ...res.sessionId ? { sessionId: res.sessionId } : {},
112
+ ...res.remoteRequestId ? { requestId: res.remoteRequestId } : {},
113
+ ...res.remoteSessionId ? { remoteSessionId: res.remoteSessionId } : {}
114
+ };
115
+ if (Object.keys(axMetadata).length > 0) metadata = mergeProviderMetadata(metadata, { [provider]: axMetadata });
116
+ return metadata;
131
117
  }
132
118
  function createResponseMetadata(res) {
133
- if (!res.remoteId && !res.modelUsage?.model) {
134
- return void 0;
135
- }
136
- return {
137
- ...res.remoteId ? { id: res.remoteId } : {},
138
- ...res.modelUsage?.model ? { modelId: res.modelUsage.model } : {}
139
- };
119
+ if (!res.remoteId && !res.modelUsage?.model) return;
120
+ return {
121
+ ...res.remoteId ? { id: res.remoteId } : {},
122
+ ...res.modelUsage?.model ? { modelId: res.modelUsage.model } : {}
123
+ };
140
124
  }
141
- var nanoid = customAlphabet(
142
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
143
- 7
144
- );
125
+ const nanoid = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 7);
145
126
  var AxAgentProvider = class {
146
- config;
147
- funcInfo;
148
- generateFunction;
149
- updateState;
150
- constructor({
151
- agent,
152
- updateState,
153
- generate,
154
- config
155
- }) {
156
- this.funcInfo = agent.getFunction();
157
- this.generateFunction = generate;
158
- this.updateState = updateState;
159
- this.config = config;
160
- }
161
- get description() {
162
- return this.funcInfo.description;
163
- }
164
- get parameters() {
165
- const schema = this.funcInfo.parameters ?? {
166
- type: "object",
167
- properties: {}
168
- };
169
- return convertToZodSchema(schema);
170
- }
171
- get generate() {
172
- const fn = async (input) => {
173
- const res = await this.funcInfo.func(input);
174
- const toolCallId = nanoid();
175
- this.updateState([
176
- {
177
- role: "assistant",
178
- content: [
179
- {
180
- type: "tool-call",
181
- toolName: this.funcInfo.name,
182
- toolCallId,
183
- input
184
- }
185
- ]
186
- },
187
- {
188
- role: "tool",
189
- content: [
190
- {
191
- type: "tool-result",
192
- toolName: this.funcInfo.name,
193
- toolCallId,
194
- output: { type: "text", value: JSON.stringify(res) }
195
- }
196
- ]
197
- }
198
- ]);
199
- return this.generateFunction(res);
200
- };
201
- return fn;
202
- }
127
+ config;
128
+ funcInfo;
129
+ generateFunction;
130
+ updateState;
131
+ constructor({ agent, updateState, generate, config }) {
132
+ this.funcInfo = agent.getFunction();
133
+ this.generateFunction = generate;
134
+ this.updateState = updateState;
135
+ this.config = config;
136
+ }
137
+ get description() {
138
+ return this.funcInfo.description;
139
+ }
140
+ get parameters() {
141
+ return convertToZodSchema(this.funcInfo.parameters ?? {
142
+ type: "object",
143
+ properties: {}
144
+ });
145
+ }
146
+ get generate() {
147
+ const fn = async (input) => {
148
+ const res = await this.funcInfo.func(input);
149
+ const toolCallId = nanoid();
150
+ this.updateState([{
151
+ role: "assistant",
152
+ content: [{
153
+ type: "tool-call",
154
+ toolName: this.funcInfo.name,
155
+ toolCallId,
156
+ input
157
+ }]
158
+ }, {
159
+ role: "tool",
160
+ content: [{
161
+ type: "tool-result",
162
+ toolName: this.funcInfo.name,
163
+ toolCallId,
164
+ output: {
165
+ type: "text",
166
+ value: JSON.stringify(res)
167
+ }
168
+ }]
169
+ }]);
170
+ return this.generateFunction(res);
171
+ };
172
+ return fn;
173
+ }
203
174
  };
204
175
  var AxAIProvider = class {
205
- specificationVersion = "v3";
206
- supportedUrls = {};
207
- ai;
208
- config;
209
- modelId;
210
- constructor(ai, config) {
211
- this.ai = ai;
212
- this.config = config;
213
- this.modelId = this.ai.getName();
214
- }
215
- get provider() {
216
- return this.ai.getName();
217
- }
218
- async doGenerate(options) {
219
- const req = createChatRequest(options);
220
- const res = await this.ai.chat(req, {
221
- stream: false
222
- });
223
- const choice = res.results.at(0);
224
- if (!choice) {
225
- throw new Error("No choice returned");
226
- }
227
- const content = [];
228
- if (choice.content) {
229
- content.push({ type: "text", text: choice.content });
230
- }
231
- if (choice.functionCalls) {
232
- for (const tc of choice.functionCalls) {
233
- content.push({
234
- type: "tool-call",
235
- toolCallId: tc.id,
236
- toolName: tc.function.name,
237
- input: typeof tc.function.params === "string" ? tc.function.params : JSON.stringify(tc.function.params)
238
- });
239
- }
240
- }
241
- const providerMetadata = createProviderMetadata(res, this.provider);
242
- const response = createResponseMetadata(res);
243
- return {
244
- content,
245
- finishReason: mapAxFinishReason(choice.finishReason),
246
- usage: createUsage(res.modelUsage?.tokens),
247
- ...providerMetadata ? { providerMetadata } : {},
248
- ...response ? { response } : {},
249
- warnings: []
250
- };
251
- }
252
- async doStream(options) {
253
- const req = createChatRequest(options);
254
- const res = await this.ai.chat(req, {
255
- stream: true
256
- });
257
- return {
258
- stream: res.pipeThrough(new AxToSDKTransformer(this.provider))
259
- };
260
- }
176
+ specificationVersion = "v3";
177
+ supportedUrls = {};
178
+ ai;
179
+ config;
180
+ modelId;
181
+ constructor(ai, config) {
182
+ this.ai = ai;
183
+ this.config = config;
184
+ this.modelId = this.ai.getName();
185
+ }
186
+ get provider() {
187
+ return this.ai.getName();
188
+ }
189
+ async doGenerate(options) {
190
+ const req = createChatRequest(options);
191
+ const res = await this.ai.chat(req, { stream: false });
192
+ const choice = res.results.at(0);
193
+ if (!choice) throw new Error("No choice returned");
194
+ const content = [];
195
+ if (choice.content) content.push({
196
+ type: "text",
197
+ text: choice.content
198
+ });
199
+ if (choice.functionCalls) for (const tc of choice.functionCalls) content.push({
200
+ type: "tool-call",
201
+ toolCallId: tc.id,
202
+ toolName: tc.function.name,
203
+ input: typeof tc.function.params === "string" ? tc.function.params : JSON.stringify(tc.function.params)
204
+ });
205
+ const providerMetadata = createProviderMetadata(res, this.provider);
206
+ const response = createResponseMetadata(res);
207
+ return {
208
+ content,
209
+ finishReason: mapAxFinishReason(choice.finishReason),
210
+ usage: createUsage(res.modelUsage?.tokens),
211
+ ...providerMetadata ? { providerMetadata } : {},
212
+ ...response ? { response } : {},
213
+ warnings: []
214
+ };
215
+ }
216
+ async doStream(options) {
217
+ const req = createChatRequest(options);
218
+ return { stream: (await this.ai.chat(req, { stream: true })).pipeThrough(new AxToSDKTransformer(this.provider)) };
219
+ }
261
220
  };
262
221
  function prepareToolsAndToolChoice(tools, toolChoice) {
263
- if (!tools || tools.length === 0) {
264
- return {};
265
- }
266
- const functions = tools.map((f) => ({
267
- name: f.name,
268
- description: f.description ?? "",
269
- parameters: f.inputSchema
270
- }));
271
- if (!toolChoice) {
272
- return { functions };
273
- }
274
- const type = toolChoice.type;
275
- switch (type) {
276
- case "auto":
277
- return { functions, functionCall: "auto" };
278
- case "none":
279
- return { functions, functionCall: "none" };
280
- case "required":
281
- return { functions, functionCall: "required" };
282
- case "tool":
283
- return {
284
- functions,
285
- functionCall: {
286
- type: "function",
287
- function: { name: toolChoice.toolName }
288
- }
289
- };
290
- default: {
291
- const ExhaustiveCheck = type;
292
- throw new Error(`Unsupported tool choice type: ${ExhaustiveCheck}`);
293
- }
294
- }
222
+ if (!tools || tools.length === 0) return {};
223
+ const functions = tools.map((f) => ({
224
+ name: f.name,
225
+ description: f.description ?? "",
226
+ parameters: f.inputSchema
227
+ }));
228
+ if (!toolChoice) return { functions };
229
+ const type = toolChoice.type;
230
+ switch (type) {
231
+ case "auto": return {
232
+ functions,
233
+ functionCall: "auto"
234
+ };
235
+ case "none": return {
236
+ functions,
237
+ functionCall: "none"
238
+ };
239
+ case "required": return {
240
+ functions,
241
+ functionCall: "required"
242
+ };
243
+ case "tool": return {
244
+ functions,
245
+ functionCall: {
246
+ type: "function",
247
+ function: { name: toolChoice.toolName }
248
+ }
249
+ };
250
+ default: throw new Error(`Unsupported tool choice type: ${type}`);
251
+ }
295
252
  }
296
253
  function convertToAxChatPrompt(prompt) {
297
- const messages = [];
298
- for (const { role, content } of prompt) {
299
- switch (role) {
300
- case "system": {
301
- messages.push({ role: "system", content });
302
- break;
303
- }
304
- case "user": {
305
- messages.push({
306
- role: "user",
307
- content: content.map((part) => {
308
- switch (part.type) {
309
- case "text": {
310
- return { type: "text", text: part.text };
311
- }
312
- case "file": {
313
- if (!part.mediaType) {
314
- throw new Error("File part must have a mediaType");
315
- }
316
- let dataContent;
317
- if (typeof part.data === "string") {
318
- dataContent = part.data;
319
- } else if (part.data instanceof URL) {
320
- dataContent = part.data.toString();
321
- } else {
322
- dataContent = Buffer.from(part.data).toString("base64");
323
- }
324
- return {
325
- type: "image",
326
- mimeType: part.mediaType,
327
- image: dataContent
328
- };
329
- }
330
- default:
331
- throw new Error(`Unsupported part: ${part}`);
332
- }
333
- })
334
- });
335
- break;
336
- }
337
- case "assistant": {
338
- let text = "";
339
- const toolCalls = [];
340
- for (const part of content) {
341
- switch (part.type) {
342
- case "text": {
343
- text += part.text;
344
- break;
345
- }
346
- case "tool-call": {
347
- toolCalls.push({
348
- id: part.toolCallId,
349
- type: "function",
350
- function: {
351
- name: part.toolName,
352
- params: typeof part.input === "string" ? JSON.parse(part.input) : part.input
353
- }
354
- });
355
- break;
356
- }
357
- default: {
358
- const ExhaustiveCheck = part;
359
- throw new Error(`Unsupported part: ${ExhaustiveCheck}`);
360
- }
361
- }
362
- }
363
- const functionCalls = toolCalls.length === 0 ? void 0 : toolCalls;
364
- if (functionCalls || text.length > 0) {
365
- messages.push({
366
- role: "assistant",
367
- content: text,
368
- functionCalls
369
- });
370
- }
371
- break;
372
- }
373
- case "tool": {
374
- for (const part of content) {
375
- if (part.type !== "tool-result") {
376
- throw new Error(`Unsupported part: ${part.type}`);
377
- }
378
- messages.push({
379
- role: "function",
380
- functionId: part.toolCallId,
381
- result: typeof part.output === "object" && part.output?.type === "text" ? part.output.value : JSON.stringify(part.output, null, 2)
382
- });
383
- }
384
- break;
385
- }
386
- default: {
387
- const ExhaustiveCheck = role;
388
- throw new Error(`Unsupported role: ${ExhaustiveCheck}`);
389
- }
390
- }
391
- }
392
- return messages;
254
+ const messages = [];
255
+ for (const { role, content } of prompt) switch (role) {
256
+ case "system":
257
+ messages.push({
258
+ role: "system",
259
+ content
260
+ });
261
+ break;
262
+ case "user":
263
+ messages.push({
264
+ role: "user",
265
+ content: content.map((part) => {
266
+ switch (part.type) {
267
+ case "text": return {
268
+ type: "text",
269
+ text: part.text
270
+ };
271
+ case "file": {
272
+ if (!part.mediaType) throw new Error("File part must have a mediaType");
273
+ if (part.data instanceof URL) return {
274
+ type: "file",
275
+ fileUri: part.data.toString(),
276
+ filename: part.filename,
277
+ mimeType: part.mediaType
278
+ };
279
+ const data = typeof part.data === "string" ? part.data : Buffer.from(part.data).toString("base64");
280
+ if (part.mediaType.startsWith("image/")) return {
281
+ type: "image",
282
+ image: data,
283
+ mimeType: part.mediaType
284
+ };
285
+ return {
286
+ type: "file",
287
+ data,
288
+ filename: part.filename,
289
+ mimeType: part.mediaType
290
+ };
291
+ }
292
+ default: throw new Error(`Unsupported part: ${part}`);
293
+ }
294
+ })
295
+ });
296
+ break;
297
+ case "assistant": {
298
+ let text = "";
299
+ const toolCalls = [];
300
+ for (const part of content) switch (part.type) {
301
+ case "text":
302
+ text += part.text;
303
+ break;
304
+ case "tool-call":
305
+ toolCalls.push({
306
+ id: part.toolCallId,
307
+ type: "function",
308
+ function: {
309
+ name: part.toolName,
310
+ params: typeof part.input === "string" ? JSON.parse(part.input) : part.input
311
+ }
312
+ });
313
+ break;
314
+ default: throw new Error(`Unsupported part: ${part}`);
315
+ }
316
+ const functionCalls = toolCalls.length === 0 ? void 0 : toolCalls;
317
+ if (functionCalls || text.length > 0) messages.push({
318
+ role: "assistant",
319
+ content: text,
320
+ functionCalls
321
+ });
322
+ break;
323
+ }
324
+ case "tool":
325
+ for (const part of content) {
326
+ if (part.type !== "tool-result") throw new Error(`Unsupported part: ${part.type}`);
327
+ messages.push({
328
+ role: "function",
329
+ functionId: part.toolCallId,
330
+ result: typeof part.output === "object" && part.output?.type === "text" ? part.output.value : JSON.stringify(part.output, null, 2)
331
+ });
332
+ }
333
+ break;
334
+ default: throw new Error(`Unsupported role: ${role}`);
335
+ }
336
+ return messages;
393
337
  }
394
338
  function mapAxFinishReason(finishReason) {
395
- const raw = finishReason;
396
- switch (finishReason) {
397
- case "stop":
398
- return { unified: "stop", raw };
399
- case "length":
400
- return { unified: "length", raw };
401
- case "function_call":
402
- return { unified: "tool-calls", raw };
403
- case "content_filter":
404
- return { unified: "content-filter", raw };
405
- case "error":
406
- return { unified: "error", raw };
407
- default:
408
- return { unified: "other", raw };
409
- }
339
+ const raw = finishReason;
340
+ switch (finishReason) {
341
+ case "stop": return {
342
+ unified: "stop",
343
+ raw
344
+ };
345
+ case "length": return {
346
+ unified: "length",
347
+ raw
348
+ };
349
+ case "function_call": return {
350
+ unified: "tool-calls",
351
+ raw
352
+ };
353
+ case "content_filter": return {
354
+ unified: "content-filter",
355
+ raw
356
+ };
357
+ case "error": return {
358
+ unified: "error",
359
+ raw
360
+ };
361
+ default: return {
362
+ unified: "other",
363
+ raw
364
+ };
365
+ }
410
366
  }
411
- function createChatRequest({
412
- tools,
413
- toolChoice,
414
- prompt,
415
- maxOutputTokens,
416
- temperature,
417
- topP,
418
- frequencyPenalty,
419
- presencePenalty
420
- //seed,
421
- }) {
422
- const req = {
423
- chatPrompt: convertToAxChatPrompt(prompt),
424
- ...frequencyPenalty != null ? { frequencyPenalty } : {},
425
- ...presencePenalty != null ? { presencePenalty } : {},
426
- ...maxOutputTokens != null ? { maxTokens: maxOutputTokens } : {},
427
- ...temperature != null ? { temperature } : {},
428
- ...topP != null ? { topP } : {}
429
- };
430
- if (tools && tools.length > 0) {
431
- const functionTools = tools.filter(
432
- (tool) => tool.type === "function"
433
- );
434
- return { ...req, ...prepareToolsAndToolChoice(functionTools, toolChoice) };
435
- }
436
- return req;
367
+ function createChatRequest({ tools, toolChoice, prompt, maxOutputTokens, temperature, topP, frequencyPenalty, presencePenalty }) {
368
+ const req = {
369
+ chatPrompt: convertToAxChatPrompt(prompt),
370
+ ...frequencyPenalty != null ? { frequencyPenalty } : {},
371
+ ...presencePenalty != null ? { presencePenalty } : {},
372
+ ...maxOutputTokens != null ? { maxTokens: maxOutputTokens } : {},
373
+ ...temperature != null ? { temperature } : {},
374
+ ...topP != null ? { topP } : {}
375
+ };
376
+ if (tools && tools.length > 0) {
377
+ const functionTools = tools.filter((tool) => tool.type === "function");
378
+ return {
379
+ ...req,
380
+ ...prepareToolsAndToolChoice(functionTools, toolChoice)
381
+ };
382
+ }
383
+ return req;
437
384
  }
438
385
  function createUsage(tokens) {
439
- return {
440
- inputTokens: {
441
- total: tokens?.promptTokens,
442
- noCache: void 0,
443
- cacheRead: tokens?.cacheReadTokens,
444
- cacheWrite: tokens?.cacheCreationTokens
445
- },
446
- outputTokens: {
447
- total: tokens?.completionTokens,
448
- text: void 0,
449
- reasoning: tokens?.reasoningTokens
450
- }
451
- };
386
+ return {
387
+ inputTokens: {
388
+ total: tokens?.promptTokens,
389
+ noCache: void 0,
390
+ cacheRead: tokens?.cacheReadTokens,
391
+ cacheWrite: tokens?.cacheCreationTokens
392
+ },
393
+ outputTokens: {
394
+ total: tokens?.completionTokens,
395
+ text: void 0,
396
+ reasoning: tokens?.reasoningTokens
397
+ }
398
+ };
452
399
  }
453
400
  function addUsage(usage, tokens) {
454
- return {
455
- inputTokens: {
456
- ...usage.inputTokens,
457
- total: (usage.inputTokens.total ?? 0) + (tokens?.promptTokens ?? 0),
458
- cacheRead: addOptionalUsage(
459
- usage.inputTokens.cacheRead,
460
- tokens?.cacheReadTokens
461
- ),
462
- cacheWrite: addOptionalUsage(
463
- usage.inputTokens.cacheWrite,
464
- tokens?.cacheCreationTokens
465
- )
466
- },
467
- outputTokens: {
468
- ...usage.outputTokens,
469
- total: (usage.outputTokens.total ?? 0) + (tokens?.completionTokens ?? 0),
470
- reasoning: addOptionalUsage(
471
- usage.outputTokens.reasoning,
472
- tokens?.reasoningTokens
473
- )
474
- }
475
- };
401
+ return {
402
+ inputTokens: {
403
+ ...usage.inputTokens,
404
+ total: (usage.inputTokens.total ?? 0) + (tokens?.promptTokens ?? 0),
405
+ cacheRead: addOptionalUsage(usage.inputTokens.cacheRead, tokens?.cacheReadTokens),
406
+ cacheWrite: addOptionalUsage(usage.inputTokens.cacheWrite, tokens?.cacheCreationTokens)
407
+ },
408
+ outputTokens: {
409
+ ...usage.outputTokens,
410
+ total: (usage.outputTokens.total ?? 0) + (tokens?.completionTokens ?? 0),
411
+ reasoning: addOptionalUsage(usage.outputTokens.reasoning, tokens?.reasoningTokens)
412
+ }
413
+ };
476
414
  }
477
415
  function addOptionalUsage(current, next) {
478
- if (next === void 0) {
479
- return current;
480
- }
481
- return (current ?? 0) + next;
416
+ if (next === void 0) return current;
417
+ return (current ?? 0) + next;
482
418
  }
483
419
  var AxToSDKTransformer = class extends TransformStream {
484
- usage = {
485
- inputTokens: {
486
- total: 0,
487
- noCache: void 0,
488
- cacheRead: void 0,
489
- cacheWrite: void 0
490
- },
491
- outputTokens: {
492
- total: 0,
493
- text: void 0,
494
- reasoning: void 0
495
- }
496
- };
497
- finishReason = {
498
- unified: "other",
499
- raw: void 0
500
- };
501
- functionCalls = [];
502
- providerMetadata;
503
- responseMetadataSent = false;
504
- hasStarted = false;
505
- textStarted = false;
506
- constructor(provider) {
507
- const providerName = provider;
508
- const transformer = {
509
- transform: (chunk, controller) => {
510
- if (!this.hasStarted) {
511
- controller.enqueue({
512
- type: "stream-start",
513
- warnings: []
514
- });
515
- this.hasStarted = true;
516
- }
517
- const chunkProviderMetadata = createProviderMetadata(
518
- chunk,
519
- providerName
520
- );
521
- this.providerMetadata = mergeProviderMetadata(
522
- this.providerMetadata,
523
- chunkProviderMetadata
524
- );
525
- const responseMetadata = createResponseMetadata(chunk);
526
- if (!this.responseMetadataSent && responseMetadata) {
527
- controller.enqueue({
528
- type: "response-metadata",
529
- ...responseMetadata
530
- });
531
- this.responseMetadataSent = true;
532
- }
533
- const choice = chunk.results.at(0);
534
- if (!choice) {
535
- if (this.textStarted) {
536
- controller.enqueue({
537
- type: "text-end",
538
- id: "text-content"
539
- });
540
- }
541
- const val = {
542
- type: "finish",
543
- finishReason: this.finishReason,
544
- usage: this.usage,
545
- ...this.providerMetadata ? { providerMetadata: this.providerMetadata } : {}
546
- };
547
- controller.enqueue(val);
548
- return;
549
- }
550
- if (chunk.modelUsage) {
551
- this.usage = addUsage(this.usage, chunk.modelUsage.tokens);
552
- }
553
- if (choice.functionCalls) {
554
- for (const fc of choice.functionCalls) {
555
- const index = this.functionCalls.findIndex(
556
- (f) => f.toolCallId === fc.id
557
- );
558
- if (index === -1) {
559
- this.functionCalls.push({
560
- type: "tool-call",
561
- toolCallId: fc.id,
562
- toolName: fc.function.name,
563
- input: typeof fc.function.params === "string" ? fc.function.params : JSON.stringify(fc.function.params)
564
- });
565
- } else {
566
- const obj = this.functionCalls[index];
567
- if (!obj) {
568
- continue;
569
- }
570
- if (typeof fc.function.params === "string") {
571
- obj.input = (obj.input || "") + fc.function.params;
572
- } else {
573
- obj.input = JSON.stringify(fc.function.params);
574
- }
575
- }
576
- this.finishReason = { unified: "tool-calls", raw: "function_call" };
577
- }
578
- }
579
- if (choice.content && choice.content.length > 0) {
580
- if (!this.textStarted) {
581
- controller.enqueue({
582
- type: "text-start",
583
- id: "text-content"
584
- });
585
- this.textStarted = true;
586
- }
587
- controller.enqueue({
588
- type: "text-delta",
589
- id: "text-content",
590
- delta: choice.content ?? ""
591
- });
592
- this.finishReason = mapAxFinishReason(choice.finishReason);
593
- }
594
- },
595
- flush: (controller) => {
596
- if (this.textStarted) {
597
- controller.enqueue({
598
- type: "text-end",
599
- id: "text-content"
600
- });
601
- }
602
- for (const fc of this.functionCalls) {
603
- controller.enqueue(fc);
604
- }
605
- const val = {
606
- type: "finish",
607
- finishReason: this.finishReason,
608
- usage: this.usage,
609
- ...this.providerMetadata ? { providerMetadata: this.providerMetadata } : {}
610
- };
611
- controller.enqueue(val);
612
- controller.terminate();
613
- }
614
- };
615
- super(transformer);
616
- }
420
+ usage = {
421
+ inputTokens: {
422
+ total: 0,
423
+ noCache: void 0,
424
+ cacheRead: void 0,
425
+ cacheWrite: void 0
426
+ },
427
+ outputTokens: {
428
+ total: 0,
429
+ text: void 0,
430
+ reasoning: void 0
431
+ }
432
+ };
433
+ finishReason = {
434
+ unified: "other",
435
+ raw: void 0
436
+ };
437
+ functionCalls = [];
438
+ providerMetadata;
439
+ responseMetadataSent = false;
440
+ hasStarted = false;
441
+ textStarted = false;
442
+ constructor(provider) {
443
+ const providerName = provider;
444
+ super({
445
+ transform: (chunk, controller) => {
446
+ if (!this.hasStarted) {
447
+ controller.enqueue({
448
+ type: "stream-start",
449
+ warnings: []
450
+ });
451
+ this.hasStarted = true;
452
+ }
453
+ const chunkProviderMetadata = createProviderMetadata(chunk, providerName);
454
+ this.providerMetadata = mergeProviderMetadata(this.providerMetadata, chunkProviderMetadata);
455
+ const responseMetadata = createResponseMetadata(chunk);
456
+ if (!this.responseMetadataSent && responseMetadata) {
457
+ controller.enqueue({
458
+ type: "response-metadata",
459
+ ...responseMetadata
460
+ });
461
+ this.responseMetadataSent = true;
462
+ }
463
+ const choice = chunk.results.at(0);
464
+ if (!choice) {
465
+ if (this.textStarted) controller.enqueue({
466
+ type: "text-end",
467
+ id: "text-content"
468
+ });
469
+ const val = {
470
+ type: "finish",
471
+ finishReason: this.finishReason,
472
+ usage: this.usage,
473
+ ...this.providerMetadata ? { providerMetadata: this.providerMetadata } : {}
474
+ };
475
+ controller.enqueue(val);
476
+ return;
477
+ }
478
+ if (chunk.modelUsage) this.usage = addUsage(this.usage, chunk.modelUsage.tokens);
479
+ if (choice.functionCalls) for (const fc of choice.functionCalls) {
480
+ const index = this.functionCalls.findIndex((f) => f.toolCallId === fc.id);
481
+ if (index === -1) this.functionCalls.push({
482
+ type: "tool-call",
483
+ toolCallId: fc.id,
484
+ toolName: fc.function.name,
485
+ input: typeof fc.function.params === "string" ? fc.function.params : JSON.stringify(fc.function.params)
486
+ });
487
+ else {
488
+ const obj = this.functionCalls[index];
489
+ if (!obj) continue;
490
+ if (typeof fc.function.params === "string") obj.input = (obj.input || "") + fc.function.params;
491
+ else obj.input = JSON.stringify(fc.function.params);
492
+ }
493
+ this.finishReason = {
494
+ unified: "tool-calls",
495
+ raw: "function_call"
496
+ };
497
+ }
498
+ if (choice.content && choice.content.length > 0) {
499
+ if (!this.textStarted) {
500
+ controller.enqueue({
501
+ type: "text-start",
502
+ id: "text-content"
503
+ });
504
+ this.textStarted = true;
505
+ }
506
+ controller.enqueue({
507
+ type: "text-delta",
508
+ id: "text-content",
509
+ delta: choice.content ?? ""
510
+ });
511
+ this.finishReason = mapAxFinishReason(choice.finishReason);
512
+ }
513
+ },
514
+ flush: (controller) => {
515
+ if (this.textStarted) controller.enqueue({
516
+ type: "text-end",
517
+ id: "text-content"
518
+ });
519
+ for (const fc of this.functionCalls) controller.enqueue(fc);
520
+ const val = {
521
+ type: "finish",
522
+ finishReason: this.finishReason,
523
+ usage: this.usage,
524
+ ...this.providerMetadata ? { providerMetadata: this.providerMetadata } : {}
525
+ };
526
+ controller.enqueue(val);
527
+ controller.terminate();
528
+ }
529
+ });
530
+ }
617
531
  };
618
532
  function convertToZodSchema(jsonSchema) {
619
- const { type, properties, required, items } = jsonSchema;
620
- switch (type) {
621
- case "string":
622
- return import_zod.z.string();
623
- case "number":
624
- return import_zod.z.number();
625
- case "boolean":
626
- return import_zod.z.boolean();
627
- case "array":
628
- if (!items) {
629
- throw new Error("Array type must have 'items' property.");
630
- }
631
- return import_zod.z.array(convertToZodSchema(items));
632
- case "object": {
633
- if (!properties) {
634
- throw new Error("Object type must have 'properties' property.");
635
- }
636
- const shape = {};
637
- for (const [key, value] of Object.entries(properties)) {
638
- const schema = convertToZodSchema(value);
639
- let val = required?.includes(key) ? schema : schema.optional();
640
- val = value.description ? val.describe(value.description) : val;
641
- shape[key] = val;
642
- }
643
- return import_zod.z.object(shape);
644
- }
645
- default:
646
- throw new Error(`Unsupported type: ${type}`);
647
- }
533
+ const { type, properties, required, items } = jsonSchema;
534
+ switch (type) {
535
+ case "string": return zod.z.string();
536
+ case "number": return zod.z.number();
537
+ case "boolean": return zod.z.boolean();
538
+ case "array":
539
+ if (!items) throw new Error("Array type must have 'items' property.");
540
+ return zod.z.array(convertToZodSchema(items));
541
+ case "object": {
542
+ if (!properties) throw new Error("Object type must have 'properties' property.");
543
+ const shape = {};
544
+ for (const [key, value] of Object.entries(properties)) {
545
+ const schema = convertToZodSchema(value);
546
+ let val = required?.includes(key) ? schema : schema.optional();
547
+ val = value.description ? val.describe(value.description) : val;
548
+ shape[key] = val;
549
+ }
550
+ return zod.z.object(shape);
551
+ }
552
+ default: throw new Error(`Unsupported type: ${type}`);
553
+ }
648
554
  }
649
- // Annotate the CommonJS export names for ESM import in node:
650
- 0 && (module.exports = {
651
- AxAIProvider,
652
- AxAgentProvider
653
- });
555
+
556
+ //#endregion
557
+ exports.AxAIProvider = AxAIProvider;
558
+ exports.AxAgentProvider = AxAgentProvider;
654
559
  //# sourceMappingURL=index.cjs.map