workers-ai-provider 0.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/LICENSE +21 -0
- package/README.md +56 -0
- package/dist/index.d.ts +53 -0
- package/dist/index.js +614 -0
- package/dist/index.js.map +1 -0
- package/package.json +32 -0
- package/src/convert-to-workersai-chat-messages.ts +106 -0
- package/src/index.ts +62 -0
- package/src/map-workersai-finish-reason.ts +17 -0
- package/src/workersai-chat-language-model.ts +283 -0
- package/src/workersai-chat-prompt.ts +33 -0
- package/src/workersai-chat-settings.ts +8 -0
- package/src/workersai-error.ts +17 -0
package/dist/index.js
ADDED
@@ -0,0 +1,614 @@
|
|
1
|
+
var __create = Object.create;
|
2
|
+
var __defProp = Object.defineProperty;
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
7
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
8
|
+
var __commonJS = (cb, mod) => function __require() {
|
9
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
10
|
+
};
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
13
|
+
for (let key of __getOwnPropNames(from))
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
16
|
+
}
|
17
|
+
return to;
|
18
|
+
};
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
20
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
21
|
+
// file that has been converted to a CommonJS file using a Babel-
|
22
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
23
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
24
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
25
|
+
mod
|
26
|
+
));
|
27
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
28
|
+
|
29
|
+
// node_modules/secure-json-parse/index.js
|
30
|
+
var require_secure_json_parse = __commonJS({
|
31
|
+
"node_modules/secure-json-parse/index.js"(exports, module) {
|
32
|
+
"use strict";
|
33
|
+
var hasBuffer = typeof Buffer !== "undefined";
|
34
|
+
var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
|
35
|
+
var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
|
36
|
+
function _parse(text, reviver, options) {
|
37
|
+
if (options == null) {
|
38
|
+
if (reviver !== null && typeof reviver === "object") {
|
39
|
+
options = reviver;
|
40
|
+
reviver = void 0;
|
41
|
+
}
|
42
|
+
}
|
43
|
+
if (hasBuffer && Buffer.isBuffer(text)) {
|
44
|
+
text = text.toString();
|
45
|
+
}
|
46
|
+
if (text && text.charCodeAt(0) === 65279) {
|
47
|
+
text = text.slice(1);
|
48
|
+
}
|
49
|
+
const obj = JSON.parse(text, reviver);
|
50
|
+
if (obj === null || typeof obj !== "object") {
|
51
|
+
return obj;
|
52
|
+
}
|
53
|
+
const protoAction = options && options.protoAction || "error";
|
54
|
+
const constructorAction = options && options.constructorAction || "error";
|
55
|
+
if (protoAction === "ignore" && constructorAction === "ignore") {
|
56
|
+
return obj;
|
57
|
+
}
|
58
|
+
if (protoAction !== "ignore" && constructorAction !== "ignore") {
|
59
|
+
if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
|
60
|
+
return obj;
|
61
|
+
}
|
62
|
+
} else if (protoAction !== "ignore" && constructorAction === "ignore") {
|
63
|
+
if (suspectProtoRx.test(text) === false) {
|
64
|
+
return obj;
|
65
|
+
}
|
66
|
+
} else {
|
67
|
+
if (suspectConstructorRx.test(text) === false) {
|
68
|
+
return obj;
|
69
|
+
}
|
70
|
+
}
|
71
|
+
return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
|
72
|
+
}
|
73
|
+
function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
|
74
|
+
let next = [obj];
|
75
|
+
while (next.length) {
|
76
|
+
const nodes = next;
|
77
|
+
next = [];
|
78
|
+
for (const node of nodes) {
|
79
|
+
if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
|
80
|
+
if (safe === true) {
|
81
|
+
return null;
|
82
|
+
} else if (protoAction === "error") {
|
83
|
+
throw new SyntaxError("Object contains forbidden prototype property");
|
84
|
+
}
|
85
|
+
delete node.__proto__;
|
86
|
+
}
|
87
|
+
if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
|
88
|
+
if (safe === true) {
|
89
|
+
return null;
|
90
|
+
} else if (constructorAction === "error") {
|
91
|
+
throw new SyntaxError("Object contains forbidden prototype property");
|
92
|
+
}
|
93
|
+
delete node.constructor;
|
94
|
+
}
|
95
|
+
for (const key in node) {
|
96
|
+
const value = node[key];
|
97
|
+
if (value && typeof value === "object") {
|
98
|
+
next.push(value);
|
99
|
+
}
|
100
|
+
}
|
101
|
+
}
|
102
|
+
}
|
103
|
+
return obj;
|
104
|
+
}
|
105
|
+
function parse(text, reviver, options) {
|
106
|
+
const stackTraceLimit = Error.stackTraceLimit;
|
107
|
+
Error.stackTraceLimit = 0;
|
108
|
+
try {
|
109
|
+
return _parse(text, reviver, options);
|
110
|
+
} finally {
|
111
|
+
Error.stackTraceLimit = stackTraceLimit;
|
112
|
+
}
|
113
|
+
}
|
114
|
+
function safeParse(text, reviver) {
|
115
|
+
const stackTraceLimit = Error.stackTraceLimit;
|
116
|
+
Error.stackTraceLimit = 0;
|
117
|
+
try {
|
118
|
+
return _parse(text, reviver, { safe: true });
|
119
|
+
} catch (_e) {
|
120
|
+
return null;
|
121
|
+
} finally {
|
122
|
+
Error.stackTraceLimit = stackTraceLimit;
|
123
|
+
}
|
124
|
+
}
|
125
|
+
module.exports = parse;
|
126
|
+
module.exports.default = parse;
|
127
|
+
module.exports.parse = parse;
|
128
|
+
module.exports.safeParse = safeParse;
|
129
|
+
module.exports.scan = filter;
|
130
|
+
}
|
131
|
+
});
|
132
|
+
|
133
|
+
// src/workersai-chat-language-model.ts
|
134
|
+
import {
|
135
|
+
UnsupportedFunctionalityError as UnsupportedFunctionalityError2
|
136
|
+
} from "@ai-sdk/provider";
|
137
|
+
import { z as z2 } from "zod";
|
138
|
+
|
139
|
+
// src/convert-to-workersai-chat-messages.ts
|
140
|
+
import {
|
141
|
+
UnsupportedFunctionalityError
|
142
|
+
} from "@ai-sdk/provider";
|
143
|
+
function convertToWorkersAIChatMessages(prompt) {
|
144
|
+
const messages = [];
|
145
|
+
for (const { role, content } of prompt) {
|
146
|
+
switch (role) {
|
147
|
+
case "system": {
|
148
|
+
messages.push({ role: "system", content });
|
149
|
+
break;
|
150
|
+
}
|
151
|
+
case "user": {
|
152
|
+
messages.push({
|
153
|
+
role: "user",
|
154
|
+
content: content.map((part) => {
|
155
|
+
switch (part.type) {
|
156
|
+
case "text": {
|
157
|
+
return part.text;
|
158
|
+
}
|
159
|
+
case "image": {
|
160
|
+
throw new UnsupportedFunctionalityError({
|
161
|
+
functionality: "image-part"
|
162
|
+
});
|
163
|
+
}
|
164
|
+
}
|
165
|
+
}).join("")
|
166
|
+
});
|
167
|
+
break;
|
168
|
+
}
|
169
|
+
case "assistant": {
|
170
|
+
let text = "";
|
171
|
+
const toolCalls = [];
|
172
|
+
for (const part of content) {
|
173
|
+
switch (part.type) {
|
174
|
+
case "text": {
|
175
|
+
text += part.text;
|
176
|
+
break;
|
177
|
+
}
|
178
|
+
case "tool-call": {
|
179
|
+
toolCalls.push({
|
180
|
+
id: part.toolCallId,
|
181
|
+
type: "function",
|
182
|
+
function: {
|
183
|
+
name: part.toolName,
|
184
|
+
arguments: JSON.stringify(part.args)
|
185
|
+
}
|
186
|
+
});
|
187
|
+
break;
|
188
|
+
}
|
189
|
+
default: {
|
190
|
+
const _exhaustiveCheck = part;
|
191
|
+
throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
|
192
|
+
}
|
193
|
+
}
|
194
|
+
}
|
195
|
+
messages.push({
|
196
|
+
role: "assistant",
|
197
|
+
content: text,
|
198
|
+
tool_calls: toolCalls.length > 0 ? toolCalls.map(({ function: { name, arguments: args } }) => ({
|
199
|
+
id: "null",
|
200
|
+
type: "function",
|
201
|
+
function: { name, arguments: args }
|
202
|
+
})) : void 0
|
203
|
+
});
|
204
|
+
break;
|
205
|
+
}
|
206
|
+
case "tool": {
|
207
|
+
for (const toolResponse of content) {
|
208
|
+
messages.push({
|
209
|
+
role: "tool",
|
210
|
+
name: toolResponse.toolName,
|
211
|
+
content: JSON.stringify(toolResponse.result)
|
212
|
+
});
|
213
|
+
}
|
214
|
+
break;
|
215
|
+
}
|
216
|
+
default: {
|
217
|
+
const _exhaustiveCheck = role;
|
218
|
+
throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
|
219
|
+
}
|
220
|
+
}
|
221
|
+
}
|
222
|
+
return messages;
|
223
|
+
}
|
224
|
+
|
225
|
+
// node_modules/@ai-sdk/provider-utils/node_modules/nanoid/non-secure/index.js
|
226
|
+
var customAlphabet = (alphabet, defaultSize = 21) => {
|
227
|
+
return (size = defaultSize) => {
|
228
|
+
let id = "";
|
229
|
+
let i = size;
|
230
|
+
while (i--) {
|
231
|
+
id += alphabet[Math.random() * alphabet.length | 0];
|
232
|
+
}
|
233
|
+
return id;
|
234
|
+
};
|
235
|
+
};
|
236
|
+
|
237
|
+
// node_modules/@ai-sdk/provider-utils/dist/index.mjs
|
238
|
+
var import_secure_json_parse = __toESM(require_secure_json_parse(), 1);
|
239
|
+
import { LoadAPIKeyError } from "@ai-sdk/provider";
|
240
|
+
import { LoadSettingError } from "@ai-sdk/provider";
|
241
|
+
import { JSONParseError, TypeValidationError as TypeValidationError2 } from "@ai-sdk/provider";
|
242
|
+
import { TypeValidationError } from "@ai-sdk/provider";
|
243
|
+
import { APICallError } from "@ai-sdk/provider";
|
244
|
+
import { APICallError as APICallError2, EmptyResponseBodyError } from "@ai-sdk/provider";
|
245
|
+
function extractResponseHeaders(response) {
|
246
|
+
const headers = {};
|
247
|
+
response.headers.forEach((value, key) => {
|
248
|
+
headers[key] = value;
|
249
|
+
});
|
250
|
+
return headers;
|
251
|
+
}
|
252
|
+
var generateId = customAlphabet(
|
253
|
+
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
254
|
+
7
|
255
|
+
);
|
256
|
+
var validatorSymbol = Symbol("vercel.ai.validator");
|
257
|
+
function validator(validate) {
|
258
|
+
return { [validatorSymbol]: true, validate };
|
259
|
+
}
|
260
|
+
function isValidator(value) {
|
261
|
+
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
|
262
|
+
}
|
263
|
+
function zodValidator(zodSchema) {
|
264
|
+
return validator((value) => {
|
265
|
+
const result = zodSchema.safeParse(value);
|
266
|
+
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
267
|
+
});
|
268
|
+
}
|
269
|
+
function validateTypes({
|
270
|
+
value,
|
271
|
+
schema: inputSchema
|
272
|
+
}) {
|
273
|
+
const result = safeValidateTypes({ value, schema: inputSchema });
|
274
|
+
if (!result.success) {
|
275
|
+
throw new TypeValidationError({ value, cause: result.error });
|
276
|
+
}
|
277
|
+
return result.value;
|
278
|
+
}
|
279
|
+
function safeValidateTypes({
|
280
|
+
value,
|
281
|
+
schema: inputSchema
|
282
|
+
}) {
|
283
|
+
const schema = isValidator(inputSchema) ? inputSchema : zodValidator(inputSchema);
|
284
|
+
try {
|
285
|
+
if (schema.validate == null) {
|
286
|
+
return { success: true, value };
|
287
|
+
}
|
288
|
+
const validationResult = schema.validate(value);
|
289
|
+
if (validationResult.success) {
|
290
|
+
return validationResult;
|
291
|
+
}
|
292
|
+
return {
|
293
|
+
success: false,
|
294
|
+
error: new TypeValidationError({
|
295
|
+
value,
|
296
|
+
cause: validationResult.error
|
297
|
+
})
|
298
|
+
};
|
299
|
+
} catch (error) {
|
300
|
+
return {
|
301
|
+
success: false,
|
302
|
+
error: TypeValidationError.isTypeValidationError(error) ? error : new TypeValidationError({ value, cause: error })
|
303
|
+
};
|
304
|
+
}
|
305
|
+
}
|
306
|
+
function parseJSON({
|
307
|
+
text,
|
308
|
+
schema
|
309
|
+
}) {
|
310
|
+
try {
|
311
|
+
const value = import_secure_json_parse.default.parse(text);
|
312
|
+
if (schema == null) {
|
313
|
+
return value;
|
314
|
+
}
|
315
|
+
return validateTypes({ value, schema });
|
316
|
+
} catch (error) {
|
317
|
+
if (JSONParseError.isJSONParseError(error) || TypeValidationError2.isTypeValidationError(error)) {
|
318
|
+
throw error;
|
319
|
+
}
|
320
|
+
throw new JSONParseError({ text, cause: error });
|
321
|
+
}
|
322
|
+
}
|
323
|
+
var createJsonErrorResponseHandler = ({
|
324
|
+
errorSchema,
|
325
|
+
errorToMessage,
|
326
|
+
isRetryable
|
327
|
+
}) => async ({ response, url, requestBodyValues }) => {
|
328
|
+
const responseBody = await response.text();
|
329
|
+
const responseHeaders = extractResponseHeaders(response);
|
330
|
+
if (responseBody.trim() === "") {
|
331
|
+
return {
|
332
|
+
responseHeaders,
|
333
|
+
value: new APICallError2({
|
334
|
+
message: response.statusText,
|
335
|
+
url,
|
336
|
+
requestBodyValues,
|
337
|
+
statusCode: response.status,
|
338
|
+
responseHeaders,
|
339
|
+
responseBody,
|
340
|
+
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
|
341
|
+
})
|
342
|
+
};
|
343
|
+
}
|
344
|
+
try {
|
345
|
+
const parsedError = parseJSON({
|
346
|
+
text: responseBody,
|
347
|
+
schema: errorSchema
|
348
|
+
});
|
349
|
+
return {
|
350
|
+
responseHeaders,
|
351
|
+
value: new APICallError2({
|
352
|
+
message: errorToMessage(parsedError),
|
353
|
+
url,
|
354
|
+
requestBodyValues,
|
355
|
+
statusCode: response.status,
|
356
|
+
responseHeaders,
|
357
|
+
responseBody,
|
358
|
+
data: parsedError,
|
359
|
+
isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
|
360
|
+
})
|
361
|
+
};
|
362
|
+
} catch (parseError) {
|
363
|
+
return {
|
364
|
+
responseHeaders,
|
365
|
+
value: new APICallError2({
|
366
|
+
message: response.statusText,
|
367
|
+
url,
|
368
|
+
requestBodyValues,
|
369
|
+
statusCode: response.status,
|
370
|
+
responseHeaders,
|
371
|
+
responseBody,
|
372
|
+
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
|
373
|
+
})
|
374
|
+
};
|
375
|
+
}
|
376
|
+
};
|
377
|
+
|
378
|
+
// src/workersai-error.ts
|
379
|
+
import { z } from "zod";
|
380
|
+
var workersAIErrorDataSchema = z.object({
|
381
|
+
object: z.literal("error"),
|
382
|
+
message: z.string(),
|
383
|
+
type: z.string(),
|
384
|
+
param: z.string().nullable(),
|
385
|
+
code: z.string().nullable()
|
386
|
+
});
|
387
|
+
var workersAIFailedResponseHandler = createJsonErrorResponseHandler({
|
388
|
+
errorSchema: workersAIErrorDataSchema,
|
389
|
+
errorToMessage: (data) => data.message
|
390
|
+
});
|
391
|
+
|
392
|
+
// src/workersai-chat-language-model.ts
|
393
|
+
import { events } from "fetch-event-stream";
|
394
|
+
var WorkersAIChatLanguageModel = class {
|
395
|
+
constructor(modelId, settings, config) {
|
396
|
+
__publicField(this, "specificationVersion", "v1");
|
397
|
+
__publicField(this, "defaultObjectGenerationMode", "json");
|
398
|
+
__publicField(this, "modelId");
|
399
|
+
__publicField(this, "settings");
|
400
|
+
__publicField(this, "config");
|
401
|
+
this.modelId = modelId;
|
402
|
+
this.settings = settings;
|
403
|
+
this.config = config;
|
404
|
+
}
|
405
|
+
get provider() {
|
406
|
+
return this.config.provider;
|
407
|
+
}
|
408
|
+
getArgs({
|
409
|
+
mode,
|
410
|
+
prompt,
|
411
|
+
maxTokens,
|
412
|
+
temperature,
|
413
|
+
topP,
|
414
|
+
frequencyPenalty,
|
415
|
+
presencePenalty,
|
416
|
+
seed
|
417
|
+
}) {
|
418
|
+
const type = mode.type;
|
419
|
+
const warnings = [];
|
420
|
+
if (frequencyPenalty != null) {
|
421
|
+
warnings.push({
|
422
|
+
type: "unsupported-setting",
|
423
|
+
setting: "frequencyPenalty"
|
424
|
+
});
|
425
|
+
}
|
426
|
+
if (presencePenalty != null) {
|
427
|
+
warnings.push({
|
428
|
+
type: "unsupported-setting",
|
429
|
+
setting: "presencePenalty"
|
430
|
+
});
|
431
|
+
}
|
432
|
+
const baseArgs = {
|
433
|
+
// model id:
|
434
|
+
model: this.modelId,
|
435
|
+
// model specific settings:
|
436
|
+
safe_prompt: this.settings.safePrompt,
|
437
|
+
// standardized settings:
|
438
|
+
max_tokens: maxTokens,
|
439
|
+
temperature,
|
440
|
+
top_p: topP,
|
441
|
+
random_seed: seed,
|
442
|
+
// messages:
|
443
|
+
messages: convertToWorkersAIChatMessages(prompt)
|
444
|
+
};
|
445
|
+
switch (type) {
|
446
|
+
case "regular": {
|
447
|
+
return {
|
448
|
+
args: { ...baseArgs, ...prepareToolsAndToolChoice(mode) },
|
449
|
+
warnings
|
450
|
+
};
|
451
|
+
}
|
452
|
+
case "object-json": {
|
453
|
+
return {
|
454
|
+
args: {
|
455
|
+
...baseArgs,
|
456
|
+
response_format: { type: "json_object" }
|
457
|
+
},
|
458
|
+
warnings
|
459
|
+
};
|
460
|
+
}
|
461
|
+
case "object-tool": {
|
462
|
+
return {
|
463
|
+
args: {
|
464
|
+
...baseArgs,
|
465
|
+
tool_choice: "any",
|
466
|
+
tools: [{ type: "function", function: mode.tool }]
|
467
|
+
},
|
468
|
+
warnings
|
469
|
+
};
|
470
|
+
}
|
471
|
+
case "object-grammar": {
|
472
|
+
throw new UnsupportedFunctionalityError2({
|
473
|
+
functionality: "object-grammar mode"
|
474
|
+
});
|
475
|
+
}
|
476
|
+
default: {
|
477
|
+
const _exhaustiveCheck = type;
|
478
|
+
throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
|
479
|
+
}
|
480
|
+
}
|
481
|
+
}
|
482
|
+
async doGenerate(options) {
|
483
|
+
const { args, warnings } = this.getArgs(options);
|
484
|
+
console.warn(warnings);
|
485
|
+
const response = await this.config.binding.run(args.model, {
|
486
|
+
messages: args.messages
|
487
|
+
});
|
488
|
+
return {
|
489
|
+
text: response.response,
|
490
|
+
finishReason: "stop",
|
491
|
+
rawCall: { rawPrompt: args.messages, rawSettings: args },
|
492
|
+
usage: {
|
493
|
+
promptTokens: 0,
|
494
|
+
completionTokens: 0
|
495
|
+
}
|
496
|
+
};
|
497
|
+
}
|
498
|
+
async doStream(options) {
|
499
|
+
const { args, warnings } = this.getArgs(options);
|
500
|
+
const response = await this.config.binding.run(args.model, {
|
501
|
+
messages: args.messages,
|
502
|
+
stream: true
|
503
|
+
});
|
504
|
+
return {
|
505
|
+
stream: response.pipeThrough(
|
506
|
+
new TransformStream({
|
507
|
+
async transform(chunk, controller) {
|
508
|
+
const chunkToText = new TextDecoder().decode(
|
509
|
+
chunk
|
510
|
+
);
|
511
|
+
const chunks = events(new Response(chunkToText));
|
512
|
+
for await (const singleChunk of chunks) {
|
513
|
+
if (!singleChunk.data) {
|
514
|
+
continue;
|
515
|
+
}
|
516
|
+
if (singleChunk.data === "[DONE]") {
|
517
|
+
controller.enqueue({
|
518
|
+
type: "finish",
|
519
|
+
finishReason: "stop",
|
520
|
+
usage: {
|
521
|
+
promptTokens: 0,
|
522
|
+
completionTokens: 0
|
523
|
+
}
|
524
|
+
});
|
525
|
+
return;
|
526
|
+
}
|
527
|
+
const data = JSON.parse(singleChunk.data);
|
528
|
+
console.log("data", data);
|
529
|
+
controller.enqueue({
|
530
|
+
type: "text-delta",
|
531
|
+
textDelta: data.response ?? "DATALOSS"
|
532
|
+
});
|
533
|
+
}
|
534
|
+
controller.enqueue({
|
535
|
+
type: "finish",
|
536
|
+
finishReason: "stop",
|
537
|
+
usage: {
|
538
|
+
promptTokens: 0,
|
539
|
+
completionTokens: 0
|
540
|
+
}
|
541
|
+
});
|
542
|
+
}
|
543
|
+
})
|
544
|
+
),
|
545
|
+
rawCall: { rawPrompt: args.messages, rawSettings: args },
|
546
|
+
warnings
|
547
|
+
};
|
548
|
+
}
|
549
|
+
};
|
550
|
+
var workersAIChatResponseSchema = z2.object({
|
551
|
+
response: z2.string()
|
552
|
+
});
|
553
|
+
var workersAIChatChunkSchema = z2.instanceof(Uint8Array);
|
554
|
+
function prepareToolsAndToolChoice(mode) {
|
555
|
+
const tools = mode.tools?.length ? mode.tools : void 0;
|
556
|
+
if (tools == null) {
|
557
|
+
return { tools: void 0, tool_choice: void 0 };
|
558
|
+
}
|
559
|
+
const mappedTools = tools.map((tool) => ({
|
560
|
+
type: "function",
|
561
|
+
function: {
|
562
|
+
name: tool.name,
|
563
|
+
description: tool.description,
|
564
|
+
parameters: tool.parameters
|
565
|
+
}
|
566
|
+
}));
|
567
|
+
const toolChoice = mode.toolChoice;
|
568
|
+
if (toolChoice == null) {
|
569
|
+
return { tools: mappedTools, tool_choice: void 0 };
|
570
|
+
}
|
571
|
+
const type = toolChoice.type;
|
572
|
+
console.log(mode, type);
|
573
|
+
switch (type) {
|
574
|
+
case "auto":
|
575
|
+
return { tools: mappedTools, tool_choice: type };
|
576
|
+
case "none":
|
577
|
+
return { tools: mappedTools, tool_choice: type };
|
578
|
+
case "required":
|
579
|
+
return { tools: mappedTools, tool_choice: "any" };
|
580
|
+
case "tool":
|
581
|
+
return {
|
582
|
+
tools: mappedTools.filter(
|
583
|
+
(tool) => tool.function.name === toolChoice.toolName
|
584
|
+
),
|
585
|
+
tool_choice: "any"
|
586
|
+
};
|
587
|
+
default: {
|
588
|
+
const _exhaustiveCheck = type;
|
589
|
+
throw new Error(`Unsupported tool choice type: ${_exhaustiveCheck}`);
|
590
|
+
}
|
591
|
+
}
|
592
|
+
}
|
593
|
+
|
594
|
+
// src/index.ts
|
595
|
+
function createWorkersAIProvider(options) {
|
596
|
+
const createChatModel = (modelId, settings = {}) => new WorkersAIChatLanguageModel(modelId, settings, {
|
597
|
+
provider: "workerai.chat",
|
598
|
+
binding: options.binding
|
599
|
+
});
|
600
|
+
const provider = function(modelId, settings) {
|
601
|
+
if (new.target) {
|
602
|
+
throw new Error(
|
603
|
+
"The WorkersAI model function cannot be called with the new keyword."
|
604
|
+
);
|
605
|
+
}
|
606
|
+
return createChatModel(modelId, settings);
|
607
|
+
};
|
608
|
+
provider.chat = createChatModel;
|
609
|
+
return provider;
|
610
|
+
}
|
611
|
+
export {
|
612
|
+
createWorkersAIProvider
|
613
|
+
};
|
614
|
+
//# sourceMappingURL=index.js.map
|