@anyr/ai-sdk-provider 0.1.0

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/dist/index.js ADDED
@@ -0,0 +1,739 @@
1
+ 'use strict';
2
+
3
+ var providerUtils = require('@ai-sdk/provider-utils');
4
+ var zod = require('zod');
5
+ var provider = require('@ai-sdk/provider');
6
+ var sdk = require('@anyr/sdk');
7
+
8
+ // src/anyrouter-chat-language-model.ts
9
+ function convertToAnyRouterChatMessages(prompt) {
10
+ const messages = [];
11
+ for (const message of prompt) {
12
+ switch (message.role) {
13
+ case "system":
14
+ messages.push({ role: "system", content: message.content });
15
+ break;
16
+ case "user":
17
+ messages.push(convertUserMessage(message));
18
+ break;
19
+ case "assistant":
20
+ messages.push(convertAssistantMessage(message));
21
+ break;
22
+ case "tool":
23
+ for (const part of message.content) {
24
+ if (part.type === "tool-result") {
25
+ messages.push(convertToolResultMessage(part));
26
+ }
27
+ }
28
+ break;
29
+ default: {
30
+ const _exhaustive = message;
31
+ throw new Error(`Unsupported message role: ${_exhaustive.role}`);
32
+ }
33
+ }
34
+ }
35
+ return messages;
36
+ }
37
+ function convertUserMessage(message) {
38
+ if (message.content.length === 1 && message.content[0].type === "text") {
39
+ return { role: "user", content: message.content[0].text };
40
+ }
41
+ const parts = [];
42
+ for (const part of message.content) {
43
+ if (part.type === "text") {
44
+ parts.push({ type: "text", text: part.text });
45
+ } else if (part.type === "file") {
46
+ const filePart = part;
47
+ const mediaType = filePart.mediaType;
48
+ const url = toDataUrlOrString(filePart.data, mediaType);
49
+ if (mediaType.startsWith("image/")) {
50
+ parts.push({ type: "image_url", image_url: { url } });
51
+ } else {
52
+ parts.push({ type: "file", file: { url, media_type: mediaType } });
53
+ }
54
+ } else {
55
+ const unknown = part;
56
+ throw new provider.UnsupportedFunctionalityError({
57
+ functionality: `User message part type: ${unknown.type ?? "unknown"}`
58
+ });
59
+ }
60
+ }
61
+ return { role: "user", content: parts };
62
+ }
63
+ function convertAssistantMessage(message) {
64
+ let text = "";
65
+ const toolCalls = [];
66
+ for (const part of message.content) {
67
+ switch (part.type) {
68
+ case "text":
69
+ text += part.text;
70
+ break;
71
+ case "tool-call": {
72
+ const tc = part;
73
+ toolCalls.push({
74
+ id: tc.toolCallId,
75
+ type: "function",
76
+ function: {
77
+ name: tc.toolName,
78
+ arguments: typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input)
79
+ }
80
+ });
81
+ break;
82
+ }
83
+ }
84
+ }
85
+ const result = {
86
+ role: "assistant",
87
+ content: text || null
88
+ };
89
+ if (toolCalls.length > 0) {
90
+ result.tool_calls = toolCalls;
91
+ }
92
+ return result;
93
+ }
94
+ function convertToolResultMessage(part) {
95
+ return {
96
+ role: "tool",
97
+ tool_call_id: part.toolCallId,
98
+ content: toolResultOutputToString(part.output)
99
+ };
100
+ }
101
+ function toolResultOutputToString(output) {
102
+ switch (output.type) {
103
+ case "text":
104
+ return output.value;
105
+ case "json":
106
+ return JSON.stringify(output.value);
107
+ case "error-text":
108
+ return output.value;
109
+ case "error-json":
110
+ return JSON.stringify(output.value);
111
+ case "execution-denied":
112
+ return output.reason ?? "Tool execution denied.";
113
+ case "content": {
114
+ const segments = [];
115
+ for (const c of output.value) {
116
+ if (c.type === "text") {
117
+ segments.push(c.text);
118
+ } else {
119
+ segments.push(`[${c.type}]`);
120
+ }
121
+ }
122
+ return segments.join("\n");
123
+ }
124
+ default:
125
+ return JSON.stringify(output);
126
+ }
127
+ }
128
+ function toDataUrlOrString(data, mediaType) {
129
+ if (data instanceof URL) return data.toString();
130
+ if (typeof data === "string") {
131
+ if (data.startsWith("http") || data.startsWith("data:")) return data;
132
+ return `data:${mediaType};base64,${data}`;
133
+ }
134
+ return `data:${mediaType};base64,${uint8ArrayToBase64(data)}`;
135
+ }
136
+ function uint8ArrayToBase64(bytes) {
137
+ let binary = "";
138
+ for (let i = 0; i < bytes.length; i++) {
139
+ binary += String.fromCharCode(bytes[i]);
140
+ }
141
+ return btoa(binary);
142
+ }
143
+
144
+ // src/anyrouter-chat-language-model.ts
145
+ var anyRouterProviderOptionsSchema = zod.z.object({
146
+ /** Routing preference forwarded as `provider` in the request body. */
147
+ provider: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
148
+ /** Session ID forwarded as `session_id` in the request body. */
149
+ sessionId: zod.z.string().optional(),
150
+ /** Extra body fields merged in last (highest precedence). */
151
+ extraBody: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
152
+ });
153
+ var anyRouterErrorSchema = zod.z.object({
154
+ error: zod.z.object({
155
+ code: zod.z.string().optional(),
156
+ message: zod.z.string().optional(),
157
+ metadata: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
158
+ }).optional()
159
+ });
160
+ var completionUsageSchema = zod.z.object({
161
+ prompt_tokens: zod.z.number().optional(),
162
+ completion_tokens: zod.z.number().optional(),
163
+ total_tokens: zod.z.number().optional()
164
+ });
165
+ var toolCallSchema = zod.z.object({
166
+ id: zod.z.string().optional(),
167
+ type: zod.z.literal("function").optional(),
168
+ function: zod.z.object({
169
+ name: zod.z.string().optional(),
170
+ arguments: zod.z.string().optional()
171
+ }).optional()
172
+ });
173
+ var toolCallDeltaSchema = zod.z.object({
174
+ index: zod.z.number(),
175
+ id: zod.z.string().optional(),
176
+ type: zod.z.literal("function").optional(),
177
+ function: zod.z.object({
178
+ name: zod.z.string().optional(),
179
+ arguments: zod.z.string().optional()
180
+ }).optional()
181
+ });
182
+ var messageSchema = zod.z.object({
183
+ content: zod.z.string().nullish(),
184
+ reasoning_content: zod.z.string().nullish(),
185
+ tool_calls: zod.z.array(toolCallSchema).optional()
186
+ });
187
+ var choiceSchema = zod.z.object({
188
+ message: messageSchema.optional(),
189
+ finish_reason: zod.z.string().nullish()
190
+ });
191
+ var generateResponseSchema = zod.z.object({
192
+ id: zod.z.string().optional(),
193
+ model: zod.z.string().optional(),
194
+ choices: zod.z.array(choiceSchema).optional(),
195
+ usage: completionUsageSchema.optional()
196
+ });
197
+ var deltaSchema = zod.z.object({
198
+ content: zod.z.string().nullish(),
199
+ reasoning_content: zod.z.string().nullish(),
200
+ tool_calls: zod.z.array(toolCallDeltaSchema).optional()
201
+ });
202
+ var streamChoiceSchema = zod.z.object({
203
+ delta: deltaSchema.optional(),
204
+ finish_reason: zod.z.string().nullish()
205
+ });
206
+ var streamChunkSchema = zod.z.object({
207
+ id: zod.z.string().optional(),
208
+ model: zod.z.string().optional(),
209
+ choices: zod.z.array(streamChoiceSchema).optional(),
210
+ usage: completionUsageSchema.optional()
211
+ });
212
+ function mapFinishReason(raw) {
213
+ switch (raw) {
214
+ case "stop":
215
+ return { unified: "stop", raw };
216
+ case "length":
217
+ case "max_tokens":
218
+ return { unified: "length", raw };
219
+ case "tool_calls":
220
+ case "function_call":
221
+ return { unified: "tool-calls", raw };
222
+ case "content_filter":
223
+ return { unified: "content-filter", raw };
224
+ default:
225
+ return { unified: "other", raw: raw ?? void 0 };
226
+ }
227
+ }
228
+ function buildUsage(raw) {
229
+ return {
230
+ inputTokens: {
231
+ total: raw?.prompt_tokens ?? void 0,
232
+ noCache: void 0,
233
+ cacheRead: void 0,
234
+ cacheWrite: void 0
235
+ },
236
+ outputTokens: {
237
+ total: raw?.completion_tokens ?? void 0,
238
+ text: void 0,
239
+ reasoning: void 0
240
+ }
241
+ };
242
+ }
243
+ function emitResponseMetadata(chunk, state, fallbackModelId, controller) {
244
+ if (state.metadataEmitted || !(chunk.id || chunk.model)) return;
245
+ state.metadataEmitted = true;
246
+ controller.enqueue({
247
+ type: "response-metadata",
248
+ id: chunk.id,
249
+ modelId: chunk.model ?? fallbackModelId
250
+ });
251
+ }
252
+ function emitTextDelta(content, state, controller) {
253
+ if (state.activeTextId === null) {
254
+ state.activeTextId = providerUtils.generateId();
255
+ controller.enqueue({ type: "text-start", id: state.activeTextId });
256
+ }
257
+ controller.enqueue({ type: "text-delta", id: state.activeTextId, delta: content });
258
+ }
259
+ function emitToolCallDeltas(toolCalls, acc, controller) {
260
+ for (const tcDelta of toolCalls) {
261
+ const idx = tcDelta.index;
262
+ if (!acc[idx]) acc[idx] = { id: "", name: "", arguments: "", started: false };
263
+ const entry = acc[idx];
264
+ if (tcDelta.id) entry.id = tcDelta.id;
265
+ if (tcDelta.function?.name) entry.name = tcDelta.function.name;
266
+ if (tcDelta.function?.arguments) entry.arguments += tcDelta.function.arguments;
267
+ const toolId = entry.id || `tool-${idx}`;
268
+ if (!entry.started && entry.name) {
269
+ entry.started = true;
270
+ controller.enqueue({ type: "tool-input-start", id: toolId, toolName: entry.name });
271
+ }
272
+ if (tcDelta.function?.arguments) {
273
+ controller.enqueue({
274
+ type: "tool-input-delta",
275
+ id: toolId,
276
+ delta: tcDelta.function.arguments
277
+ });
278
+ }
279
+ }
280
+ }
281
+ function emitFinish(choice, chunk, state, acc, controller) {
282
+ if (state.activeTextId !== null) {
283
+ controller.enqueue({ type: "text-end", id: state.activeTextId });
284
+ state.activeTextId = null;
285
+ }
286
+ for (const [idxStr, entry] of Object.entries(acc)) {
287
+ if (!entry.started) continue;
288
+ const toolId = entry.id || `tool-${idxStr}`;
289
+ controller.enqueue({ type: "tool-input-end", id: toolId });
290
+ controller.enqueue({
291
+ type: "tool-call",
292
+ toolCallId: toolId,
293
+ toolName: entry.name,
294
+ input: entry.arguments
295
+ });
296
+ }
297
+ controller.enqueue({
298
+ type: "finish",
299
+ usage: buildUsage(chunk.usage),
300
+ finishReason: mapFinishReason(choice.finish_reason)
301
+ });
302
+ }
303
+ function mapToolChoice(toolChoice) {
304
+ if (!toolChoice) return void 0;
305
+ switch (toolChoice.type) {
306
+ case "auto":
307
+ return "auto";
308
+ case "none":
309
+ return "none";
310
+ case "required":
311
+ return "required";
312
+ case "tool":
313
+ return { type: "function", function: { name: toolChoice.toolName } };
314
+ }
315
+ }
316
+ function buildResponseFormat(responseFormat) {
317
+ if (!responseFormat) return void 0;
318
+ if (responseFormat.type === "text") return { type: "text" };
319
+ if (responseFormat.type === "json") {
320
+ if (responseFormat.schema) {
321
+ return {
322
+ type: "json_schema",
323
+ json_schema: {
324
+ name: responseFormat.name ?? "response",
325
+ description: responseFormat.description,
326
+ schema: responseFormat.schema,
327
+ strict: true
328
+ }
329
+ };
330
+ }
331
+ return { type: "json_object" };
332
+ }
333
+ return void 0;
334
+ }
335
+ function buildTools(tools) {
336
+ if (!tools || tools.length === 0) return void 0;
337
+ const fns = tools.filter((t) => t.type === "function").map((t) => ({
338
+ type: "function",
339
+ function: {
340
+ name: t.name,
341
+ description: t.description,
342
+ parameters: t.inputSchema,
343
+ strict: t.strict
344
+ }
345
+ }));
346
+ return fns.length > 0 ? fns : void 0;
347
+ }
348
+ function buildRequestBody(modelId, options, settings, stream, perCallOptions) {
349
+ const messages = convertToAnyRouterChatMessages(options.prompt);
350
+ const responseFormat = buildResponseFormat(options.responseFormat);
351
+ const tools = buildTools(options.tools);
352
+ const toolChoice = mapToolChoice(options.toolChoice);
353
+ const provider = perCallOptions.provider ?? settings.provider;
354
+ const sessionId = perCallOptions.sessionId ?? settings.sessionId;
355
+ const extraBody = { ...settings.extraBody, ...perCallOptions.extraBody };
356
+ const body = {
357
+ model: modelId,
358
+ messages,
359
+ ...stream ? { stream: true, stream_options: { include_usage: true } } : {},
360
+ max_tokens: options.maxOutputTokens,
361
+ temperature: options.temperature,
362
+ top_p: options.topP,
363
+ top_k: options.topK,
364
+ stop: options.stopSequences,
365
+ frequency_penalty: options.frequencyPenalty,
366
+ presence_penalty: options.presencePenalty,
367
+ seed: options.seed,
368
+ response_format: responseFormat,
369
+ tools,
370
+ tool_choice: toolChoice,
371
+ provider: provider ?? void 0,
372
+ session_id: sessionId ?? void 0,
373
+ ...extraBody
374
+ };
375
+ for (const key of Object.keys(body)) {
376
+ if (body[key] === void 0) delete body[key];
377
+ }
378
+ return body;
379
+ }
380
+ var AnyRouterChatLanguageModel = class {
381
+ specificationVersion = "v3";
382
+ provider;
383
+ modelId;
384
+ supportedUrls = {};
385
+ config;
386
+ constructor(modelId, config) {
387
+ this.modelId = modelId;
388
+ this.provider = config.provider;
389
+ this.config = config;
390
+ }
391
+ // ─── doGenerate ─────────────────────────────────────────────────────────
392
+ async doGenerate(options) {
393
+ const perCallOptions = await providerUtils.parseProviderOptions({
394
+ provider: "anyrouter",
395
+ providerOptions: options.providerOptions,
396
+ schema: anyRouterProviderOptionsSchema
397
+ }) ?? {};
398
+ const body = buildRequestBody(
399
+ this.modelId,
400
+ options,
401
+ this.config.settings,
402
+ false,
403
+ perCallOptions
404
+ );
405
+ const { value: response, responseHeaders } = await providerUtils.postJsonToApi({
406
+ url: `${this.config.baseURL}/chat/completions`,
407
+ headers: providerUtils.combineHeaders(this.config.headers(), options.headers),
408
+ body,
409
+ failedResponseHandler: providerUtils.createJsonErrorResponseHandler({
410
+ errorSchema: anyRouterErrorSchema,
411
+ errorToMessage: (data) => data.error?.message ?? "AnyRouter API error",
412
+ isRetryable: (response2) => response2.status >= 500
413
+ }),
414
+ successfulResponseHandler: providerUtils.createJsonResponseHandler(generateResponseSchema),
415
+ abortSignal: options.abortSignal,
416
+ fetch: this.config.fetch
417
+ });
418
+ const choice = response.choices?.[0];
419
+ const message = choice?.message;
420
+ const content = [];
421
+ if (message?.content) {
422
+ content.push({ type: "text", text: message.content });
423
+ }
424
+ if (message?.tool_calls && message.tool_calls.length > 0) {
425
+ for (const tc of message.tool_calls) {
426
+ if (tc.id && tc.function?.name) {
427
+ content.push({
428
+ type: "tool-call",
429
+ toolCallId: tc.id,
430
+ toolName: tc.function.name,
431
+ input: tc.function.arguments ?? "{}"
432
+ });
433
+ }
434
+ }
435
+ }
436
+ return {
437
+ content,
438
+ finishReason: mapFinishReason(choice?.finish_reason),
439
+ usage: buildUsage(response.usage),
440
+ warnings: [],
441
+ request: { body },
442
+ response: {
443
+ id: response.id,
444
+ modelId: response.model,
445
+ headers: responseHeaders
446
+ }
447
+ };
448
+ }
449
+ // ─── doStream ───────────────────────────────────────────────────────────
450
+ async doStream(options) {
451
+ const perCallOptions = await providerUtils.parseProviderOptions({
452
+ provider: "anyrouter",
453
+ providerOptions: options.providerOptions,
454
+ schema: anyRouterProviderOptionsSchema
455
+ }) ?? {};
456
+ const body = buildRequestBody(this.modelId, options, this.config.settings, true, perCallOptions);
457
+ const { value: stream, responseHeaders } = await providerUtils.postJsonToApi({
458
+ url: `${this.config.baseURL}/chat/completions`,
459
+ headers: providerUtils.combineHeaders(this.config.headers(), options.headers),
460
+ body,
461
+ failedResponseHandler: providerUtils.createJsonErrorResponseHandler({
462
+ errorSchema: anyRouterErrorSchema,
463
+ errorToMessage: (data) => data.error?.message ?? "AnyRouter API error",
464
+ isRetryable: (response) => response.status >= 500
465
+ }),
466
+ successfulResponseHandler: providerUtils.createEventSourceResponseHandler(streamChunkSchema),
467
+ abortSignal: options.abortSignal,
468
+ fetch: this.config.fetch
469
+ });
470
+ const toolCallAccumulator = {};
471
+ const state = { activeTextId: null, metadataEmitted: false };
472
+ const selfModelId = this.modelId;
473
+ const transformStream = new TransformStream({
474
+ start(controller) {
475
+ controller.enqueue({ type: "stream-start", warnings: [] });
476
+ },
477
+ transform(chunkResult, controller) {
478
+ if (!chunkResult.success) {
479
+ controller.enqueue({ type: "error", error: chunkResult.error });
480
+ return;
481
+ }
482
+ const chunk = chunkResult.value;
483
+ const choice = chunk.choices?.[0];
484
+ emitResponseMetadata(chunk, state, selfModelId, controller);
485
+ const delta = choice?.delta;
486
+ if (delta) {
487
+ if (typeof delta.content === "string" && delta.content.length > 0) {
488
+ emitTextDelta(delta.content, state, controller);
489
+ }
490
+ if (delta.tool_calls) {
491
+ emitToolCallDeltas(delta.tool_calls, toolCallAccumulator, controller);
492
+ }
493
+ }
494
+ if (choice?.finish_reason) {
495
+ emitFinish(choice, chunk, state, toolCallAccumulator, controller);
496
+ }
497
+ },
498
+ flush(controller) {
499
+ if (state.activeTextId !== null) {
500
+ controller.enqueue({ type: "text-end", id: state.activeTextId });
501
+ }
502
+ }
503
+ });
504
+ return {
505
+ stream: stream.pipeThrough(transformStream),
506
+ request: { body },
507
+ response: { headers: responseHeaders }
508
+ };
509
+ }
510
+ };
511
+ var anyRouterErrorSchema2 = zod.z.object({
512
+ error: zod.z.object({
513
+ code: zod.z.string().optional(),
514
+ message: zod.z.string().optional()
515
+ }).optional()
516
+ });
517
+ var embeddingResponseSchema = zod.z.object({
518
+ data: zod.z.array(
519
+ zod.z.object({
520
+ embedding: zod.z.array(zod.z.number())
521
+ })
522
+ ),
523
+ usage: zod.z.object({
524
+ prompt_tokens: zod.z.number().optional(),
525
+ total_tokens: zod.z.number().optional()
526
+ }).optional()
527
+ });
528
+ var AnyRouterEmbeddingModel = class {
529
+ specificationVersion = "v3";
530
+ provider;
531
+ modelId;
532
+ /** No hard per-call limit imposed by the provider layer. */
533
+ maxEmbeddingsPerCall = void 0;
534
+ supportsParallelCalls = true;
535
+ config;
536
+ constructor(modelId, config) {
537
+ this.modelId = modelId;
538
+ this.provider = config.provider;
539
+ this.config = config;
540
+ }
541
+ async doEmbed(options) {
542
+ const { value: response } = await providerUtils.postJsonToApi({
543
+ url: `${this.config.baseURL}/embeddings`,
544
+ headers: providerUtils.combineHeaders(this.config.headers(), options.headers),
545
+ body: {
546
+ model: this.modelId,
547
+ input: options.values
548
+ },
549
+ failedResponseHandler: providerUtils.createJsonErrorResponseHandler({
550
+ errorSchema: anyRouterErrorSchema2,
551
+ errorToMessage: (data) => data.error?.message ?? "AnyRouter embeddings API error",
552
+ isRetryable: (response2) => response2.status >= 500
553
+ }),
554
+ successfulResponseHandler: providerUtils.createJsonResponseHandler(embeddingResponseSchema),
555
+ abortSignal: options.abortSignal,
556
+ fetch: this.config.fetch
557
+ });
558
+ const embeddings = response.data.map((d) => d.embedding);
559
+ const tokens = response.usage?.prompt_tokens ?? response.usage?.total_tokens;
560
+ return {
561
+ embeddings,
562
+ usage: tokens !== void 0 ? { tokens } : void 0,
563
+ warnings: []
564
+ };
565
+ }
566
+ };
567
+ var anyRouterErrorSchema3 = zod.z.object({
568
+ error: zod.z.object({
569
+ code: zod.z.string().optional(),
570
+ message: zod.z.string().optional()
571
+ }).optional()
572
+ });
573
+ var imageGenerationResponseSchema = zod.z.object({
574
+ created: zod.z.number().optional(),
575
+ data: zod.z.array(
576
+ zod.z.object({
577
+ url: zod.z.string().optional(),
578
+ b64_json: zod.z.string().optional(),
579
+ revised_prompt: zod.z.string().optional()
580
+ })
581
+ )
582
+ });
583
+ var AnyRouterImageModel = class {
584
+ specificationVersion = "v3";
585
+ provider;
586
+ modelId;
587
+ /**
588
+ * Most image generation APIs support only 1 image per call via the
589
+ * standard `/images/generations` endpoint.
590
+ */
591
+ maxImagesPerCall = 1;
592
+ config;
593
+ constructor(modelId, config) {
594
+ this.modelId = modelId;
595
+ this.provider = config.provider;
596
+ this.config = config;
597
+ }
598
+ async doGenerate(options) {
599
+ if (options.mask) {
600
+ throw new provider.UnsupportedFunctionalityError({
601
+ functionality: "mask (inpainting) for AnyRouter image generation"
602
+ });
603
+ }
604
+ const warnings = [];
605
+ if (options.n > 1) {
606
+ warnings.push({
607
+ type: "unsupported",
608
+ feature: `n=${options.n} (AnyRouter image endpoint supports n=1 per call)`
609
+ });
610
+ }
611
+ const body = {
612
+ model: this.modelId,
613
+ prompt: options.prompt ?? "",
614
+ n: Math.min(options.n, 1),
615
+ ...options.size ? { size: options.size } : {},
616
+ ...options.seed !== void 0 ? { seed: options.seed } : {},
617
+ response_format: "b64_json"
618
+ };
619
+ const { value: response, responseHeaders } = await providerUtils.postJsonToApi({
620
+ url: `${this.config.baseURL}/images/generations`,
621
+ headers: providerUtils.combineHeaders(this.config.headers(), options.headers),
622
+ body,
623
+ failedResponseHandler: providerUtils.createJsonErrorResponseHandler({
624
+ errorSchema: anyRouterErrorSchema3,
625
+ errorToMessage: (data) => data.error?.message ?? "AnyRouter images API error",
626
+ isRetryable: (res) => res.status >= 500
627
+ }),
628
+ successfulResponseHandler: providerUtils.createJsonResponseHandler(imageGenerationResponseSchema),
629
+ abortSignal: options.abortSignal,
630
+ fetch: this.config.fetch
631
+ });
632
+ const images = [];
633
+ for (const item of response.data) {
634
+ if (item.b64_json) {
635
+ images.push(item.b64_json);
636
+ } else if (item.url) {
637
+ images.push(item.url);
638
+ }
639
+ }
640
+ return {
641
+ images,
642
+ warnings,
643
+ response: {
644
+ timestamp: /* @__PURE__ */ new Date(),
645
+ modelId: this.modelId,
646
+ headers: responseHeaders
647
+ }
648
+ };
649
+ }
650
+ };
651
+ var PROVIDER_ID = "anyrouter";
652
+ function createAnyRouter(options = {}) {
653
+ const baseURL = providerUtils.withoutTrailingSlash(options.baseURL ?? sdk.DEFAULT_BASE_URL) ?? sdk.DEFAULT_BASE_URL;
654
+ function getHeaders() {
655
+ const apiKey = providerUtils.loadApiKey({
656
+ apiKey: options.apiKey,
657
+ environmentVariableName: "ANYROUTER_API_KEY",
658
+ description: "AnyRouter"
659
+ });
660
+ return providerUtils.combineHeaders({ Authorization: `Bearer ${apiKey}` }, options.headers);
661
+ }
662
+ function chatModel(modelId) {
663
+ return new AnyRouterChatLanguageModel(modelId, {
664
+ provider: PROVIDER_ID,
665
+ baseURL,
666
+ headers: getHeaders,
667
+ fetch: options.fetch,
668
+ settings: options
669
+ });
670
+ }
671
+ function embeddingModel(modelId) {
672
+ return new AnyRouterEmbeddingModel(modelId, {
673
+ provider: PROVIDER_ID,
674
+ baseURL,
675
+ headers: getHeaders,
676
+ fetch: options.fetch
677
+ });
678
+ }
679
+ function imageModel(modelId) {
680
+ return new AnyRouterImageModel(modelId, {
681
+ provider: PROVIDER_ID,
682
+ baseURL,
683
+ headers: getHeaders,
684
+ fetch: options.fetch
685
+ });
686
+ }
687
+ const provider$1 = (modelId) => chatModel(modelId);
688
+ const providerObj = Object.assign(provider$1, {
689
+ // ProviderV3 required fields
690
+ specificationVersion: "v3",
691
+ // ProviderV3 required methods
692
+ languageModel(modelId) {
693
+ return chatModel(modelId);
694
+ },
695
+ embeddingModel(modelId) {
696
+ return embeddingModel(modelId);
697
+ },
698
+ imageModel(modelId) {
699
+ return imageModel(modelId);
700
+ },
701
+ // ProviderV3 optional methods (deprecated textEmbeddingModel alias)
702
+ textEmbeddingModel(modelId) {
703
+ return embeddingModel(modelId);
704
+ },
705
+ // AnyRouter convenience alias
706
+ chat(modelId) {
707
+ return chatModel(modelId);
708
+ },
709
+ // Unsupported model types — throw NoSuchModelError per ProviderV3 contract
710
+ transcriptionModel(modelId) {
711
+ throw new provider.NoSuchModelError({ modelId, modelType: "transcriptionModel" });
712
+ },
713
+ speechModel(modelId) {
714
+ throw new provider.NoSuchModelError({ modelId, modelType: "speechModel" });
715
+ }
716
+ });
717
+ Object.defineProperty(providerObj, "client", {
718
+ enumerable: true,
719
+ configurable: true,
720
+ get() {
721
+ return new sdk.AnyRouter({
722
+ apiKey: options.apiKey,
723
+ baseURL: options.baseURL,
724
+ headers: options.headers,
725
+ fetch: options.fetch
726
+ });
727
+ }
728
+ });
729
+ return providerObj;
730
+ }
731
+ var anyrouter = createAnyRouter();
732
+
733
+ exports.AnyRouterChatLanguageModel = AnyRouterChatLanguageModel;
734
+ exports.AnyRouterEmbeddingModel = AnyRouterEmbeddingModel;
735
+ exports.AnyRouterImageModel = AnyRouterImageModel;
736
+ exports.anyrouter = anyrouter;
737
+ exports.createAnyRouter = createAnyRouter;
738
+ //# sourceMappingURL=index.js.map
739
+ //# sourceMappingURL=index.js.map