@openrouter/ai-sdk-provider 0.0.3

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.
@@ -0,0 +1,955 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
+ var __objRest = (source, exclude) => {
24
+ var target = {};
25
+ for (var prop in source)
26
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
27
+ target[prop] = source[prop];
28
+ if (source != null && __getOwnPropSymbols)
29
+ for (var prop of __getOwnPropSymbols(source)) {
30
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
31
+ target[prop] = source[prop];
32
+ }
33
+ return target;
34
+ };
35
+ var __export = (target, all) => {
36
+ for (var name in all)
37
+ __defProp(target, name, { get: all[name], enumerable: true });
38
+ };
39
+ var __copyProps = (to, from, except, desc) => {
40
+ if (from && typeof from === "object" || typeof from === "function") {
41
+ for (let key of __getOwnPropNames(from))
42
+ if (!__hasOwnProp.call(to, key) && key !== except)
43
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
44
+ }
45
+ return to;
46
+ };
47
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
48
+
49
+ // src/internal/index.ts
50
+ var internal_exports = {};
51
+ __export(internal_exports, {
52
+ OpenRouterChatLanguageModel: () => OpenRouterChatLanguageModel,
53
+ OpenRouterCompletionLanguageModel: () => OpenRouterCompletionLanguageModel
54
+ });
55
+ module.exports = __toCommonJS(internal_exports);
56
+
57
+ // src/openrouter-chat-language-model.ts
58
+ var import_provider = require("@ai-sdk/provider");
59
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
60
+ var import_zod2 = require("zod");
61
+
62
+ // src/convert-to-openrouter-chat-messages.ts
63
+ var import_provider_utils = require("@ai-sdk/provider-utils");
64
+ function convertToOpenRouterChatMessages(prompt) {
65
+ var _a;
66
+ const messages = [];
67
+ for (const { role, content } of prompt) {
68
+ switch (role) {
69
+ case "system": {
70
+ messages.push({ role: "system", content });
71
+ break;
72
+ }
73
+ case "user": {
74
+ if (content.length === 1 && ((_a = content[0]) == null ? void 0 : _a.type) === "text") {
75
+ messages.push({ role: "user", content: content[0].text });
76
+ break;
77
+ }
78
+ messages.push({
79
+ role: "user",
80
+ content: content.map((part) => {
81
+ var _a2;
82
+ switch (part.type) {
83
+ case "text": {
84
+ return { type: "text", text: part.text };
85
+ }
86
+ case "image": {
87
+ return {
88
+ type: "image_url",
89
+ image_url: {
90
+ url: part.image instanceof URL ? part.image.toString() : `data:${(_a2 = part.mimeType) != null ? _a2 : "image/jpeg"};base64,${(0, import_provider_utils.convertUint8ArrayToBase64)(part.image)}`
91
+ }
92
+ };
93
+ }
94
+ }
95
+ })
96
+ });
97
+ break;
98
+ }
99
+ case "assistant": {
100
+ let text = "";
101
+ const toolCalls = [];
102
+ for (const part of content) {
103
+ switch (part.type) {
104
+ case "text": {
105
+ text += part.text;
106
+ break;
107
+ }
108
+ case "tool-call": {
109
+ toolCalls.push({
110
+ id: part.toolCallId,
111
+ type: "function",
112
+ function: {
113
+ name: part.toolName,
114
+ arguments: JSON.stringify(part.args)
115
+ }
116
+ });
117
+ break;
118
+ }
119
+ default: {
120
+ const _exhaustiveCheck = part;
121
+ throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
122
+ }
123
+ }
124
+ }
125
+ messages.push({
126
+ role: "assistant",
127
+ content: text,
128
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
129
+ });
130
+ break;
131
+ }
132
+ case "tool": {
133
+ for (const toolResponse of content) {
134
+ messages.push({
135
+ role: "tool",
136
+ tool_call_id: toolResponse.toolCallId,
137
+ content: JSON.stringify(toolResponse.result)
138
+ });
139
+ }
140
+ break;
141
+ }
142
+ default: {
143
+ const _exhaustiveCheck = role;
144
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
145
+ }
146
+ }
147
+ }
148
+ return messages;
149
+ }
150
+
151
+ // src/map-openrouter-chat-logprobs.ts
152
+ function mapOpenRouterChatLogProbsOutput(logprobs) {
153
+ var _a, _b;
154
+ return (_b = (_a = logprobs == null ? void 0 : logprobs.content) == null ? void 0 : _a.map(({ token, logprob, top_logprobs }) => ({
155
+ token,
156
+ logprob,
157
+ topLogprobs: top_logprobs ? top_logprobs.map(({ token: token2, logprob: logprob2 }) => ({
158
+ token: token2,
159
+ logprob: logprob2
160
+ })) : []
161
+ }))) != null ? _b : void 0;
162
+ }
163
+
164
+ // src/map-openrouter-finish-reason.ts
165
+ function mapOpenRouterFinishReason(finishReason) {
166
+ switch (finishReason) {
167
+ case "stop":
168
+ return "stop";
169
+ case "length":
170
+ return "length";
171
+ case "content_filter":
172
+ return "content-filter";
173
+ case "function_call":
174
+ case "tool_calls":
175
+ return "tool-calls";
176
+ default:
177
+ return "unknown";
178
+ }
179
+ }
180
+
181
+ // src/openrouter-error.ts
182
+ var import_zod = require("zod");
183
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
184
+ var openAIErrorDataSchema = import_zod.z.object({
185
+ error: import_zod.z.object({
186
+ message: import_zod.z.string(),
187
+ type: import_zod.z.string(),
188
+ param: import_zod.z.any().nullable(),
189
+ code: import_zod.z.string().nullable()
190
+ })
191
+ });
192
+ var openrouterFailedResponseHandler = (0, import_provider_utils2.createJsonErrorResponseHandler)({
193
+ errorSchema: openAIErrorDataSchema,
194
+ errorToMessage: (data) => data.error.message
195
+ });
196
+
197
+ // src/openrouter-chat-language-model.ts
198
+ var OpenRouterChatLanguageModel = class {
199
+ constructor(modelId, settings, config) {
200
+ this.specificationVersion = "v1";
201
+ this.defaultObjectGenerationMode = "tool";
202
+ this.modelId = modelId;
203
+ this.settings = settings;
204
+ this.config = config;
205
+ }
206
+ get provider() {
207
+ return this.config.provider;
208
+ }
209
+ getArgs({
210
+ mode,
211
+ prompt,
212
+ maxTokens,
213
+ temperature,
214
+ topP,
215
+ frequencyPenalty,
216
+ presencePenalty,
217
+ seed
218
+ }) {
219
+ const type = mode.type;
220
+ const baseArgs = {
221
+ // model id:
222
+ model: this.modelId,
223
+ // model specific settings:
224
+ logit_bias: this.settings.logitBias,
225
+ logprobs: this.settings.logprobs === true || typeof this.settings.logprobs === "number" ? true : void 0,
226
+ top_logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
227
+ user: this.settings.user,
228
+ parallel_tool_calls: this.settings.parallelToolCalls,
229
+ // standardized settings:
230
+ max_tokens: maxTokens,
231
+ temperature,
232
+ top_p: topP,
233
+ frequency_penalty: frequencyPenalty,
234
+ presence_penalty: presencePenalty,
235
+ seed,
236
+ // messages:
237
+ messages: convertToOpenRouterChatMessages(prompt)
238
+ };
239
+ switch (type) {
240
+ case "regular": {
241
+ return __spreadValues(__spreadValues({}, baseArgs), prepareToolsAndToolChoice(mode));
242
+ }
243
+ case "object-json": {
244
+ return __spreadProps(__spreadValues({}, baseArgs), {
245
+ response_format: { type: "json_object" }
246
+ });
247
+ }
248
+ case "object-tool": {
249
+ return __spreadProps(__spreadValues({}, baseArgs), {
250
+ tool_choice: { type: "function", function: { name: mode.tool.name } },
251
+ tools: [
252
+ {
253
+ type: "function",
254
+ function: {
255
+ name: mode.tool.name,
256
+ description: mode.tool.description,
257
+ parameters: mode.tool.parameters
258
+ }
259
+ }
260
+ ]
261
+ });
262
+ }
263
+ case "object-grammar": {
264
+ throw new import_provider.UnsupportedFunctionalityError({
265
+ functionality: "object-grammar mode"
266
+ });
267
+ }
268
+ default: {
269
+ const _exhaustiveCheck = type;
270
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
271
+ }
272
+ }
273
+ }
274
+ async doGenerate(options) {
275
+ var _b, _c;
276
+ const args = this.getArgs(options);
277
+ const { responseHeaders, value: response } = await (0, import_provider_utils3.postJsonToApi)({
278
+ url: this.config.url({
279
+ path: "/chat/completions",
280
+ modelId: this.modelId
281
+ }),
282
+ headers: (0, import_provider_utils3.combineHeaders)(this.config.headers(), options.headers),
283
+ body: args,
284
+ failedResponseHandler: openrouterFailedResponseHandler,
285
+ successfulResponseHandler: (0, import_provider_utils3.createJsonResponseHandler)(
286
+ openAIChatResponseSchema
287
+ ),
288
+ abortSignal: options.abortSignal,
289
+ fetch: this.config.fetch
290
+ });
291
+ const _a = args, { messages: rawPrompt } = _a, rawSettings = __objRest(_a, ["messages"]);
292
+ const choice = response.choices[0];
293
+ if (choice == null) {
294
+ throw new Error("No choice in response");
295
+ }
296
+ return {
297
+ text: (_b = choice.message.content) != null ? _b : void 0,
298
+ toolCalls: (_c = choice.message.tool_calls) == null ? void 0 : _c.map((toolCall) => {
299
+ var _a2;
300
+ return {
301
+ toolCallType: "function",
302
+ toolCallId: (_a2 = toolCall.id) != null ? _a2 : (0, import_provider_utils3.generateId)(),
303
+ toolName: toolCall.function.name,
304
+ args: toolCall.function.arguments
305
+ };
306
+ }),
307
+ finishReason: mapOpenRouterFinishReason(choice.finish_reason),
308
+ usage: {
309
+ promptTokens: response.usage.prompt_tokens,
310
+ completionTokens: response.usage.completion_tokens
311
+ },
312
+ rawCall: { rawPrompt, rawSettings },
313
+ rawResponse: { headers: responseHeaders },
314
+ warnings: [],
315
+ logprobs: mapOpenRouterChatLogProbsOutput(choice.logprobs)
316
+ };
317
+ }
318
+ async doStream(options) {
319
+ const args = this.getArgs(options);
320
+ const { responseHeaders, value: response } = await (0, import_provider_utils3.postJsonToApi)({
321
+ url: this.config.url({
322
+ path: "/chat/completions",
323
+ modelId: this.modelId
324
+ }),
325
+ headers: (0, import_provider_utils3.combineHeaders)(this.config.headers(), options.headers),
326
+ body: __spreadProps(__spreadValues({}, args), {
327
+ stream: true,
328
+ // only include stream_options when in strict compatibility mode:
329
+ stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
330
+ }),
331
+ failedResponseHandler: openrouterFailedResponseHandler,
332
+ successfulResponseHandler: (0, import_provider_utils3.createEventSourceResponseHandler)(
333
+ openrouterChatChunkSchema
334
+ ),
335
+ abortSignal: options.abortSignal,
336
+ fetch: this.config.fetch
337
+ });
338
+ const _a = args, { messages: rawPrompt } = _a, rawSettings = __objRest(_a, ["messages"]);
339
+ const toolCalls = [];
340
+ let finishReason = "other";
341
+ let usage = {
342
+ promptTokens: Number.NaN,
343
+ completionTokens: Number.NaN
344
+ };
345
+ let logprobs;
346
+ return {
347
+ stream: response.pipeThrough(
348
+ new TransformStream({
349
+ transform(chunk, controller) {
350
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
351
+ if (!chunk.success) {
352
+ finishReason = "error";
353
+ controller.enqueue({ type: "error", error: chunk.error });
354
+ return;
355
+ }
356
+ const value = chunk.value;
357
+ if ("error" in value) {
358
+ finishReason = "error";
359
+ controller.enqueue({ type: "error", error: value.error });
360
+ return;
361
+ }
362
+ if (value.usage != null) {
363
+ usage = {
364
+ promptTokens: value.usage.prompt_tokens,
365
+ completionTokens: value.usage.completion_tokens
366
+ };
367
+ }
368
+ const choice = value.choices[0];
369
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
370
+ finishReason = mapOpenRouterFinishReason(choice.finish_reason);
371
+ }
372
+ if ((choice == null ? void 0 : choice.delta) == null) {
373
+ return;
374
+ }
375
+ const delta = choice.delta;
376
+ if (delta.content != null) {
377
+ controller.enqueue({
378
+ type: "text-delta",
379
+ textDelta: delta.content
380
+ });
381
+ }
382
+ const mappedLogprobs = mapOpenRouterChatLogProbsOutput(
383
+ choice == null ? void 0 : choice.logprobs
384
+ );
385
+ if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
386
+ if (logprobs === void 0) logprobs = [];
387
+ logprobs.push(...mappedLogprobs);
388
+ }
389
+ if (delta.tool_calls != null) {
390
+ for (const toolCallDelta of delta.tool_calls) {
391
+ const index = toolCallDelta.index;
392
+ if (toolCalls[index] == null) {
393
+ if (toolCallDelta.type !== "function") {
394
+ throw new import_provider.InvalidResponseDataError({
395
+ data: toolCallDelta,
396
+ message: `Expected 'function' type.`
397
+ });
398
+ }
399
+ if (toolCallDelta.id == null) {
400
+ throw new import_provider.InvalidResponseDataError({
401
+ data: toolCallDelta,
402
+ message: `Expected 'id' to be a string.`
403
+ });
404
+ }
405
+ if (((_a2 = toolCallDelta.function) == null ? void 0 : _a2.name) == null) {
406
+ throw new import_provider.InvalidResponseDataError({
407
+ data: toolCallDelta,
408
+ message: `Expected 'function.name' to be a string.`
409
+ });
410
+ }
411
+ toolCalls[index] = {
412
+ id: toolCallDelta.id,
413
+ type: "function",
414
+ function: {
415
+ name: toolCallDelta.function.name,
416
+ arguments: (_b = toolCallDelta.function.arguments) != null ? _b : ""
417
+ }
418
+ };
419
+ const toolCall2 = toolCalls[index];
420
+ if (toolCall2 == null) {
421
+ throw new Error("Tool call is missing");
422
+ }
423
+ if (((_c = toolCall2.function) == null ? void 0 : _c.name) != null && ((_d = toolCall2.function) == null ? void 0 : _d.arguments) != null && (0, import_provider_utils3.isParsableJson)(toolCall2.function.arguments)) {
424
+ controller.enqueue({
425
+ type: "tool-call-delta",
426
+ toolCallType: "function",
427
+ toolCallId: toolCall2.id,
428
+ toolName: toolCall2.function.name,
429
+ argsTextDelta: toolCall2.function.arguments
430
+ });
431
+ controller.enqueue({
432
+ type: "tool-call",
433
+ toolCallType: "function",
434
+ toolCallId: (_e = toolCall2.id) != null ? _e : (0, import_provider_utils3.generateId)(),
435
+ toolName: toolCall2.function.name,
436
+ args: toolCall2.function.arguments
437
+ });
438
+ }
439
+ continue;
440
+ }
441
+ const toolCall = toolCalls[index];
442
+ if (toolCall == null) {
443
+ throw new Error("Tool call is missing");
444
+ }
445
+ if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) {
446
+ toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null ? _h : "";
447
+ }
448
+ controller.enqueue({
449
+ type: "tool-call-delta",
450
+ toolCallType: "function",
451
+ toolCallId: toolCall.id,
452
+ toolName: toolCall.function.name,
453
+ argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
454
+ });
455
+ if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && (0, import_provider_utils3.isParsableJson)(toolCall.function.arguments)) {
456
+ controller.enqueue({
457
+ type: "tool-call",
458
+ toolCallType: "function",
459
+ toolCallId: (_l = toolCall.id) != null ? _l : (0, import_provider_utils3.generateId)(),
460
+ toolName: toolCall.function.name,
461
+ args: toolCall.function.arguments
462
+ });
463
+ }
464
+ }
465
+ }
466
+ },
467
+ flush(controller) {
468
+ controller.enqueue({
469
+ type: "finish",
470
+ finishReason,
471
+ logprobs,
472
+ usage
473
+ });
474
+ }
475
+ })
476
+ ),
477
+ rawCall: { rawPrompt, rawSettings },
478
+ rawResponse: { headers: responseHeaders },
479
+ warnings: []
480
+ };
481
+ }
482
+ };
483
+ var openAIChatResponseSchema = import_zod2.z.object({
484
+ choices: import_zod2.z.array(
485
+ import_zod2.z.object({
486
+ message: import_zod2.z.object({
487
+ role: import_zod2.z.literal("assistant"),
488
+ content: import_zod2.z.string().nullable().optional(),
489
+ tool_calls: import_zod2.z.array(
490
+ import_zod2.z.object({
491
+ id: import_zod2.z.string().optional().nullable(),
492
+ type: import_zod2.z.literal("function"),
493
+ function: import_zod2.z.object({
494
+ name: import_zod2.z.string(),
495
+ arguments: import_zod2.z.string()
496
+ })
497
+ })
498
+ ).optional()
499
+ }),
500
+ index: import_zod2.z.number(),
501
+ logprobs: import_zod2.z.object({
502
+ content: import_zod2.z.array(
503
+ import_zod2.z.object({
504
+ token: import_zod2.z.string(),
505
+ logprob: import_zod2.z.number(),
506
+ top_logprobs: import_zod2.z.array(
507
+ import_zod2.z.object({
508
+ token: import_zod2.z.string(),
509
+ logprob: import_zod2.z.number()
510
+ })
511
+ )
512
+ })
513
+ ).nullable()
514
+ }).nullable().optional(),
515
+ finish_reason: import_zod2.z.string().optional().nullable()
516
+ })
517
+ ),
518
+ usage: import_zod2.z.object({
519
+ prompt_tokens: import_zod2.z.number(),
520
+ completion_tokens: import_zod2.z.number()
521
+ })
522
+ });
523
+ var openrouterChatChunkSchema = import_zod2.z.union([
524
+ import_zod2.z.object({
525
+ choices: import_zod2.z.array(
526
+ import_zod2.z.object({
527
+ delta: import_zod2.z.object({
528
+ role: import_zod2.z.enum(["assistant"]).optional(),
529
+ content: import_zod2.z.string().nullish(),
530
+ tool_calls: import_zod2.z.array(
531
+ import_zod2.z.object({
532
+ index: import_zod2.z.number(),
533
+ id: import_zod2.z.string().nullish(),
534
+ type: import_zod2.z.literal("function").optional(),
535
+ function: import_zod2.z.object({
536
+ name: import_zod2.z.string().nullish(),
537
+ arguments: import_zod2.z.string().nullish()
538
+ })
539
+ })
540
+ ).nullish()
541
+ }).nullish(),
542
+ logprobs: import_zod2.z.object({
543
+ content: import_zod2.z.array(
544
+ import_zod2.z.object({
545
+ token: import_zod2.z.string(),
546
+ logprob: import_zod2.z.number(),
547
+ top_logprobs: import_zod2.z.array(
548
+ import_zod2.z.object({
549
+ token: import_zod2.z.string(),
550
+ logprob: import_zod2.z.number()
551
+ })
552
+ )
553
+ })
554
+ ).nullable()
555
+ }).nullish(),
556
+ finish_reason: import_zod2.z.string().nullable().optional(),
557
+ index: import_zod2.z.number()
558
+ })
559
+ ),
560
+ usage: import_zod2.z.object({
561
+ prompt_tokens: import_zod2.z.number(),
562
+ completion_tokens: import_zod2.z.number()
563
+ }).nullish()
564
+ }),
565
+ openAIErrorDataSchema
566
+ ]);
567
+ function prepareToolsAndToolChoice(mode) {
568
+ var _a;
569
+ const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
570
+ if (tools == null) {
571
+ return { tools: void 0, tool_choice: void 0 };
572
+ }
573
+ const mappedTools = tools.map((tool) => ({
574
+ type: "function",
575
+ function: {
576
+ name: tool.name,
577
+ description: tool.description,
578
+ parameters: tool.parameters
579
+ }
580
+ }));
581
+ const toolChoice = mode.toolChoice;
582
+ if (toolChoice == null) {
583
+ return { tools: mappedTools, tool_choice: void 0 };
584
+ }
585
+ const type = toolChoice.type;
586
+ switch (type) {
587
+ case "auto":
588
+ case "none":
589
+ case "required":
590
+ return { tools: mappedTools, tool_choice: type };
591
+ case "tool":
592
+ return {
593
+ tools: mappedTools,
594
+ tool_choice: {
595
+ type: "function",
596
+ function: {
597
+ name: toolChoice.toolName
598
+ }
599
+ }
600
+ };
601
+ default: {
602
+ const _exhaustiveCheck = type;
603
+ throw new Error(`Unsupported tool choice type: ${_exhaustiveCheck}`);
604
+ }
605
+ }
606
+ }
607
+
608
+ // src/openrouter-completion-language-model.ts
609
+ var import_provider3 = require("@ai-sdk/provider");
610
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
611
+ var import_zod3 = require("zod");
612
+
613
+ // src/convert-to-openrouter-completion-prompt.ts
614
+ var import_provider2 = require("@ai-sdk/provider");
615
+ function convertToOpenRouterCompletionPrompt({
616
+ prompt,
617
+ inputFormat,
618
+ user = "user",
619
+ assistant = "assistant"
620
+ }) {
621
+ if (inputFormat === "prompt" && prompt.length === 1 && prompt[0] && prompt[0].role === "user" && prompt[0].content.length === 1 && prompt[0].content[0] && prompt[0].content[0].type === "text") {
622
+ return { prompt: prompt[0].content[0].text };
623
+ }
624
+ let text = "";
625
+ if (prompt[0] && prompt[0].role === "system") {
626
+ text += `${prompt[0].content}
627
+
628
+ `;
629
+ prompt = prompt.slice(1);
630
+ }
631
+ for (const { role, content } of prompt) {
632
+ switch (role) {
633
+ case "system": {
634
+ throw new import_provider2.InvalidPromptError({
635
+ message: "Unexpected system message in prompt: ${content}",
636
+ prompt
637
+ });
638
+ }
639
+ case "user": {
640
+ const userMessage = content.map((part) => {
641
+ switch (part.type) {
642
+ case "text": {
643
+ return part.text;
644
+ }
645
+ case "image": {
646
+ throw new import_provider2.UnsupportedFunctionalityError({
647
+ functionality: "images"
648
+ });
649
+ }
650
+ }
651
+ }).join("");
652
+ text += `${user}:
653
+ ${userMessage}
654
+
655
+ `;
656
+ break;
657
+ }
658
+ case "assistant": {
659
+ const assistantMessage = content.map((part) => {
660
+ switch (part.type) {
661
+ case "text": {
662
+ return part.text;
663
+ }
664
+ case "tool-call": {
665
+ throw new import_provider2.UnsupportedFunctionalityError({
666
+ functionality: "tool-call messages"
667
+ });
668
+ }
669
+ }
670
+ }).join("");
671
+ text += `${assistant}:
672
+ ${assistantMessage}
673
+
674
+ `;
675
+ break;
676
+ }
677
+ case "tool": {
678
+ throw new import_provider2.UnsupportedFunctionalityError({
679
+ functionality: "tool messages"
680
+ });
681
+ }
682
+ default: {
683
+ const _exhaustiveCheck = role;
684
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
685
+ }
686
+ }
687
+ }
688
+ text += `${assistant}:
689
+ `;
690
+ return {
691
+ prompt: text,
692
+ stopSequences: [`
693
+ ${user}:`]
694
+ };
695
+ }
696
+
697
+ // src/map-openrouter-completion-logprobs.ts
698
+ function mapOpenRouterCompletionLogProbs(logprobs) {
699
+ return logprobs == null ? void 0 : logprobs.tokens.map((token, index) => {
700
+ var _a, _b;
701
+ return {
702
+ token,
703
+ logprob: (_a = logprobs.token_logprobs[index]) != null ? _a : 0,
704
+ topLogprobs: logprobs.top_logprobs ? Object.entries((_b = logprobs.top_logprobs[index]) != null ? _b : {}).map(
705
+ ([token2, logprob]) => ({
706
+ token: token2,
707
+ logprob
708
+ })
709
+ ) : []
710
+ };
711
+ });
712
+ }
713
+
714
+ // src/openrouter-completion-language-model.ts
715
+ var OpenRouterCompletionLanguageModel = class {
716
+ constructor(modelId, settings, config) {
717
+ this.specificationVersion = "v1";
718
+ this.defaultObjectGenerationMode = void 0;
719
+ this.modelId = modelId;
720
+ this.settings = settings;
721
+ this.config = config;
722
+ }
723
+ get provider() {
724
+ return this.config.provider;
725
+ }
726
+ getArgs({
727
+ mode,
728
+ inputFormat,
729
+ prompt,
730
+ maxTokens,
731
+ temperature,
732
+ topP,
733
+ frequencyPenalty,
734
+ presencePenalty,
735
+ seed
736
+ }) {
737
+ var _a;
738
+ const type = mode.type;
739
+ const { prompt: completionPrompt, stopSequences } = convertToOpenRouterCompletionPrompt({ prompt, inputFormat });
740
+ const baseArgs = {
741
+ // model id:
742
+ model: this.modelId,
743
+ // model specific settings:
744
+ echo: this.settings.echo,
745
+ logit_bias: this.settings.logitBias,
746
+ logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0,
747
+ suffix: this.settings.suffix,
748
+ user: this.settings.user,
749
+ // standardized settings:
750
+ max_tokens: maxTokens,
751
+ temperature,
752
+ top_p: topP,
753
+ frequency_penalty: frequencyPenalty,
754
+ presence_penalty: presencePenalty,
755
+ seed,
756
+ // prompt:
757
+ prompt: completionPrompt,
758
+ // stop sequences:
759
+ stop: stopSequences
760
+ };
761
+ switch (type) {
762
+ case "regular": {
763
+ if ((_a = mode.tools) == null ? void 0 : _a.length) {
764
+ throw new import_provider3.UnsupportedFunctionalityError({
765
+ functionality: "tools"
766
+ });
767
+ }
768
+ if (mode.toolChoice) {
769
+ throw new import_provider3.UnsupportedFunctionalityError({
770
+ functionality: "toolChoice"
771
+ });
772
+ }
773
+ return baseArgs;
774
+ }
775
+ case "object-json": {
776
+ throw new import_provider3.UnsupportedFunctionalityError({
777
+ functionality: "object-json mode"
778
+ });
779
+ }
780
+ case "object-tool": {
781
+ throw new import_provider3.UnsupportedFunctionalityError({
782
+ functionality: "object-tool mode"
783
+ });
784
+ }
785
+ case "object-grammar": {
786
+ throw new import_provider3.UnsupportedFunctionalityError({
787
+ functionality: "object-grammar mode"
788
+ });
789
+ }
790
+ default: {
791
+ const _exhaustiveCheck = type;
792
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
793
+ }
794
+ }
795
+ }
796
+ async doGenerate(options) {
797
+ const args = this.getArgs(options);
798
+ const { responseHeaders, value: response } = await (0, import_provider_utils4.postJsonToApi)({
799
+ url: this.config.url({
800
+ path: "/completions",
801
+ modelId: this.modelId
802
+ }),
803
+ headers: (0, import_provider_utils4.combineHeaders)(this.config.headers(), options.headers),
804
+ body: args,
805
+ failedResponseHandler: openrouterFailedResponseHandler,
806
+ successfulResponseHandler: (0, import_provider_utils4.createJsonResponseHandler)(
807
+ openAICompletionResponseSchema
808
+ ),
809
+ abortSignal: options.abortSignal,
810
+ fetch: this.config.fetch
811
+ });
812
+ const _a = args, { prompt: rawPrompt } = _a, rawSettings = __objRest(_a, ["prompt"]);
813
+ const choice = response.choices[0];
814
+ if (!choice) {
815
+ throw new Error("No choice in OpenRouter completion response");
816
+ }
817
+ return {
818
+ text: choice.text,
819
+ usage: {
820
+ promptTokens: response.usage.prompt_tokens,
821
+ completionTokens: response.usage.completion_tokens
822
+ },
823
+ finishReason: mapOpenRouterFinishReason(choice.finish_reason),
824
+ logprobs: mapOpenRouterCompletionLogProbs(choice.logprobs),
825
+ rawCall: { rawPrompt, rawSettings },
826
+ rawResponse: { headers: responseHeaders },
827
+ warnings: []
828
+ };
829
+ }
830
+ async doStream(options) {
831
+ const args = this.getArgs(options);
832
+ const { responseHeaders, value: response } = await (0, import_provider_utils4.postJsonToApi)({
833
+ url: this.config.url({
834
+ path: "/completions",
835
+ modelId: this.modelId
836
+ }),
837
+ headers: (0, import_provider_utils4.combineHeaders)(this.config.headers(), options.headers),
838
+ body: __spreadProps(__spreadValues({}, this.getArgs(options)), {
839
+ stream: true,
840
+ // only include stream_options when in strict compatibility mode:
841
+ stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0
842
+ }),
843
+ failedResponseHandler: openrouterFailedResponseHandler,
844
+ successfulResponseHandler: (0, import_provider_utils4.createEventSourceResponseHandler)(
845
+ openrouterCompletionChunkSchema
846
+ ),
847
+ abortSignal: options.abortSignal,
848
+ fetch: this.config.fetch
849
+ });
850
+ const _a = args, { prompt: rawPrompt } = _a, rawSettings = __objRest(_a, ["prompt"]);
851
+ let finishReason = "other";
852
+ let usage = {
853
+ promptTokens: Number.NaN,
854
+ completionTokens: Number.NaN
855
+ };
856
+ let logprobs;
857
+ return {
858
+ stream: response.pipeThrough(
859
+ new TransformStream({
860
+ transform(chunk, controller) {
861
+ if (!chunk.success) {
862
+ finishReason = "error";
863
+ controller.enqueue({ type: "error", error: chunk.error });
864
+ return;
865
+ }
866
+ const value = chunk.value;
867
+ if ("error" in value) {
868
+ finishReason = "error";
869
+ controller.enqueue({ type: "error", error: value.error });
870
+ return;
871
+ }
872
+ if (value.usage != null) {
873
+ usage = {
874
+ promptTokens: value.usage.prompt_tokens,
875
+ completionTokens: value.usage.completion_tokens
876
+ };
877
+ }
878
+ const choice = value.choices[0];
879
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
880
+ finishReason = mapOpenRouterFinishReason(choice.finish_reason);
881
+ }
882
+ if ((choice == null ? void 0 : choice.text) != null) {
883
+ controller.enqueue({
884
+ type: "text-delta",
885
+ textDelta: choice.text
886
+ });
887
+ }
888
+ const mappedLogprobs = mapOpenRouterCompletionLogProbs(
889
+ choice == null ? void 0 : choice.logprobs
890
+ );
891
+ if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) {
892
+ if (logprobs === void 0) logprobs = [];
893
+ logprobs.push(...mappedLogprobs);
894
+ }
895
+ },
896
+ flush(controller) {
897
+ controller.enqueue({
898
+ type: "finish",
899
+ finishReason,
900
+ logprobs,
901
+ usage
902
+ });
903
+ }
904
+ })
905
+ ),
906
+ rawCall: { rawPrompt, rawSettings },
907
+ rawResponse: { headers: responseHeaders },
908
+ warnings: []
909
+ };
910
+ }
911
+ };
912
+ var openAICompletionResponseSchema = import_zod3.z.object({
913
+ choices: import_zod3.z.array(
914
+ import_zod3.z.object({
915
+ text: import_zod3.z.string(),
916
+ finish_reason: import_zod3.z.string(),
917
+ logprobs: import_zod3.z.object({
918
+ tokens: import_zod3.z.array(import_zod3.z.string()),
919
+ token_logprobs: import_zod3.z.array(import_zod3.z.number()),
920
+ top_logprobs: import_zod3.z.array(import_zod3.z.record(import_zod3.z.string(), import_zod3.z.number())).nullable()
921
+ }).nullable().optional()
922
+ })
923
+ ),
924
+ usage: import_zod3.z.object({
925
+ prompt_tokens: import_zod3.z.number(),
926
+ completion_tokens: import_zod3.z.number()
927
+ })
928
+ });
929
+ var openrouterCompletionChunkSchema = import_zod3.z.union([
930
+ import_zod3.z.object({
931
+ choices: import_zod3.z.array(
932
+ import_zod3.z.object({
933
+ text: import_zod3.z.string(),
934
+ finish_reason: import_zod3.z.string().nullish(),
935
+ index: import_zod3.z.number(),
936
+ logprobs: import_zod3.z.object({
937
+ tokens: import_zod3.z.array(import_zod3.z.string()),
938
+ token_logprobs: import_zod3.z.array(import_zod3.z.number()),
939
+ top_logprobs: import_zod3.z.array(import_zod3.z.record(import_zod3.z.string(), import_zod3.z.number())).nullable()
940
+ }).nullable().optional()
941
+ })
942
+ ),
943
+ usage: import_zod3.z.object({
944
+ prompt_tokens: import_zod3.z.number(),
945
+ completion_tokens: import_zod3.z.number()
946
+ }).optional().nullable()
947
+ }),
948
+ openAIErrorDataSchema
949
+ ]);
950
+ // Annotate the CommonJS export names for ESM import in node:
951
+ 0 && (module.exports = {
952
+ OpenRouterChatLanguageModel,
953
+ OpenRouterCompletionLanguageModel
954
+ });
955
+ //# sourceMappingURL=index.js.map