ai 3.0.20 → 3.0.22

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.
Files changed (63) hide show
  1. package/dist/index.d.mts +45 -354
  2. package/dist/index.d.ts +45 -354
  3. package/dist/index.js +161 -460
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +136 -430
  6. package/dist/index.mjs.map +1 -1
  7. package/package.json +6 -41
  8. package/react/dist/index.d.mts +1 -1
  9. package/react/dist/index.d.ts +1 -1
  10. package/react/dist/index.js +3 -3
  11. package/react/dist/index.js.map +1 -1
  12. package/react/dist/index.mjs +3 -3
  13. package/react/dist/index.mjs.map +1 -1
  14. package/rsc/dist/rsc-server.mjs +3 -3
  15. package/rsc/dist/rsc-server.mjs.map +1 -1
  16. package/solid/dist/index.d.mts +1 -1
  17. package/solid/dist/index.d.ts +1 -1
  18. package/solid/dist/index.js +3 -3
  19. package/solid/dist/index.js.map +1 -1
  20. package/solid/dist/index.mjs +3 -3
  21. package/solid/dist/index.mjs.map +1 -1
  22. package/svelte/dist/index.d.mts +1 -1
  23. package/svelte/dist/index.d.ts +1 -1
  24. package/svelte/dist/index.js +3 -3
  25. package/svelte/dist/index.js.map +1 -1
  26. package/svelte/dist/index.mjs +3 -3
  27. package/svelte/dist/index.mjs.map +1 -1
  28. package/vue/dist/index.d.mts +1 -1
  29. package/vue/dist/index.d.ts +1 -1
  30. package/vue/dist/index.js +3 -3
  31. package/vue/dist/index.js.map +1 -1
  32. package/vue/dist/index.mjs +3 -3
  33. package/vue/dist/index.mjs.map +1 -1
  34. package/anthropic/dist/index.d.mts +0 -403
  35. package/anthropic/dist/index.d.ts +0 -403
  36. package/anthropic/dist/index.js +0 -950
  37. package/anthropic/dist/index.js.map +0 -1
  38. package/anthropic/dist/index.mjs +0 -914
  39. package/anthropic/dist/index.mjs.map +0 -1
  40. package/google/dist/index.d.mts +0 -399
  41. package/google/dist/index.d.ts +0 -399
  42. package/google/dist/index.js +0 -954
  43. package/google/dist/index.js.map +0 -1
  44. package/google/dist/index.mjs +0 -918
  45. package/google/dist/index.mjs.map +0 -1
  46. package/mistral/dist/index.d.mts +0 -404
  47. package/mistral/dist/index.d.ts +0 -404
  48. package/mistral/dist/index.js +0 -921
  49. package/mistral/dist/index.js.map +0 -1
  50. package/mistral/dist/index.mjs +0 -885
  51. package/mistral/dist/index.mjs.map +0 -1
  52. package/openai/dist/index.d.mts +0 -468
  53. package/openai/dist/index.d.ts +0 -468
  54. package/openai/dist/index.js +0 -1334
  55. package/openai/dist/index.js.map +0 -1
  56. package/openai/dist/index.mjs +0 -1298
  57. package/openai/dist/index.mjs.map +0 -1
  58. package/spec/dist/index.d.mts +0 -780
  59. package/spec/dist/index.d.ts +0 -780
  60. package/spec/dist/index.js +0 -863
  61. package/spec/dist/index.js.map +0 -1
  62. package/spec/dist/index.mjs +0 -797
  63. package/spec/dist/index.mjs.map +0 -1
@@ -1,1298 +0,0 @@
1
- // spec/errors/api-call-error.ts
2
- var APICallError = class extends Error {
3
- constructor({
4
- message,
5
- url,
6
- requestBodyValues,
7
- statusCode,
8
- responseBody,
9
- cause,
10
- isRetryable = statusCode != null && (statusCode === 408 || // request timeout
11
- statusCode === 409 || // conflict
12
- statusCode === 429 || // too many requests
13
- statusCode >= 500),
14
- // server error
15
- data
16
- }) {
17
- super(message);
18
- this.name = "AI_APICallError";
19
- this.url = url;
20
- this.requestBodyValues = requestBodyValues;
21
- this.statusCode = statusCode;
22
- this.responseBody = responseBody;
23
- this.cause = cause;
24
- this.isRetryable = isRetryable;
25
- this.data = data;
26
- }
27
- static isAPICallError(error) {
28
- return error instanceof Error && error.name === "AI_APICallError" && typeof error.url === "string" && typeof error.requestBodyValues === "object" && (error.statusCode == null || typeof error.statusCode === "number") && (error.responseBody == null || typeof error.responseBody === "string") && (error.cause == null || typeof error.cause === "object") && typeof error.isRetryable === "boolean" && (error.data == null || typeof error.data === "object");
29
- }
30
- toJSON() {
31
- return {
32
- name: this.name,
33
- message: this.message,
34
- url: this.url,
35
- requestBodyValues: this.requestBodyValues,
36
- statusCode: this.statusCode,
37
- responseBody: this.responseBody,
38
- cause: this.cause,
39
- isRetryable: this.isRetryable,
40
- data: this.data
41
- };
42
- }
43
- };
44
-
45
- // spec/errors/invalid-prompt-error.ts
46
- var InvalidPromptError = class extends Error {
47
- constructor({ prompt: prompt2, message }) {
48
- super(`Invalid prompt: ${message}`);
49
- this.name = "AI_InvalidPromptError";
50
- this.prompt = prompt2;
51
- }
52
- static isInvalidPromptError(error) {
53
- return error instanceof Error && error.name === "AI_InvalidPromptError" && prompt != null;
54
- }
55
- toJSON() {
56
- return {
57
- name: this.name,
58
- message: this.message,
59
- stack: this.stack,
60
- prompt: this.prompt
61
- };
62
- }
63
- };
64
-
65
- // spec/errors/invalid-response-data-error.ts
66
- var InvalidResponseDataError = class extends Error {
67
- constructor({
68
- data,
69
- message = `Invalid response data: ${JSON.stringify(data)}.`
70
- }) {
71
- super(message);
72
- this.name = "AI_InvalidResponseDataError";
73
- this.data = data;
74
- }
75
- static isInvalidResponseDataError(error) {
76
- return error instanceof Error && error.name === "AI_InvalidResponseDataError" && error.data != null;
77
- }
78
- toJSON() {
79
- return {
80
- name: this.name,
81
- message: this.message,
82
- stack: this.stack,
83
- data: this.data
84
- };
85
- }
86
- };
87
-
88
- // spec/util/generate-id.ts
89
- import { customAlphabet } from "nanoid/non-secure";
90
- var generateId = customAlphabet(
91
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
92
- 7
93
- );
94
-
95
- // spec/util/get-error-message.ts
96
- function getErrorMessage(error) {
97
- if (error == null) {
98
- return "unknown error";
99
- }
100
- if (typeof error === "string") {
101
- return error;
102
- }
103
- if (error instanceof Error) {
104
- return error.message;
105
- }
106
- return JSON.stringify(error);
107
- }
108
-
109
- // spec/errors/load-api-key-error.ts
110
- var LoadAPIKeyError = class extends Error {
111
- constructor({ message }) {
112
- super(message);
113
- this.name = "AI_LoadAPIKeyError";
114
- }
115
- static isLoadAPIKeyError(error) {
116
- return error instanceof Error && error.name === "AI_LoadAPIKeyError";
117
- }
118
- toJSON() {
119
- return {
120
- name: this.name,
121
- message: this.message
122
- };
123
- }
124
- };
125
-
126
- // spec/util/load-api-key.ts
127
- function loadApiKey({
128
- apiKey,
129
- environmentVariableName,
130
- apiKeyParameterName = "apiKey",
131
- description
132
- }) {
133
- if (typeof apiKey === "string") {
134
- return apiKey;
135
- }
136
- if (apiKey != null) {
137
- throw new LoadAPIKeyError({
138
- message: `${description} API key must be a string.`
139
- });
140
- }
141
- if (typeof process === "undefined") {
142
- throw new LoadAPIKeyError({
143
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
144
- });
145
- }
146
- apiKey = process.env[environmentVariableName];
147
- if (apiKey == null) {
148
- throw new LoadAPIKeyError({
149
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
150
- });
151
- }
152
- if (typeof apiKey !== "string") {
153
- throw new LoadAPIKeyError({
154
- message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
155
- });
156
- }
157
- return apiKey;
158
- }
159
-
160
- // spec/util/parse-json.ts
161
- import SecureJSON from "secure-json-parse";
162
-
163
- // spec/errors/json-parse-error.ts
164
- var JSONParseError = class extends Error {
165
- constructor({ text, cause }) {
166
- super(
167
- `JSON parsing failed: Text: ${text}.
168
- Error message: ${getErrorMessage(cause)}`
169
- );
170
- this.name = "AI_JSONParseError";
171
- this.cause = cause;
172
- this.text = text;
173
- }
174
- static isJSONParseError(error) {
175
- return error instanceof Error && error.name === "AI_JSONParseError" && typeof error.text === "string" && typeof error.cause === "string";
176
- }
177
- toJSON() {
178
- return {
179
- name: this.name,
180
- message: this.message,
181
- cause: this.cause,
182
- stack: this.stack,
183
- valueText: this.text
184
- };
185
- }
186
- };
187
-
188
- // spec/errors/type-validation-error.ts
189
- var TypeValidationError = class extends Error {
190
- constructor({ value, cause }) {
191
- super(
192
- `Type validation failed: Value: ${JSON.stringify(value)}.
193
- Error message: ${getErrorMessage(cause)}`
194
- );
195
- this.name = "AI_TypeValidationError";
196
- this.cause = cause;
197
- this.value = value;
198
- }
199
- static isTypeValidationError(error) {
200
- return error instanceof Error && error.name === "AI_TypeValidationError" && typeof error.value === "string" && typeof error.cause === "string";
201
- }
202
- toJSON() {
203
- return {
204
- name: this.name,
205
- message: this.message,
206
- cause: this.cause,
207
- stack: this.stack,
208
- value: this.value
209
- };
210
- }
211
- };
212
-
213
- // spec/util/validate-types.ts
214
- function validateTypes({
215
- value,
216
- schema
217
- }) {
218
- try {
219
- return schema.parse(value);
220
- } catch (error) {
221
- throw new TypeValidationError({ value, cause: error });
222
- }
223
- }
224
- function safeValidateTypes({
225
- value,
226
- schema
227
- }) {
228
- try {
229
- const validationResult = schema.safeParse(value);
230
- if (validationResult.success) {
231
- return {
232
- success: true,
233
- value: validationResult.data
234
- };
235
- }
236
- return {
237
- success: false,
238
- error: new TypeValidationError({
239
- value,
240
- cause: validationResult.error
241
- })
242
- };
243
- } catch (error) {
244
- return {
245
- success: false,
246
- error: TypeValidationError.isTypeValidationError(error) ? error : new TypeValidationError({ value, cause: error })
247
- };
248
- }
249
- }
250
-
251
- // spec/util/parse-json.ts
252
- function parseJSON({
253
- text,
254
- schema
255
- }) {
256
- try {
257
- const value = SecureJSON.parse(text);
258
- if (schema == null) {
259
- return value;
260
- }
261
- return validateTypes({ value, schema });
262
- } catch (error) {
263
- if (JSONParseError.isJSONParseError(error) || TypeValidationError.isTypeValidationError(error)) {
264
- throw error;
265
- }
266
- throw new JSONParseError({ text, cause: error });
267
- }
268
- }
269
- function safeParseJSON({
270
- text,
271
- schema
272
- }) {
273
- try {
274
- const value = SecureJSON.parse(text);
275
- if (schema == null) {
276
- return {
277
- success: true,
278
- value
279
- };
280
- }
281
- return safeValidateTypes({ value, schema });
282
- } catch (error) {
283
- return {
284
- success: false,
285
- error: JSONParseError.isJSONParseError(error) ? error : new JSONParseError({ text, cause: error })
286
- };
287
- }
288
- }
289
- function isParseableJson(input) {
290
- try {
291
- SecureJSON.parse(input);
292
- return true;
293
- } catch (e) {
294
- return false;
295
- }
296
- }
297
-
298
- // spec/util/post-to-api.ts
299
- var postJsonToApi = async ({
300
- url,
301
- headers,
302
- body,
303
- failedResponseHandler,
304
- successfulResponseHandler,
305
- abortSignal
306
- }) => postToApi({
307
- url,
308
- headers: {
309
- ...headers,
310
- "Content-Type": "application/json"
311
- },
312
- body: {
313
- content: JSON.stringify(body),
314
- values: body
315
- },
316
- failedResponseHandler,
317
- successfulResponseHandler,
318
- abortSignal
319
- });
320
- var postToApi = async ({
321
- url,
322
- headers = {},
323
- body,
324
- successfulResponseHandler,
325
- failedResponseHandler,
326
- abortSignal
327
- }) => {
328
- try {
329
- const definedHeaders = Object.fromEntries(
330
- Object.entries(headers).filter(([_key, value]) => value != null)
331
- );
332
- const response = await fetch(url, {
333
- method: "POST",
334
- headers: definedHeaders,
335
- body: body.content,
336
- signal: abortSignal
337
- });
338
- if (!response.ok) {
339
- try {
340
- throw await failedResponseHandler({
341
- response,
342
- url,
343
- requestBodyValues: body.values
344
- });
345
- } catch (error) {
346
- if (error instanceof Error) {
347
- if (error.name === "AbortError" || APICallError.isAPICallError(error)) {
348
- throw error;
349
- }
350
- }
351
- throw new APICallError({
352
- message: "Failed to process error response",
353
- cause: error,
354
- statusCode: response.status,
355
- url,
356
- requestBodyValues: body.values
357
- });
358
- }
359
- }
360
- try {
361
- return await successfulResponseHandler({
362
- response,
363
- url,
364
- requestBodyValues: body.values
365
- });
366
- } catch (error) {
367
- if (error instanceof Error) {
368
- if (error.name === "AbortError" || APICallError.isAPICallError(error)) {
369
- throw error;
370
- }
371
- }
372
- throw new APICallError({
373
- message: "Failed to process successful response",
374
- cause: error,
375
- statusCode: response.status,
376
- url,
377
- requestBodyValues: body.values
378
- });
379
- }
380
- } catch (error) {
381
- if (error instanceof Error) {
382
- if (error.name === "AbortError") {
383
- throw error;
384
- }
385
- }
386
- if (error instanceof TypeError && error.message === "fetch failed") {
387
- const cause = error.cause;
388
- if (cause != null) {
389
- throw new APICallError({
390
- message: `Cannot connect to API: ${cause.message}`,
391
- cause,
392
- url,
393
- requestBodyValues: body.values,
394
- isRetryable: true
395
- // retry when network error
396
- });
397
- }
398
- }
399
- throw error;
400
- }
401
- };
402
-
403
- // spec/util/response-handler.ts
404
- import {
405
- EventSourceParserStream
406
- } from "eventsource-parser/stream";
407
-
408
- // spec/errors/no-response-body-error.ts
409
- var NoResponseBodyError = class extends Error {
410
- constructor({ message = "No response body" } = {}) {
411
- super(message);
412
- this.name = "AI_NoResponseBodyError";
413
- }
414
- static isNoResponseBodyError(error) {
415
- return error instanceof Error && error.name === "AI_NoResponseBodyError";
416
- }
417
- toJSON() {
418
- return {
419
- name: this.name,
420
- message: this.message,
421
- stack: this.stack
422
- };
423
- }
424
- };
425
-
426
- // spec/util/response-handler.ts
427
- var createJsonErrorResponseHandler = ({
428
- errorSchema,
429
- errorToMessage,
430
- isRetryable
431
- }) => async ({ response, url, requestBodyValues }) => {
432
- const responseBody = await response.text();
433
- if (responseBody.trim() === "") {
434
- return new APICallError({
435
- message: response.statusText,
436
- url,
437
- requestBodyValues,
438
- statusCode: response.status,
439
- responseBody,
440
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
441
- });
442
- }
443
- try {
444
- const parsedError = parseJSON({
445
- text: responseBody,
446
- schema: errorSchema
447
- });
448
- return new APICallError({
449
- message: errorToMessage(parsedError),
450
- url,
451
- requestBodyValues,
452
- statusCode: response.status,
453
- responseBody,
454
- data: parsedError,
455
- isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
456
- });
457
- } catch (parseError) {
458
- return new APICallError({
459
- message: response.statusText,
460
- url,
461
- requestBodyValues,
462
- statusCode: response.status,
463
- responseBody,
464
- isRetryable: isRetryable == null ? void 0 : isRetryable(response)
465
- });
466
- }
467
- };
468
- var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
469
- if (response.body == null) {
470
- throw new NoResponseBodyError();
471
- }
472
- return response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
473
- new TransformStream({
474
- transform({ data }, controller) {
475
- if (data === "[DONE]") {
476
- return;
477
- }
478
- controller.enqueue(
479
- safeParseJSON({
480
- text: data,
481
- schema: chunkSchema
482
- })
483
- );
484
- }
485
- })
486
- );
487
- };
488
- var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
489
- const responseBody = await response.text();
490
- const parsedResult = safeParseJSON({
491
- text: responseBody,
492
- schema: responseSchema
493
- });
494
- if (!parsedResult.success) {
495
- throw new APICallError({
496
- message: "Invalid JSON response",
497
- cause: parsedResult.error,
498
- statusCode: response.status,
499
- responseBody,
500
- url,
501
- requestBodyValues
502
- });
503
- }
504
- return parsedResult.value;
505
- };
506
-
507
- // spec/util/scale.ts
508
- function scale({
509
- inputMin = 0,
510
- inputMax = 1,
511
- outputMin,
512
- outputMax,
513
- value
514
- }) {
515
- if (value === void 0) {
516
- return void 0;
517
- }
518
- const inputRange = inputMax - inputMin;
519
- const outputRange = outputMax - outputMin;
520
- return (value - inputMin) * outputRange / inputRange + outputMin;
521
- }
522
-
523
- // spec/util/uint8-utils.ts
524
- function convertUint8ArrayToBase64(array) {
525
- let latin1string = "";
526
- for (let i = 0; i < array.length; i++) {
527
- latin1string += String.fromCodePoint(array[i]);
528
- }
529
- return globalThis.btoa(latin1string);
530
- }
531
-
532
- // spec/errors/unsupported-functionality-error.ts
533
- var UnsupportedFunctionalityError = class extends Error {
534
- constructor({ functionality }) {
535
- super(`'${functionality}' functionality not supported.`);
536
- this.name = "AI_UnsupportedFunctionalityError";
537
- this.functionality = functionality;
538
- }
539
- static isUnsupportedFunctionalityError(error) {
540
- return error instanceof Error && error.name === "AI_UnsupportedFunctionalityError" && typeof error.functionality === "string";
541
- }
542
- toJSON() {
543
- return {
544
- name: this.name,
545
- message: this.message,
546
- stack: this.stack,
547
- functionality: this.functionality
548
- };
549
- }
550
- };
551
-
552
- // openai/openai-chat-language-model.ts
553
- import { z as z2 } from "zod";
554
-
555
- // openai/convert-to-openai-chat-messages.ts
556
- function convertToOpenAIChatMessages(prompt2) {
557
- const messages = [];
558
- for (const { role, content } of prompt2) {
559
- switch (role) {
560
- case "system": {
561
- messages.push({ role: "system", content });
562
- break;
563
- }
564
- case "user": {
565
- messages.push({
566
- role: "user",
567
- content: content.map((part) => {
568
- var _a;
569
- switch (part.type) {
570
- case "text": {
571
- return { type: "text", text: part.text };
572
- }
573
- case "image": {
574
- return {
575
- type: "image_url",
576
- image_url: {
577
- url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`
578
- }
579
- };
580
- }
581
- }
582
- })
583
- });
584
- break;
585
- }
586
- case "assistant": {
587
- let text = "";
588
- const toolCalls = [];
589
- for (const part of content) {
590
- switch (part.type) {
591
- case "text": {
592
- text += part.text;
593
- break;
594
- }
595
- case "tool-call": {
596
- toolCalls.push({
597
- id: part.toolCallId,
598
- type: "function",
599
- function: {
600
- name: part.toolName,
601
- arguments: JSON.stringify(part.args)
602
- }
603
- });
604
- break;
605
- }
606
- default: {
607
- const _exhaustiveCheck = part;
608
- throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
609
- }
610
- }
611
- }
612
- messages.push({
613
- role: "assistant",
614
- content: text,
615
- tool_calls: toolCalls.length > 0 ? toolCalls : void 0
616
- });
617
- break;
618
- }
619
- case "tool": {
620
- for (const toolResponse of content) {
621
- messages.push({
622
- role: "tool",
623
- tool_call_id: toolResponse.toolCallId,
624
- content: JSON.stringify(toolResponse.result)
625
- });
626
- }
627
- break;
628
- }
629
- default: {
630
- const _exhaustiveCheck = role;
631
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
632
- }
633
- }
634
- }
635
- return messages;
636
- }
637
-
638
- // openai/map-openai-finish-reason.ts
639
- function mapOpenAIFinishReason(finishReason) {
640
- switch (finishReason) {
641
- case "stop":
642
- return "stop";
643
- case "length":
644
- return "length";
645
- case "content_filter":
646
- return "content-filter";
647
- case "function_call":
648
- case "tool_calls":
649
- return "tool-calls";
650
- default:
651
- return "other";
652
- }
653
- }
654
-
655
- // openai/openai-error.ts
656
- import { z } from "zod";
657
- var openAIErrorDataSchema = z.object({
658
- error: z.object({
659
- message: z.string(),
660
- type: z.string(),
661
- param: z.any().nullable(),
662
- code: z.string().nullable()
663
- })
664
- });
665
- var openaiFailedResponseHandler = createJsonErrorResponseHandler({
666
- errorSchema: openAIErrorDataSchema,
667
- errorToMessage: (data) => data.error.message
668
- });
669
-
670
- // openai/openai-chat-language-model.ts
671
- var OpenAIChatLanguageModel = class {
672
- constructor(modelId, settings, config) {
673
- this.specificationVersion = "v1";
674
- this.defaultObjectGenerationMode = "tool";
675
- this.modelId = modelId;
676
- this.settings = settings;
677
- this.config = config;
678
- }
679
- get provider() {
680
- return this.config.provider;
681
- }
682
- getArgs({
683
- mode,
684
- prompt: prompt2,
685
- maxTokens,
686
- temperature,
687
- topP,
688
- frequencyPenalty,
689
- presencePenalty,
690
- seed
691
- }) {
692
- var _a;
693
- const type = mode.type;
694
- const baseArgs = {
695
- // model id:
696
- model: this.modelId,
697
- // model specific settings:
698
- logit_bias: this.settings.logitBias,
699
- user: this.settings.user,
700
- // standardized settings:
701
- max_tokens: maxTokens,
702
- temperature: scale({
703
- value: temperature,
704
- outputMin: 0,
705
- outputMax: 2
706
- }),
707
- top_p: topP,
708
- frequency_penalty: scale({
709
- value: frequencyPenalty,
710
- inputMin: -1,
711
- inputMax: 1,
712
- outputMin: -2,
713
- outputMax: 2
714
- }),
715
- presence_penalty: scale({
716
- value: presencePenalty,
717
- inputMin: -1,
718
- inputMax: 1,
719
- outputMin: -2,
720
- outputMax: 2
721
- }),
722
- seed,
723
- // messages:
724
- messages: convertToOpenAIChatMessages(prompt2)
725
- };
726
- switch (type) {
727
- case "regular": {
728
- const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
729
- return {
730
- ...baseArgs,
731
- tools: tools == null ? void 0 : tools.map((tool) => ({
732
- type: "function",
733
- function: {
734
- name: tool.name,
735
- description: tool.description,
736
- parameters: tool.parameters
737
- }
738
- }))
739
- };
740
- }
741
- case "object-json": {
742
- return {
743
- ...baseArgs,
744
- response_format: { type: "json_object" }
745
- };
746
- }
747
- case "object-tool": {
748
- return {
749
- ...baseArgs,
750
- tool_choice: { type: "function", function: { name: mode.tool.name } },
751
- tools: [{ type: "function", function: mode.tool }]
752
- };
753
- }
754
- case "object-grammar": {
755
- throw new UnsupportedFunctionalityError({
756
- functionality: "object-grammar mode"
757
- });
758
- }
759
- default: {
760
- const _exhaustiveCheck = type;
761
- throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
762
- }
763
- }
764
- }
765
- async doGenerate(options) {
766
- var _a, _b;
767
- const args = this.getArgs(options);
768
- const response = await postJsonToApi({
769
- url: `${this.config.baseUrl}/chat/completions`,
770
- headers: this.config.headers(),
771
- body: args,
772
- failedResponseHandler: openaiFailedResponseHandler,
773
- successfulResponseHandler: createJsonResponseHandler(
774
- openAIChatResponseSchema
775
- ),
776
- abortSignal: options.abortSignal
777
- });
778
- const { messages: rawPrompt, ...rawSettings } = args;
779
- const choice = response.choices[0];
780
- return {
781
- text: (_a = choice.message.content) != null ? _a : void 0,
782
- toolCalls: (_b = choice.message.tool_calls) == null ? void 0 : _b.map((toolCall) => ({
783
- toolCallType: "function",
784
- toolCallId: toolCall.id,
785
- toolName: toolCall.function.name,
786
- args: toolCall.function.arguments
787
- })),
788
- finishReason: mapOpenAIFinishReason(choice.finish_reason),
789
- usage: {
790
- promptTokens: response.usage.prompt_tokens,
791
- completionTokens: response.usage.completion_tokens
792
- },
793
- rawCall: { rawPrompt, rawSettings },
794
- warnings: []
795
- };
796
- }
797
- async doStream(options) {
798
- const args = this.getArgs(options);
799
- const response = await postJsonToApi({
800
- url: `${this.config.baseUrl}/chat/completions`,
801
- headers: this.config.headers(),
802
- body: {
803
- ...args,
804
- stream: true
805
- },
806
- failedResponseHandler: openaiFailedResponseHandler,
807
- successfulResponseHandler: createEventSourceResponseHandler(
808
- openaiChatChunkSchema
809
- ),
810
- abortSignal: options.abortSignal
811
- });
812
- const { messages: rawPrompt, ...rawSettings } = args;
813
- const toolCalls = [];
814
- let finishReason = "other";
815
- let usage = {
816
- promptTokens: Number.NaN,
817
- completionTokens: Number.NaN
818
- };
819
- return {
820
- stream: response.pipeThrough(
821
- new TransformStream({
822
- transform(chunk, controller) {
823
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
824
- if (!chunk.success) {
825
- controller.enqueue({ type: "error", error: chunk.error });
826
- return;
827
- }
828
- const value = chunk.value;
829
- if (value.usage != null) {
830
- usage = {
831
- promptTokens: value.usage.prompt_tokens,
832
- completionTokens: value.usage.completion_tokens
833
- };
834
- }
835
- const choice = value.choices[0];
836
- if ((choice == null ? void 0 : choice.finish_reason) != null) {
837
- finishReason = mapOpenAIFinishReason(choice.finish_reason);
838
- }
839
- if ((choice == null ? void 0 : choice.delta) == null) {
840
- return;
841
- }
842
- const delta = choice.delta;
843
- if (delta.content != null) {
844
- controller.enqueue({
845
- type: "text-delta",
846
- textDelta: delta.content
847
- });
848
- }
849
- if (delta.tool_calls != null) {
850
- for (const toolCallDelta of delta.tool_calls) {
851
- const index = toolCallDelta.index;
852
- if (toolCalls[index] == null) {
853
- if (toolCallDelta.type !== "function") {
854
- throw new InvalidResponseDataError({
855
- data: toolCallDelta,
856
- message: `Expected 'function' type.`
857
- });
858
- }
859
- if (toolCallDelta.id == null) {
860
- throw new InvalidResponseDataError({
861
- data: toolCallDelta,
862
- message: `Expected 'id' to be a string.`
863
- });
864
- }
865
- if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
866
- throw new InvalidResponseDataError({
867
- data: toolCallDelta,
868
- message: `Expected 'function.name' to be a string.`
869
- });
870
- }
871
- toolCalls[index] = {
872
- id: toolCallDelta.id,
873
- type: "function",
874
- function: {
875
- name: toolCallDelta.function.name,
876
- arguments: (_b = toolCallDelta.function.arguments) != null ? _b : ""
877
- }
878
- };
879
- continue;
880
- }
881
- const toolCall = toolCalls[index];
882
- if (((_c = toolCallDelta.function) == null ? void 0 : _c.arguments) != null) {
883
- toolCall.function.arguments += (_e = (_d = toolCallDelta.function) == null ? void 0 : _d.arguments) != null ? _e : "";
884
- }
885
- controller.enqueue({
886
- type: "tool-call-delta",
887
- toolCallType: "function",
888
- toolCallId: toolCall.id,
889
- toolName: toolCall.function.name,
890
- argsTextDelta: (_f = toolCallDelta.function.arguments) != null ? _f : ""
891
- });
892
- if (((_g = toolCall.function) == null ? void 0 : _g.name) == null || ((_h = toolCall.function) == null ? void 0 : _h.arguments) == null || !isParseableJson(toolCall.function.arguments)) {
893
- continue;
894
- }
895
- controller.enqueue({
896
- type: "tool-call",
897
- toolCallType: "function",
898
- toolCallId: (_i = toolCall.id) != null ? _i : generateId(),
899
- toolName: toolCall.function.name,
900
- args: toolCall.function.arguments
901
- });
902
- }
903
- }
904
- },
905
- flush(controller) {
906
- controller.enqueue({ type: "finish", finishReason, usage });
907
- }
908
- })
909
- ),
910
- rawCall: { rawPrompt, rawSettings },
911
- warnings: []
912
- };
913
- }
914
- };
915
- var openAIChatResponseSchema = z2.object({
916
- choices: z2.array(
917
- z2.object({
918
- message: z2.object({
919
- role: z2.literal("assistant"),
920
- content: z2.string().nullable(),
921
- tool_calls: z2.array(
922
- z2.object({
923
- id: z2.string(),
924
- type: z2.literal("function"),
925
- function: z2.object({
926
- name: z2.string(),
927
- arguments: z2.string()
928
- })
929
- })
930
- ).optional()
931
- }),
932
- index: z2.number(),
933
- finish_reason: z2.string().optional().nullable()
934
- })
935
- ),
936
- object: z2.literal("chat.completion"),
937
- usage: z2.object({
938
- prompt_tokens: z2.number(),
939
- completion_tokens: z2.number()
940
- })
941
- });
942
- var openaiChatChunkSchema = z2.object({
943
- object: z2.literal("chat.completion.chunk"),
944
- choices: z2.array(
945
- z2.object({
946
- delta: z2.object({
947
- role: z2.enum(["assistant"]).optional(),
948
- content: z2.string().nullable().optional(),
949
- tool_calls: z2.array(
950
- z2.object({
951
- index: z2.number(),
952
- id: z2.string().optional(),
953
- type: z2.literal("function").optional(),
954
- function: z2.object({
955
- name: z2.string().optional(),
956
- arguments: z2.string().optional()
957
- })
958
- })
959
- ).optional()
960
- }),
961
- finish_reason: z2.string().nullable().optional(),
962
- index: z2.number()
963
- })
964
- ),
965
- usage: z2.object({
966
- prompt_tokens: z2.number(),
967
- completion_tokens: z2.number()
968
- }).optional().nullable()
969
- });
970
-
971
- // openai/openai-completion-language-model.ts
972
- import { z as z3 } from "zod";
973
-
974
- // openai/convert-to-openai-completion-prompt.ts
975
- function convertToOpenAICompletionPrompt({
976
- prompt: prompt2,
977
- inputFormat,
978
- user = "user",
979
- assistant = "assistant"
980
- }) {
981
- if (inputFormat === "prompt" && prompt2.length === 1 && prompt2[0].role === "user" && prompt2[0].content.length === 1 && prompt2[0].content[0].type === "text") {
982
- return { prompt: prompt2[0].content[0].text };
983
- }
984
- let text = "";
985
- if (prompt2[0].role === "system") {
986
- text += `${prompt2[0].content}
987
-
988
- `;
989
- prompt2 = prompt2.slice(1);
990
- }
991
- for (const { role, content } of prompt2) {
992
- switch (role) {
993
- case "system": {
994
- throw new InvalidPromptError({
995
- message: "Unexpected system message in prompt: ${content}",
996
- prompt: prompt2
997
- });
998
- }
999
- case "user": {
1000
- const userMessage = content.map((part) => {
1001
- switch (part.type) {
1002
- case "text": {
1003
- return part.text;
1004
- }
1005
- case "image": {
1006
- throw new UnsupportedFunctionalityError({
1007
- functionality: "images"
1008
- });
1009
- }
1010
- }
1011
- }).join("");
1012
- text += `${user}:
1013
- ${userMessage}
1014
-
1015
- `;
1016
- break;
1017
- }
1018
- case "assistant": {
1019
- const assistantMessage = content.map((part) => {
1020
- switch (part.type) {
1021
- case "text": {
1022
- return part.text;
1023
- }
1024
- case "tool-call": {
1025
- throw new UnsupportedFunctionalityError({
1026
- functionality: "tool-call messages"
1027
- });
1028
- }
1029
- }
1030
- }).join("");
1031
- text += `${assistant}:
1032
- ${assistantMessage}
1033
-
1034
- `;
1035
- break;
1036
- }
1037
- case "tool": {
1038
- throw new UnsupportedFunctionalityError({
1039
- functionality: "tool messages"
1040
- });
1041
- }
1042
- default: {
1043
- const _exhaustiveCheck = role;
1044
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
1045
- }
1046
- }
1047
- }
1048
- text += `${assistant}:
1049
- `;
1050
- return {
1051
- prompt: text,
1052
- stopSequences: [`
1053
- ${user}:`]
1054
- };
1055
- }
1056
-
1057
- // openai/openai-completion-language-model.ts
1058
- var OpenAICompletionLanguageModel = class {
1059
- constructor(modelId, settings, config) {
1060
- this.specificationVersion = "v1";
1061
- this.defaultObjectGenerationMode = void 0;
1062
- this.modelId = modelId;
1063
- this.settings = settings;
1064
- this.config = config;
1065
- }
1066
- get provider() {
1067
- return this.config.provider;
1068
- }
1069
- getArgs({
1070
- mode,
1071
- inputFormat,
1072
- prompt: prompt2,
1073
- maxTokens,
1074
- temperature,
1075
- topP,
1076
- frequencyPenalty,
1077
- presencePenalty,
1078
- seed
1079
- }) {
1080
- var _a;
1081
- const type = mode.type;
1082
- const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ prompt: prompt2, inputFormat });
1083
- const baseArgs = {
1084
- // model id:
1085
- model: this.modelId,
1086
- // model specific settings:
1087
- echo: this.settings.echo,
1088
- logit_bias: this.settings.logitBias,
1089
- suffix: this.settings.suffix,
1090
- user: this.settings.user,
1091
- // standardized settings:
1092
- max_tokens: maxTokens,
1093
- temperature: scale({
1094
- value: temperature,
1095
- outputMin: 0,
1096
- outputMax: 2
1097
- }),
1098
- top_p: topP,
1099
- frequency_penalty: scale({
1100
- value: frequencyPenalty,
1101
- inputMin: -1,
1102
- inputMax: 1,
1103
- outputMin: -2,
1104
- outputMax: 2
1105
- }),
1106
- presence_penalty: scale({
1107
- value: presencePenalty,
1108
- inputMin: -1,
1109
- inputMax: 1,
1110
- outputMin: -2,
1111
- outputMax: 2
1112
- }),
1113
- seed,
1114
- // prompt:
1115
- prompt: completionPrompt,
1116
- // stop sequences:
1117
- stop: stopSequences
1118
- };
1119
- switch (type) {
1120
- case "regular": {
1121
- if ((_a = mode.tools) == null ? void 0 : _a.length) {
1122
- throw new UnsupportedFunctionalityError({
1123
- functionality: "tools"
1124
- });
1125
- }
1126
- return baseArgs;
1127
- }
1128
- case "object-json": {
1129
- throw new UnsupportedFunctionalityError({
1130
- functionality: "object-json mode"
1131
- });
1132
- }
1133
- case "object-tool": {
1134
- throw new UnsupportedFunctionalityError({
1135
- functionality: "object-tool mode"
1136
- });
1137
- }
1138
- case "object-grammar": {
1139
- throw new UnsupportedFunctionalityError({
1140
- functionality: "object-grammar mode"
1141
- });
1142
- }
1143
- default: {
1144
- const _exhaustiveCheck = type;
1145
- throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
1146
- }
1147
- }
1148
- }
1149
- async doGenerate(options) {
1150
- const args = this.getArgs(options);
1151
- const response = await postJsonToApi({
1152
- url: `${this.config.baseUrl}/completions`,
1153
- headers: this.config.headers(),
1154
- body: args,
1155
- failedResponseHandler: openaiFailedResponseHandler,
1156
- successfulResponseHandler: createJsonResponseHandler(
1157
- openAICompletionResponseSchema
1158
- ),
1159
- abortSignal: options.abortSignal
1160
- });
1161
- const { prompt: rawPrompt, ...rawSettings } = args;
1162
- const choice = response.choices[0];
1163
- return {
1164
- text: choice.text,
1165
- usage: {
1166
- promptTokens: response.usage.prompt_tokens,
1167
- completionTokens: response.usage.completion_tokens
1168
- },
1169
- finishReason: mapOpenAIFinishReason(choice.finish_reason),
1170
- rawCall: { rawPrompt, rawSettings },
1171
- warnings: []
1172
- };
1173
- }
1174
- async doStream(options) {
1175
- const args = this.getArgs(options);
1176
- const response = await postJsonToApi({
1177
- url: `${this.config.baseUrl}/completions`,
1178
- headers: this.config.headers(),
1179
- body: {
1180
- ...this.getArgs(options),
1181
- stream: true
1182
- },
1183
- failedResponseHandler: openaiFailedResponseHandler,
1184
- successfulResponseHandler: createEventSourceResponseHandler(
1185
- openaiCompletionChunkSchema
1186
- ),
1187
- abortSignal: options.abortSignal
1188
- });
1189
- const { prompt: rawPrompt, ...rawSettings } = args;
1190
- let finishReason = "other";
1191
- let usage = {
1192
- promptTokens: Number.NaN,
1193
- completionTokens: Number.NaN
1194
- };
1195
- return {
1196
- stream: response.pipeThrough(
1197
- new TransformStream({
1198
- transform(chunk, controller) {
1199
- if (!chunk.success) {
1200
- controller.enqueue({ type: "error", error: chunk.error });
1201
- return;
1202
- }
1203
- const value = chunk.value;
1204
- if (value.usage != null) {
1205
- usage = {
1206
- promptTokens: value.usage.prompt_tokens,
1207
- completionTokens: value.usage.completion_tokens
1208
- };
1209
- }
1210
- const choice = value.choices[0];
1211
- if ((choice == null ? void 0 : choice.finish_reason) != null) {
1212
- finishReason = mapOpenAIFinishReason(choice.finish_reason);
1213
- }
1214
- if ((choice == null ? void 0 : choice.text) != null) {
1215
- controller.enqueue({
1216
- type: "text-delta",
1217
- textDelta: choice.text
1218
- });
1219
- }
1220
- },
1221
- flush(controller) {
1222
- controller.enqueue({ type: "finish", finishReason, usage });
1223
- }
1224
- })
1225
- ),
1226
- rawCall: { rawPrompt, rawSettings },
1227
- warnings: []
1228
- };
1229
- }
1230
- };
1231
- var openAICompletionResponseSchema = z3.object({
1232
- choices: z3.array(
1233
- z3.object({
1234
- text: z3.string(),
1235
- finish_reason: z3.string()
1236
- })
1237
- ),
1238
- usage: z3.object({
1239
- prompt_tokens: z3.number(),
1240
- completion_tokens: z3.number()
1241
- })
1242
- });
1243
- var openaiCompletionChunkSchema = z3.object({
1244
- object: z3.literal("text_completion"),
1245
- choices: z3.array(
1246
- z3.object({
1247
- text: z3.string(),
1248
- finish_reason: z3.enum(["stop", "length", "content_filter"]).optional().nullable(),
1249
- index: z3.number()
1250
- })
1251
- ),
1252
- usage: z3.object({
1253
- prompt_tokens: z3.number(),
1254
- completion_tokens: z3.number()
1255
- }).optional().nullable()
1256
- });
1257
-
1258
- // openai/openai-facade.ts
1259
- var OpenAI = class {
1260
- constructor(options = {}) {
1261
- this.baseUrl = options.baseUrl;
1262
- this.apiKey = options.apiKey;
1263
- this.organization = options.organization;
1264
- }
1265
- get baseConfig() {
1266
- var _a;
1267
- return {
1268
- organization: this.organization,
1269
- baseUrl: (_a = this.baseUrl) != null ? _a : "https://api.openai.com/v1",
1270
- headers: () => ({
1271
- Authorization: `Bearer ${loadApiKey({
1272
- apiKey: this.apiKey,
1273
- environmentVariableName: "OPENAI_API_KEY",
1274
- description: "OpenAI"
1275
- })}`,
1276
- "OpenAI-Organization": this.organization
1277
- })
1278
- };
1279
- }
1280
- chat(modelId, settings = {}) {
1281
- return new OpenAIChatLanguageModel(modelId, settings, {
1282
- provider: "openai.chat",
1283
- ...this.baseConfig
1284
- });
1285
- }
1286
- completion(modelId, settings = {}) {
1287
- return new OpenAICompletionLanguageModel(modelId, settings, {
1288
- provider: "openai.completion",
1289
- ...this.baseConfig
1290
- });
1291
- }
1292
- };
1293
- var openai = new OpenAI();
1294
- export {
1295
- OpenAI,
1296
- openai
1297
- };
1298
- //# sourceMappingURL=index.mjs.map