ai 3.0.17 → 3.0.18
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/anthropic/dist/index.d.mts +371 -0
- package/anthropic/dist/index.d.ts +371 -0
- package/anthropic/dist/index.js +946 -0
- package/anthropic/dist/index.js.map +1 -0
- package/anthropic/dist/index.mjs +910 -0
- package/anthropic/dist/index.mjs.map +1 -0
- package/dist/index.js +29 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +29 -2
- package/dist/index.mjs.map +1 -1
- package/google/dist/index.js.map +1 -1
- package/google/dist/index.mjs.map +1 -1
- package/mistral/dist/index.js +2 -2
- package/mistral/dist/index.js.map +1 -1
- package/mistral/dist/index.mjs +2 -2
- package/mistral/dist/index.mjs.map +1 -1
- package/openai/dist/index.js.map +1 -1
- package/openai/dist/index.mjs.map +1 -1
- package/package.json +10 -2
- package/spec/dist/index.js.map +1 -1
- package/spec/dist/index.mjs.map +1 -1
@@ -0,0 +1,910 @@
|
|
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/util/generate-id.ts
|
46
|
+
import { customAlphabet } from "nanoid/non-secure";
|
47
|
+
var generateId = customAlphabet(
|
48
|
+
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
|
49
|
+
7
|
50
|
+
);
|
51
|
+
|
52
|
+
// spec/util/get-error-message.ts
|
53
|
+
function getErrorMessage(error) {
|
54
|
+
if (error == null) {
|
55
|
+
return "unknown error";
|
56
|
+
}
|
57
|
+
if (typeof error === "string") {
|
58
|
+
return error;
|
59
|
+
}
|
60
|
+
if (error instanceof Error) {
|
61
|
+
return error.message;
|
62
|
+
}
|
63
|
+
return JSON.stringify(error);
|
64
|
+
}
|
65
|
+
|
66
|
+
// spec/errors/load-api-key-error.ts
|
67
|
+
var LoadAPIKeyError = class extends Error {
|
68
|
+
constructor({ message }) {
|
69
|
+
super(message);
|
70
|
+
this.name = "AI_LoadAPIKeyError";
|
71
|
+
}
|
72
|
+
static isLoadAPIKeyError(error) {
|
73
|
+
return error instanceof Error && error.name === "AI_LoadAPIKeyError";
|
74
|
+
}
|
75
|
+
toJSON() {
|
76
|
+
return {
|
77
|
+
name: this.name,
|
78
|
+
message: this.message
|
79
|
+
};
|
80
|
+
}
|
81
|
+
};
|
82
|
+
|
83
|
+
// spec/util/load-api-key.ts
|
84
|
+
function loadApiKey({
|
85
|
+
apiKey,
|
86
|
+
environmentVariableName,
|
87
|
+
apiKeyParameterName = "apiKey",
|
88
|
+
description
|
89
|
+
}) {
|
90
|
+
if (typeof apiKey === "string") {
|
91
|
+
return apiKey;
|
92
|
+
}
|
93
|
+
if (apiKey != null) {
|
94
|
+
throw new LoadAPIKeyError({
|
95
|
+
message: `${description} API key must be a string.`
|
96
|
+
});
|
97
|
+
}
|
98
|
+
if (typeof process === "undefined") {
|
99
|
+
throw new LoadAPIKeyError({
|
100
|
+
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
|
101
|
+
});
|
102
|
+
}
|
103
|
+
apiKey = process.env[environmentVariableName];
|
104
|
+
if (apiKey == null) {
|
105
|
+
throw new LoadAPIKeyError({
|
106
|
+
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
|
107
|
+
});
|
108
|
+
}
|
109
|
+
if (typeof apiKey !== "string") {
|
110
|
+
throw new LoadAPIKeyError({
|
111
|
+
message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
|
112
|
+
});
|
113
|
+
}
|
114
|
+
return apiKey;
|
115
|
+
}
|
116
|
+
|
117
|
+
// spec/util/parse-json.ts
|
118
|
+
import SecureJSON from "secure-json-parse";
|
119
|
+
|
120
|
+
// spec/errors/json-parse-error.ts
|
121
|
+
var JSONParseError = class extends Error {
|
122
|
+
constructor({ text, cause }) {
|
123
|
+
super(
|
124
|
+
`JSON parsing failed: Text: ${text}.
|
125
|
+
Error message: ${getErrorMessage(cause)}`
|
126
|
+
);
|
127
|
+
this.name = "AI_JSONParseError";
|
128
|
+
this.cause = cause;
|
129
|
+
this.text = text;
|
130
|
+
}
|
131
|
+
static isJSONParseError(error) {
|
132
|
+
return error instanceof Error && error.name === "AI_JSONParseError" && typeof error.text === "string" && typeof error.cause === "string";
|
133
|
+
}
|
134
|
+
toJSON() {
|
135
|
+
return {
|
136
|
+
name: this.name,
|
137
|
+
message: this.message,
|
138
|
+
cause: this.cause,
|
139
|
+
stack: this.stack,
|
140
|
+
valueText: this.text
|
141
|
+
};
|
142
|
+
}
|
143
|
+
};
|
144
|
+
|
145
|
+
// spec/errors/type-validation-error.ts
|
146
|
+
var TypeValidationError = class extends Error {
|
147
|
+
constructor({ value, cause }) {
|
148
|
+
super(
|
149
|
+
`Type validation failed: Value: ${JSON.stringify(value)}.
|
150
|
+
Error message: ${getErrorMessage(cause)}`
|
151
|
+
);
|
152
|
+
this.name = "AI_TypeValidationError";
|
153
|
+
this.cause = cause;
|
154
|
+
this.value = value;
|
155
|
+
}
|
156
|
+
static isTypeValidationError(error) {
|
157
|
+
return error instanceof Error && error.name === "AI_TypeValidationError" && typeof error.value === "string" && typeof error.cause === "string";
|
158
|
+
}
|
159
|
+
toJSON() {
|
160
|
+
return {
|
161
|
+
name: this.name,
|
162
|
+
message: this.message,
|
163
|
+
cause: this.cause,
|
164
|
+
stack: this.stack,
|
165
|
+
value: this.value
|
166
|
+
};
|
167
|
+
}
|
168
|
+
};
|
169
|
+
|
170
|
+
// spec/util/validate-types.ts
|
171
|
+
function validateTypes({
|
172
|
+
value,
|
173
|
+
schema
|
174
|
+
}) {
|
175
|
+
try {
|
176
|
+
return schema.parse(value);
|
177
|
+
} catch (error) {
|
178
|
+
throw new TypeValidationError({ value, cause: error });
|
179
|
+
}
|
180
|
+
}
|
181
|
+
function safeValidateTypes({
|
182
|
+
value,
|
183
|
+
schema
|
184
|
+
}) {
|
185
|
+
try {
|
186
|
+
const validationResult = schema.safeParse(value);
|
187
|
+
if (validationResult.success) {
|
188
|
+
return {
|
189
|
+
success: true,
|
190
|
+
value: validationResult.data
|
191
|
+
};
|
192
|
+
}
|
193
|
+
return {
|
194
|
+
success: false,
|
195
|
+
error: new TypeValidationError({
|
196
|
+
value,
|
197
|
+
cause: validationResult.error
|
198
|
+
})
|
199
|
+
};
|
200
|
+
} catch (error) {
|
201
|
+
return {
|
202
|
+
success: false,
|
203
|
+
error: TypeValidationError.isTypeValidationError(error) ? error : new TypeValidationError({ value, cause: error })
|
204
|
+
};
|
205
|
+
}
|
206
|
+
}
|
207
|
+
|
208
|
+
// spec/util/parse-json.ts
|
209
|
+
function parseJSON({
|
210
|
+
text,
|
211
|
+
schema
|
212
|
+
}) {
|
213
|
+
try {
|
214
|
+
const value = SecureJSON.parse(text);
|
215
|
+
if (schema == null) {
|
216
|
+
return value;
|
217
|
+
}
|
218
|
+
return validateTypes({ value, schema });
|
219
|
+
} catch (error) {
|
220
|
+
if (JSONParseError.isJSONParseError(error) || TypeValidationError.isTypeValidationError(error)) {
|
221
|
+
throw error;
|
222
|
+
}
|
223
|
+
throw new JSONParseError({ text, cause: error });
|
224
|
+
}
|
225
|
+
}
|
226
|
+
function safeParseJSON({
|
227
|
+
text,
|
228
|
+
schema
|
229
|
+
}) {
|
230
|
+
try {
|
231
|
+
const value = SecureJSON.parse(text);
|
232
|
+
if (schema == null) {
|
233
|
+
return {
|
234
|
+
success: true,
|
235
|
+
value
|
236
|
+
};
|
237
|
+
}
|
238
|
+
return safeValidateTypes({ value, schema });
|
239
|
+
} catch (error) {
|
240
|
+
return {
|
241
|
+
success: false,
|
242
|
+
error: JSONParseError.isJSONParseError(error) ? error : new JSONParseError({ text, cause: error })
|
243
|
+
};
|
244
|
+
}
|
245
|
+
}
|
246
|
+
|
247
|
+
// spec/util/post-to-api.ts
|
248
|
+
var postJsonToApi = async ({
|
249
|
+
url,
|
250
|
+
headers,
|
251
|
+
body,
|
252
|
+
failedResponseHandler,
|
253
|
+
successfulResponseHandler,
|
254
|
+
abortSignal
|
255
|
+
}) => postToApi({
|
256
|
+
url,
|
257
|
+
headers: {
|
258
|
+
...headers,
|
259
|
+
"Content-Type": "application/json"
|
260
|
+
},
|
261
|
+
body: {
|
262
|
+
content: JSON.stringify(body),
|
263
|
+
values: body
|
264
|
+
},
|
265
|
+
failedResponseHandler,
|
266
|
+
successfulResponseHandler,
|
267
|
+
abortSignal
|
268
|
+
});
|
269
|
+
var postToApi = async ({
|
270
|
+
url,
|
271
|
+
headers = {},
|
272
|
+
body,
|
273
|
+
successfulResponseHandler,
|
274
|
+
failedResponseHandler,
|
275
|
+
abortSignal
|
276
|
+
}) => {
|
277
|
+
try {
|
278
|
+
const definedHeaders = Object.fromEntries(
|
279
|
+
Object.entries(headers).filter(([_key, value]) => value != null)
|
280
|
+
);
|
281
|
+
const response = await fetch(url, {
|
282
|
+
method: "POST",
|
283
|
+
headers: definedHeaders,
|
284
|
+
body: body.content,
|
285
|
+
signal: abortSignal
|
286
|
+
});
|
287
|
+
if (!response.ok) {
|
288
|
+
try {
|
289
|
+
throw await failedResponseHandler({
|
290
|
+
response,
|
291
|
+
url,
|
292
|
+
requestBodyValues: body.values
|
293
|
+
});
|
294
|
+
} catch (error) {
|
295
|
+
if (error instanceof Error) {
|
296
|
+
if (error.name === "AbortError" || APICallError.isAPICallError(error)) {
|
297
|
+
throw error;
|
298
|
+
}
|
299
|
+
}
|
300
|
+
throw new APICallError({
|
301
|
+
message: "Failed to process error response",
|
302
|
+
cause: error,
|
303
|
+
statusCode: response.status,
|
304
|
+
url,
|
305
|
+
requestBodyValues: body.values
|
306
|
+
});
|
307
|
+
}
|
308
|
+
}
|
309
|
+
try {
|
310
|
+
return await successfulResponseHandler({
|
311
|
+
response,
|
312
|
+
url,
|
313
|
+
requestBodyValues: body.values
|
314
|
+
});
|
315
|
+
} catch (error) {
|
316
|
+
if (error instanceof Error) {
|
317
|
+
if (error.name === "AbortError" || APICallError.isAPICallError(error)) {
|
318
|
+
throw error;
|
319
|
+
}
|
320
|
+
}
|
321
|
+
throw new APICallError({
|
322
|
+
message: "Failed to process successful response",
|
323
|
+
cause: error,
|
324
|
+
statusCode: response.status,
|
325
|
+
url,
|
326
|
+
requestBodyValues: body.values
|
327
|
+
});
|
328
|
+
}
|
329
|
+
} catch (error) {
|
330
|
+
if (error instanceof Error) {
|
331
|
+
if (error.name === "AbortError") {
|
332
|
+
throw error;
|
333
|
+
}
|
334
|
+
}
|
335
|
+
if (error instanceof TypeError && error.message === "fetch failed") {
|
336
|
+
const cause = error.cause;
|
337
|
+
if (cause != null) {
|
338
|
+
throw new APICallError({
|
339
|
+
message: `Cannot connect to API: ${cause.message}`,
|
340
|
+
cause,
|
341
|
+
url,
|
342
|
+
requestBodyValues: body.values,
|
343
|
+
isRetryable: true
|
344
|
+
// retry when network error
|
345
|
+
});
|
346
|
+
}
|
347
|
+
}
|
348
|
+
throw error;
|
349
|
+
}
|
350
|
+
};
|
351
|
+
|
352
|
+
// spec/util/response-handler.ts
|
353
|
+
import {
|
354
|
+
EventSourceParserStream
|
355
|
+
} from "eventsource-parser/stream";
|
356
|
+
|
357
|
+
// spec/errors/no-response-body-error.ts
|
358
|
+
var NoResponseBodyError = class extends Error {
|
359
|
+
constructor({ message = "No response body" } = {}) {
|
360
|
+
super(message);
|
361
|
+
this.name = "AI_NoResponseBodyError";
|
362
|
+
}
|
363
|
+
static isNoResponseBodyError(error) {
|
364
|
+
return error instanceof Error && error.name === "AI_NoResponseBodyError";
|
365
|
+
}
|
366
|
+
toJSON() {
|
367
|
+
return {
|
368
|
+
name: this.name,
|
369
|
+
message: this.message,
|
370
|
+
stack: this.stack
|
371
|
+
};
|
372
|
+
}
|
373
|
+
};
|
374
|
+
|
375
|
+
// spec/util/response-handler.ts
|
376
|
+
var createJsonErrorResponseHandler = ({
|
377
|
+
errorSchema,
|
378
|
+
errorToMessage,
|
379
|
+
isRetryable
|
380
|
+
}) => async ({ response, url, requestBodyValues }) => {
|
381
|
+
const responseBody = await response.text();
|
382
|
+
if (responseBody.trim() === "") {
|
383
|
+
return new APICallError({
|
384
|
+
message: response.statusText,
|
385
|
+
url,
|
386
|
+
requestBodyValues,
|
387
|
+
statusCode: response.status,
|
388
|
+
responseBody,
|
389
|
+
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
|
390
|
+
});
|
391
|
+
}
|
392
|
+
try {
|
393
|
+
const parsedError = parseJSON({
|
394
|
+
text: responseBody,
|
395
|
+
schema: errorSchema
|
396
|
+
});
|
397
|
+
return new APICallError({
|
398
|
+
message: errorToMessage(parsedError),
|
399
|
+
url,
|
400
|
+
requestBodyValues,
|
401
|
+
statusCode: response.status,
|
402
|
+
responseBody,
|
403
|
+
data: parsedError,
|
404
|
+
isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
|
405
|
+
});
|
406
|
+
} catch (parseError) {
|
407
|
+
return new APICallError({
|
408
|
+
message: response.statusText,
|
409
|
+
url,
|
410
|
+
requestBodyValues,
|
411
|
+
statusCode: response.status,
|
412
|
+
responseBody,
|
413
|
+
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
|
414
|
+
});
|
415
|
+
}
|
416
|
+
};
|
417
|
+
var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
|
418
|
+
if (response.body == null) {
|
419
|
+
throw new NoResponseBodyError();
|
420
|
+
}
|
421
|
+
return response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(
|
422
|
+
new TransformStream({
|
423
|
+
transform({ data }, controller) {
|
424
|
+
if (data === "[DONE]") {
|
425
|
+
return;
|
426
|
+
}
|
427
|
+
controller.enqueue(
|
428
|
+
safeParseJSON({
|
429
|
+
text: data,
|
430
|
+
schema: chunkSchema
|
431
|
+
})
|
432
|
+
);
|
433
|
+
}
|
434
|
+
})
|
435
|
+
);
|
436
|
+
};
|
437
|
+
var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
|
438
|
+
const responseBody = await response.text();
|
439
|
+
const parsedResult = safeParseJSON({
|
440
|
+
text: responseBody,
|
441
|
+
schema: responseSchema
|
442
|
+
});
|
443
|
+
if (!parsedResult.success) {
|
444
|
+
throw new APICallError({
|
445
|
+
message: "Invalid JSON response",
|
446
|
+
cause: parsedResult.error,
|
447
|
+
statusCode: response.status,
|
448
|
+
responseBody,
|
449
|
+
url,
|
450
|
+
requestBodyValues
|
451
|
+
});
|
452
|
+
}
|
453
|
+
return parsedResult.value;
|
454
|
+
};
|
455
|
+
|
456
|
+
// spec/util/uint8-utils.ts
|
457
|
+
function convertUint8ArrayToBase64(array) {
|
458
|
+
let latin1string = "";
|
459
|
+
for (let i = 0; i < array.length; i++) {
|
460
|
+
latin1string += String.fromCodePoint(array[i]);
|
461
|
+
}
|
462
|
+
return globalThis.btoa(latin1string);
|
463
|
+
}
|
464
|
+
|
465
|
+
// spec/errors/unsupported-functionality-error.ts
|
466
|
+
var UnsupportedFunctionalityError = class extends Error {
|
467
|
+
constructor({
|
468
|
+
provider,
|
469
|
+
functionality
|
470
|
+
}) {
|
471
|
+
super(
|
472
|
+
`'${functionality}' functionality not supported by the '${provider}' provider.`
|
473
|
+
);
|
474
|
+
this.name = "AI_UnsupportedFunctionalityError";
|
475
|
+
this.provider = provider;
|
476
|
+
this.functionality = functionality;
|
477
|
+
}
|
478
|
+
static isUnsupportedFunctionalityError(error) {
|
479
|
+
return error instanceof Error && error.name === "AI_UnsupportedFunctionalityError" && typeof error.provider === "string" && typeof error.functionality === "string";
|
480
|
+
}
|
481
|
+
toJSON() {
|
482
|
+
return {
|
483
|
+
name: this.name,
|
484
|
+
message: this.message,
|
485
|
+
stack: this.stack,
|
486
|
+
provider: this.provider,
|
487
|
+
functionality: this.functionality
|
488
|
+
};
|
489
|
+
}
|
490
|
+
};
|
491
|
+
|
492
|
+
// anthropic/anthropic-messages-language-model.ts
|
493
|
+
import { z as z2 } from "zod";
|
494
|
+
|
495
|
+
// anthropic/anthropic-error.ts
|
496
|
+
import { z } from "zod";
|
497
|
+
var anthropicErrorDataSchema = z.object({
|
498
|
+
type: z.literal("error"),
|
499
|
+
error: z.object({
|
500
|
+
type: z.string(),
|
501
|
+
message: z.string()
|
502
|
+
})
|
503
|
+
});
|
504
|
+
var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
|
505
|
+
errorSchema: anthropicErrorDataSchema,
|
506
|
+
errorToMessage: (data) => data.error.message
|
507
|
+
});
|
508
|
+
|
509
|
+
// anthropic/map-anthropic-finish-reason.ts
|
510
|
+
function mapAnthropicFinishReason(finishReason) {
|
511
|
+
switch (finishReason) {
|
512
|
+
case "end_turn":
|
513
|
+
case "stop_sequence":
|
514
|
+
return "stop";
|
515
|
+
case "max_tokens":
|
516
|
+
return "length";
|
517
|
+
default:
|
518
|
+
return "other";
|
519
|
+
}
|
520
|
+
}
|
521
|
+
|
522
|
+
// anthropic/convert-to-anthropic-messages-prompt.ts
|
523
|
+
function convertToAnthropicMessagesPrompt({
|
524
|
+
prompt,
|
525
|
+
provider
|
526
|
+
}) {
|
527
|
+
let system;
|
528
|
+
const messages = [];
|
529
|
+
for (const { role, content } of prompt) {
|
530
|
+
switch (role) {
|
531
|
+
case "system": {
|
532
|
+
system = content;
|
533
|
+
break;
|
534
|
+
}
|
535
|
+
case "user": {
|
536
|
+
messages.push({
|
537
|
+
role: "user",
|
538
|
+
content: content.map((part) => {
|
539
|
+
var _a;
|
540
|
+
switch (part.type) {
|
541
|
+
case "text": {
|
542
|
+
return { type: "text", text: part.text };
|
543
|
+
}
|
544
|
+
case "image": {
|
545
|
+
if (part.image instanceof URL) {
|
546
|
+
throw new UnsupportedFunctionalityError({
|
547
|
+
provider,
|
548
|
+
functionality: "URL image parts"
|
549
|
+
});
|
550
|
+
} else {
|
551
|
+
return {
|
552
|
+
type: "image",
|
553
|
+
source: {
|
554
|
+
type: "base64",
|
555
|
+
media_type: (_a = part.mimeType) != null ? _a : "image/jpeg",
|
556
|
+
data: convertUint8ArrayToBase64(part.image)
|
557
|
+
}
|
558
|
+
};
|
559
|
+
}
|
560
|
+
}
|
561
|
+
}
|
562
|
+
})
|
563
|
+
});
|
564
|
+
break;
|
565
|
+
}
|
566
|
+
case "assistant": {
|
567
|
+
let text = "";
|
568
|
+
for (const part of content) {
|
569
|
+
switch (part.type) {
|
570
|
+
case "text": {
|
571
|
+
text += part.text;
|
572
|
+
break;
|
573
|
+
}
|
574
|
+
case "tool-call": {
|
575
|
+
throw new UnsupportedFunctionalityError({
|
576
|
+
provider,
|
577
|
+
functionality: "tool-call-part"
|
578
|
+
});
|
579
|
+
}
|
580
|
+
default: {
|
581
|
+
const _exhaustiveCheck = part;
|
582
|
+
throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
|
583
|
+
}
|
584
|
+
}
|
585
|
+
}
|
586
|
+
messages.push({
|
587
|
+
role: "assistant",
|
588
|
+
content: text
|
589
|
+
});
|
590
|
+
break;
|
591
|
+
}
|
592
|
+
case "tool": {
|
593
|
+
throw new UnsupportedFunctionalityError({
|
594
|
+
provider,
|
595
|
+
functionality: "tool-role"
|
596
|
+
});
|
597
|
+
}
|
598
|
+
default: {
|
599
|
+
const _exhaustiveCheck = role;
|
600
|
+
throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
|
601
|
+
}
|
602
|
+
}
|
603
|
+
}
|
604
|
+
return {
|
605
|
+
system,
|
606
|
+
messages
|
607
|
+
};
|
608
|
+
}
|
609
|
+
|
610
|
+
// anthropic/anthropic-messages-language-model.ts
|
611
|
+
var AnthropicMessagesLanguageModel = class {
|
612
|
+
constructor(modelId, settings, config) {
|
613
|
+
this.specificationVersion = "v1";
|
614
|
+
this.defaultObjectGenerationMode = "json";
|
615
|
+
this.modelId = modelId;
|
616
|
+
this.settings = settings;
|
617
|
+
this.config = config;
|
618
|
+
}
|
619
|
+
get provider() {
|
620
|
+
return this.config.provider;
|
621
|
+
}
|
622
|
+
getArgs({
|
623
|
+
mode,
|
624
|
+
prompt,
|
625
|
+
maxTokens,
|
626
|
+
temperature,
|
627
|
+
topP,
|
628
|
+
frequencyPenalty,
|
629
|
+
presencePenalty,
|
630
|
+
seed
|
631
|
+
}) {
|
632
|
+
var _a;
|
633
|
+
const type = mode.type;
|
634
|
+
const warnings = [];
|
635
|
+
if (frequencyPenalty != null) {
|
636
|
+
warnings.push({
|
637
|
+
type: "unsupported-setting",
|
638
|
+
setting: "frequencyPenalty"
|
639
|
+
});
|
640
|
+
}
|
641
|
+
if (presencePenalty != null) {
|
642
|
+
warnings.push({
|
643
|
+
type: "unsupported-setting",
|
644
|
+
setting: "presencePenalty"
|
645
|
+
});
|
646
|
+
}
|
647
|
+
if (seed != null) {
|
648
|
+
warnings.push({
|
649
|
+
type: "unsupported-setting",
|
650
|
+
setting: "seed"
|
651
|
+
});
|
652
|
+
}
|
653
|
+
const messagesPrompt = convertToAnthropicMessagesPrompt({
|
654
|
+
provider: this.provider,
|
655
|
+
prompt
|
656
|
+
});
|
657
|
+
const baseArgs = {
|
658
|
+
// model id:
|
659
|
+
model: this.modelId,
|
660
|
+
// model specific settings:
|
661
|
+
top_k: this.settings.topK,
|
662
|
+
// standardized settings:
|
663
|
+
max_tokens: maxTokens != null ? maxTokens : 4096,
|
664
|
+
// 4096: max model output tokens
|
665
|
+
temperature,
|
666
|
+
// uses 0..1 scale
|
667
|
+
top_p: topP,
|
668
|
+
// prompt:
|
669
|
+
system: messagesPrompt.system,
|
670
|
+
messages: messagesPrompt.messages
|
671
|
+
};
|
672
|
+
switch (type) {
|
673
|
+
case "regular": {
|
674
|
+
const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
|
675
|
+
return {
|
676
|
+
args: {
|
677
|
+
...baseArgs,
|
678
|
+
tools: tools == null ? void 0 : tools.map((tool) => ({
|
679
|
+
type: "function",
|
680
|
+
function: {
|
681
|
+
name: tool.name,
|
682
|
+
description: tool.description,
|
683
|
+
parameters: tool.parameters
|
684
|
+
}
|
685
|
+
}))
|
686
|
+
},
|
687
|
+
warnings
|
688
|
+
};
|
689
|
+
}
|
690
|
+
case "object-json": {
|
691
|
+
return {
|
692
|
+
args: {
|
693
|
+
...baseArgs,
|
694
|
+
response_format: { type: "json_object" }
|
695
|
+
},
|
696
|
+
warnings
|
697
|
+
};
|
698
|
+
}
|
699
|
+
case "object-tool": {
|
700
|
+
return {
|
701
|
+
args: {
|
702
|
+
...baseArgs,
|
703
|
+
tool_choice: "any",
|
704
|
+
tools: [{ type: "function", function: mode.tool }]
|
705
|
+
},
|
706
|
+
warnings
|
707
|
+
};
|
708
|
+
}
|
709
|
+
case "object-grammar": {
|
710
|
+
throw new UnsupportedFunctionalityError({
|
711
|
+
functionality: "object-grammar mode",
|
712
|
+
provider: this.provider
|
713
|
+
});
|
714
|
+
}
|
715
|
+
default: {
|
716
|
+
const _exhaustiveCheck = type;
|
717
|
+
throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
|
718
|
+
}
|
719
|
+
}
|
720
|
+
}
|
721
|
+
async doGenerate(options) {
|
722
|
+
const { args, warnings } = this.getArgs(options);
|
723
|
+
const response = await postJsonToApi({
|
724
|
+
url: `${this.config.baseUrl}/messages`,
|
725
|
+
headers: this.config.headers(),
|
726
|
+
body: args,
|
727
|
+
failedResponseHandler: anthropicFailedResponseHandler,
|
728
|
+
successfulResponseHandler: createJsonResponseHandler(
|
729
|
+
anthropicMessagesResponseSchema
|
730
|
+
),
|
731
|
+
abortSignal: options.abortSignal
|
732
|
+
});
|
733
|
+
const { messages: rawPrompt, ...rawSettings } = args;
|
734
|
+
return {
|
735
|
+
text: response.content.map(({ text }) => text).join(""),
|
736
|
+
finishReason: mapAnthropicFinishReason(response.stop_reason),
|
737
|
+
usage: {
|
738
|
+
promptTokens: response.usage.input_tokens,
|
739
|
+
completionTokens: response.usage.output_tokens
|
740
|
+
},
|
741
|
+
rawCall: { rawPrompt, rawSettings },
|
742
|
+
warnings
|
743
|
+
};
|
744
|
+
}
|
745
|
+
async doStream(options) {
|
746
|
+
const { args, warnings } = this.getArgs(options);
|
747
|
+
const response = await postJsonToApi({
|
748
|
+
url: `${this.config.baseUrl}/messages`,
|
749
|
+
headers: this.config.headers(),
|
750
|
+
body: {
|
751
|
+
...args,
|
752
|
+
stream: true
|
753
|
+
},
|
754
|
+
failedResponseHandler: anthropicFailedResponseHandler,
|
755
|
+
successfulResponseHandler: createEventSourceResponseHandler(
|
756
|
+
anthropicMessagesChunkSchema
|
757
|
+
),
|
758
|
+
abortSignal: options.abortSignal
|
759
|
+
});
|
760
|
+
const { messages: rawPrompt, ...rawSettings } = args;
|
761
|
+
let finishReason = "other";
|
762
|
+
const usage = {
|
763
|
+
promptTokens: Number.NaN,
|
764
|
+
completionTokens: Number.NaN
|
765
|
+
};
|
766
|
+
const generateId2 = this.config.generateId;
|
767
|
+
return {
|
768
|
+
stream: response.pipeThrough(
|
769
|
+
new TransformStream({
|
770
|
+
transform(chunk, controller) {
|
771
|
+
if (!chunk.success) {
|
772
|
+
controller.enqueue({ type: "error", error: chunk.error });
|
773
|
+
return;
|
774
|
+
}
|
775
|
+
const value = chunk.value;
|
776
|
+
switch (value.type) {
|
777
|
+
case "ping":
|
778
|
+
case "content_block_start":
|
779
|
+
case "content_block_stop": {
|
780
|
+
return;
|
781
|
+
}
|
782
|
+
case "content_block_delta": {
|
783
|
+
controller.enqueue({
|
784
|
+
type: "text-delta",
|
785
|
+
textDelta: value.delta.text
|
786
|
+
});
|
787
|
+
return;
|
788
|
+
}
|
789
|
+
case "message_start": {
|
790
|
+
usage.promptTokens = value.message.usage.input_tokens;
|
791
|
+
usage.completionTokens = value.message.usage.output_tokens;
|
792
|
+
return;
|
793
|
+
}
|
794
|
+
case "message_delta": {
|
795
|
+
usage.completionTokens = value.usage.output_tokens;
|
796
|
+
finishReason = mapAnthropicFinishReason(
|
797
|
+
value.delta.stop_reason
|
798
|
+
);
|
799
|
+
return;
|
800
|
+
}
|
801
|
+
case "message_stop": {
|
802
|
+
controller.enqueue({ type: "finish", finishReason, usage });
|
803
|
+
return;
|
804
|
+
}
|
805
|
+
default: {
|
806
|
+
const _exhaustiveCheck = value;
|
807
|
+
throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);
|
808
|
+
}
|
809
|
+
}
|
810
|
+
}
|
811
|
+
})
|
812
|
+
),
|
813
|
+
rawCall: { rawPrompt, rawSettings },
|
814
|
+
warnings
|
815
|
+
};
|
816
|
+
}
|
817
|
+
};
|
818
|
+
var anthropicMessagesResponseSchema = z2.object({
|
819
|
+
type: z2.literal("message"),
|
820
|
+
content: z2.array(
|
821
|
+
z2.object({
|
822
|
+
type: z2.literal("text"),
|
823
|
+
text: z2.string()
|
824
|
+
})
|
825
|
+
),
|
826
|
+
stop_reason: z2.string().optional().nullable(),
|
827
|
+
usage: z2.object({
|
828
|
+
input_tokens: z2.number(),
|
829
|
+
output_tokens: z2.number()
|
830
|
+
})
|
831
|
+
});
|
832
|
+
var anthropicMessagesChunkSchema = z2.discriminatedUnion("type", [
|
833
|
+
z2.object({
|
834
|
+
type: z2.literal("message_start"),
|
835
|
+
message: z2.object({
|
836
|
+
usage: z2.object({
|
837
|
+
input_tokens: z2.number(),
|
838
|
+
output_tokens: z2.number()
|
839
|
+
})
|
840
|
+
})
|
841
|
+
}),
|
842
|
+
z2.object({
|
843
|
+
type: z2.literal("content_block_start"),
|
844
|
+
index: z2.number(),
|
845
|
+
content_block: z2.object({
|
846
|
+
type: z2.literal("text"),
|
847
|
+
text: z2.string()
|
848
|
+
})
|
849
|
+
}),
|
850
|
+
z2.object({
|
851
|
+
type: z2.literal("content_block_delta"),
|
852
|
+
index: z2.number(),
|
853
|
+
delta: z2.object({
|
854
|
+
type: z2.literal("text_delta"),
|
855
|
+
text: z2.string()
|
856
|
+
})
|
857
|
+
}),
|
858
|
+
z2.object({
|
859
|
+
type: z2.literal("content_block_stop"),
|
860
|
+
index: z2.number()
|
861
|
+
}),
|
862
|
+
z2.object({
|
863
|
+
type: z2.literal("message_delta"),
|
864
|
+
delta: z2.object({ stop_reason: z2.string().optional().nullable() }),
|
865
|
+
usage: z2.object({ output_tokens: z2.number() })
|
866
|
+
}),
|
867
|
+
z2.object({
|
868
|
+
type: z2.literal("message_stop")
|
869
|
+
}),
|
870
|
+
z2.object({
|
871
|
+
type: z2.literal("ping")
|
872
|
+
})
|
873
|
+
]);
|
874
|
+
|
875
|
+
// anthropic/anthropic-facade.ts
|
876
|
+
var Anthropic = class {
|
877
|
+
constructor(options = {}) {
|
878
|
+
var _a;
|
879
|
+
this.baseUrl = options.baseUrl;
|
880
|
+
this.apiKey = options.apiKey;
|
881
|
+
this.generateId = (_a = options.generateId) != null ? _a : generateId;
|
882
|
+
}
|
883
|
+
get baseConfig() {
|
884
|
+
var _a;
|
885
|
+
return {
|
886
|
+
baseUrl: (_a = this.baseUrl) != null ? _a : "https://api.anthropic.com/v1",
|
887
|
+
headers: () => ({
|
888
|
+
"anthropic-version": "2023-06-01",
|
889
|
+
"x-api-key": loadApiKey({
|
890
|
+
apiKey: this.apiKey,
|
891
|
+
environmentVariableName: "ANTHROPIC_API_KEY",
|
892
|
+
description: "Anthropic"
|
893
|
+
})
|
894
|
+
})
|
895
|
+
};
|
896
|
+
}
|
897
|
+
messages(modelId, settings = {}) {
|
898
|
+
return new AnthropicMessagesLanguageModel(modelId, settings, {
|
899
|
+
provider: "anthropic.messages",
|
900
|
+
...this.baseConfig,
|
901
|
+
generateId: this.generateId
|
902
|
+
});
|
903
|
+
}
|
904
|
+
};
|
905
|
+
var anthropic = new Anthropic();
|
906
|
+
export {
|
907
|
+
Anthropic,
|
908
|
+
anthropic
|
909
|
+
};
|
910
|
+
//# sourceMappingURL=index.mjs.map
|