@ai-sdk/cohere 4.0.0-beta.2 → 4.0.0-beta.21

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.mjs DELETED
@@ -1,1067 +0,0 @@
1
- // src/cohere-provider.ts
2
- import {
3
- NoSuchModelError
4
- } from "@ai-sdk/provider";
5
- import {
6
- generateId,
7
- loadApiKey,
8
- withoutTrailingSlash,
9
- withUserAgentSuffix
10
- } from "@ai-sdk/provider-utils";
11
-
12
- // src/cohere-chat-language-model.ts
13
- import {
14
- combineHeaders,
15
- createEventSourceResponseHandler,
16
- createJsonResponseHandler,
17
- parseProviderOptions,
18
- postJsonToApi
19
- } from "@ai-sdk/provider-utils";
20
- import { z as z3 } from "zod/v4";
21
-
22
- // src/cohere-chat-options.ts
23
- import { z } from "zod/v4";
24
- var cohereLanguageModelOptions = z.object({
25
- /**
26
- * Configuration for reasoning features (optional)
27
- *
28
- * Can be set to an object with the two properties `type` and `tokenBudget`. `type` can be set to `'enabled'` or `'disabled'` (defaults to `'enabled'`).
29
- * `tokenBudget` is the maximum number of tokens the model can use for thinking, which must be set to a positive integer. The model will stop thinking if it reaches the thinking token budget and will proceed with the response
30
- *
31
- * @see https://docs.cohere.com/reference/chat#request.body.thinking
32
- */
33
- thinking: z.object({
34
- type: z.enum(["enabled", "disabled"]).optional(),
35
- tokenBudget: z.number().optional()
36
- }).optional()
37
- });
38
-
39
- // src/cohere-error.ts
40
- import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
41
- import { z as z2 } from "zod/v4";
42
- var cohereErrorDataSchema = z2.object({
43
- message: z2.string()
44
- });
45
- var cohereFailedResponseHandler = createJsonErrorResponseHandler({
46
- errorSchema: cohereErrorDataSchema,
47
- errorToMessage: (data) => data.message
48
- });
49
-
50
- // src/cohere-prepare-tools.ts
51
- import {
52
- UnsupportedFunctionalityError
53
- } from "@ai-sdk/provider";
54
- function prepareTools({
55
- tools,
56
- toolChoice
57
- }) {
58
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
59
- const toolWarnings = [];
60
- if (tools == null) {
61
- return { tools: void 0, toolChoice: void 0, toolWarnings };
62
- }
63
- const cohereTools = [];
64
- for (const tool of tools) {
65
- if (tool.type === "provider") {
66
- toolWarnings.push({
67
- type: "unsupported",
68
- feature: `provider-defined tool ${tool.id}`
69
- });
70
- } else {
71
- cohereTools.push({
72
- type: "function",
73
- function: {
74
- name: tool.name,
75
- description: tool.description,
76
- parameters: tool.inputSchema
77
- }
78
- });
79
- }
80
- }
81
- if (toolChoice == null) {
82
- return { tools: cohereTools, toolChoice: void 0, toolWarnings };
83
- }
84
- const type = toolChoice.type;
85
- switch (type) {
86
- case "auto":
87
- return { tools: cohereTools, toolChoice: void 0, toolWarnings };
88
- case "none":
89
- return { tools: cohereTools, toolChoice: "NONE", toolWarnings };
90
- case "required":
91
- return { tools: cohereTools, toolChoice: "REQUIRED", toolWarnings };
92
- case "tool":
93
- return {
94
- tools: cohereTools.filter(
95
- (tool) => tool.function.name === toolChoice.toolName
96
- ),
97
- toolChoice: "REQUIRED",
98
- toolWarnings
99
- };
100
- default: {
101
- const _exhaustiveCheck = type;
102
- throw new UnsupportedFunctionalityError({
103
- functionality: `tool choice type: ${_exhaustiveCheck}`
104
- });
105
- }
106
- }
107
- }
108
-
109
- // src/convert-cohere-usage.ts
110
- function convertCohereUsage(tokens) {
111
- if (tokens == null) {
112
- return {
113
- inputTokens: {
114
- total: void 0,
115
- noCache: void 0,
116
- cacheRead: void 0,
117
- cacheWrite: void 0
118
- },
119
- outputTokens: {
120
- total: void 0,
121
- text: void 0,
122
- reasoning: void 0
123
- },
124
- raw: void 0
125
- };
126
- }
127
- const inputTokens = tokens.input_tokens;
128
- const outputTokens = tokens.output_tokens;
129
- return {
130
- inputTokens: {
131
- total: inputTokens,
132
- noCache: inputTokens,
133
- cacheRead: void 0,
134
- cacheWrite: void 0
135
- },
136
- outputTokens: {
137
- total: outputTokens,
138
- text: outputTokens,
139
- reasoning: void 0
140
- },
141
- raw: tokens
142
- };
143
- }
144
-
145
- // src/convert-to-cohere-chat-prompt.ts
146
- import {
147
- UnsupportedFunctionalityError as UnsupportedFunctionalityError2
148
- } from "@ai-sdk/provider";
149
- function convertToCohereChatPrompt(prompt) {
150
- const messages = [];
151
- const documents = [];
152
- const warnings = [];
153
- for (const { role, content } of prompt) {
154
- switch (role) {
155
- case "system": {
156
- messages.push({ role: "system", content });
157
- break;
158
- }
159
- case "user": {
160
- messages.push({
161
- role: "user",
162
- content: content.map((part) => {
163
- var _a;
164
- switch (part.type) {
165
- case "text": {
166
- return part.text;
167
- }
168
- case "file": {
169
- let textContent;
170
- if (typeof part.data === "string") {
171
- textContent = part.data;
172
- } else if (part.data instanceof Uint8Array) {
173
- if (!(((_a = part.mediaType) == null ? void 0 : _a.startsWith("text/")) || part.mediaType === "application/json")) {
174
- throw new UnsupportedFunctionalityError2({
175
- functionality: `document media type: ${part.mediaType}`,
176
- message: `Media type '${part.mediaType}' is not supported. Supported media types are: text/* and application/json.`
177
- });
178
- }
179
- textContent = new TextDecoder().decode(part.data);
180
- } else {
181
- throw new UnsupportedFunctionalityError2({
182
- functionality: "File URL data",
183
- message: "URLs should be downloaded by the AI SDK and not reach this point. This indicates a configuration issue."
184
- });
185
- }
186
- documents.push({
187
- data: {
188
- text: textContent,
189
- title: part.filename
190
- }
191
- });
192
- return "";
193
- }
194
- }
195
- }).join("")
196
- });
197
- break;
198
- }
199
- case "assistant": {
200
- let text = "";
201
- const toolCalls = [];
202
- for (const part of content) {
203
- switch (part.type) {
204
- case "text": {
205
- text += part.text;
206
- break;
207
- }
208
- case "tool-call": {
209
- toolCalls.push({
210
- id: part.toolCallId,
211
- type: "function",
212
- function: {
213
- name: part.toolName,
214
- arguments: JSON.stringify(part.input)
215
- }
216
- });
217
- break;
218
- }
219
- }
220
- }
221
- messages.push({
222
- role: "assistant",
223
- content: toolCalls.length > 0 ? void 0 : text,
224
- tool_calls: toolCalls.length > 0 ? toolCalls : void 0,
225
- tool_plan: void 0
226
- });
227
- break;
228
- }
229
- case "tool": {
230
- messages.push(
231
- ...content.filter((toolResult) => toolResult.type !== "tool-approval-response").map((toolResult) => {
232
- var _a;
233
- const output = toolResult.output;
234
- let contentValue;
235
- switch (output.type) {
236
- case "text":
237
- case "error-text":
238
- contentValue = output.value;
239
- break;
240
- case "execution-denied":
241
- contentValue = (_a = output.reason) != null ? _a : "Tool execution denied.";
242
- break;
243
- case "content":
244
- case "json":
245
- case "error-json":
246
- contentValue = JSON.stringify(output.value);
247
- break;
248
- }
249
- return {
250
- role: "tool",
251
- content: contentValue,
252
- tool_call_id: toolResult.toolCallId
253
- };
254
- })
255
- );
256
- break;
257
- }
258
- default: {
259
- const _exhaustiveCheck = role;
260
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
261
- }
262
- }
263
- }
264
- return { messages, documents, warnings };
265
- }
266
-
267
- // src/map-cohere-finish-reason.ts
268
- function mapCohereFinishReason(finishReason) {
269
- switch (finishReason) {
270
- case "COMPLETE":
271
- case "STOP_SEQUENCE":
272
- return "stop";
273
- case "MAX_TOKENS":
274
- return "length";
275
- case "ERROR":
276
- return "error";
277
- case "TOOL_CALL":
278
- return "tool-calls";
279
- default:
280
- return "other";
281
- }
282
- }
283
-
284
- // src/cohere-chat-language-model.ts
285
- var CohereChatLanguageModel = class {
286
- constructor(modelId, config) {
287
- this.specificationVersion = "v3";
288
- this.supportedUrls = {
289
- // No URLs are supported.
290
- };
291
- this.modelId = modelId;
292
- this.config = config;
293
- }
294
- get provider() {
295
- return this.config.provider;
296
- }
297
- async getArgs({
298
- prompt,
299
- maxOutputTokens,
300
- temperature,
301
- topP,
302
- topK,
303
- frequencyPenalty,
304
- presencePenalty,
305
- stopSequences,
306
- responseFormat,
307
- seed,
308
- tools,
309
- toolChoice,
310
- providerOptions
311
- }) {
312
- var _a, _b;
313
- const cohereOptions = (_a = await parseProviderOptions({
314
- provider: "cohere",
315
- providerOptions,
316
- schema: cohereLanguageModelOptions
317
- })) != null ? _a : {};
318
- const {
319
- messages: chatPrompt,
320
- documents: cohereDocuments,
321
- warnings: promptWarnings
322
- } = convertToCohereChatPrompt(prompt);
323
- const {
324
- tools: cohereTools,
325
- toolChoice: cohereToolChoice,
326
- toolWarnings
327
- } = prepareTools({ tools, toolChoice });
328
- return {
329
- args: {
330
- // model id:
331
- model: this.modelId,
332
- // standardized settings:
333
- frequency_penalty: frequencyPenalty,
334
- presence_penalty: presencePenalty,
335
- max_tokens: maxOutputTokens,
336
- temperature,
337
- p: topP,
338
- k: topK,
339
- seed,
340
- stop_sequences: stopSequences,
341
- // response format:
342
- response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? { type: "json_object", json_schema: responseFormat.schema } : void 0,
343
- // messages:
344
- messages: chatPrompt,
345
- // tools:
346
- tools: cohereTools,
347
- tool_choice: cohereToolChoice,
348
- // documents for RAG:
349
- ...cohereDocuments.length > 0 && { documents: cohereDocuments },
350
- // reasoning
351
- ...cohereOptions.thinking && {
352
- thinking: {
353
- type: (_b = cohereOptions.thinking.type) != null ? _b : "enabled",
354
- token_budget: cohereOptions.thinking.tokenBudget
355
- }
356
- }
357
- },
358
- warnings: [...toolWarnings, ...promptWarnings]
359
- };
360
- }
361
- async doGenerate(options) {
362
- var _a, _b, _c, _d, _e, _f, _g;
363
- const { args, warnings } = await this.getArgs(options);
364
- const {
365
- responseHeaders,
366
- value: response,
367
- rawValue: rawResponse
368
- } = await postJsonToApi({
369
- url: `${this.config.baseURL}/chat`,
370
- headers: combineHeaders(this.config.headers(), options.headers),
371
- body: args,
372
- failedResponseHandler: cohereFailedResponseHandler,
373
- successfulResponseHandler: createJsonResponseHandler(
374
- cohereChatResponseSchema
375
- ),
376
- abortSignal: options.abortSignal,
377
- fetch: this.config.fetch
378
- });
379
- const content = [];
380
- for (const item of (_a = response.message.content) != null ? _a : []) {
381
- if (item.type === "text" && item.text.length > 0) {
382
- content.push({ type: "text", text: item.text });
383
- continue;
384
- }
385
- if (item.type === "thinking" && item.thinking.length > 0) {
386
- content.push({ type: "reasoning", text: item.thinking });
387
- continue;
388
- }
389
- }
390
- for (const citation of (_b = response.message.citations) != null ? _b : []) {
391
- content.push({
392
- type: "source",
393
- sourceType: "document",
394
- id: this.config.generateId(),
395
- mediaType: "text/plain",
396
- title: ((_d = (_c = citation.sources[0]) == null ? void 0 : _c.document) == null ? void 0 : _d.title) || "Document",
397
- providerMetadata: {
398
- cohere: {
399
- start: citation.start,
400
- end: citation.end,
401
- text: citation.text,
402
- sources: citation.sources,
403
- ...citation.type && { citationType: citation.type }
404
- }
405
- }
406
- });
407
- }
408
- for (const toolCall of (_e = response.message.tool_calls) != null ? _e : []) {
409
- content.push({
410
- type: "tool-call",
411
- toolCallId: toolCall.id,
412
- toolName: toolCall.function.name,
413
- // Cohere sometimes returns `null` for tool call arguments for tools
414
- // defined as having no arguments.
415
- input: toolCall.function.arguments.replace(/^null$/, "{}")
416
- });
417
- }
418
- return {
419
- content,
420
- finishReason: {
421
- unified: mapCohereFinishReason(response.finish_reason),
422
- raw: (_f = response.finish_reason) != null ? _f : void 0
423
- },
424
- usage: convertCohereUsage(response.usage.tokens),
425
- request: { body: args },
426
- response: {
427
- // TODO timestamp, model id
428
- id: (_g = response.generation_id) != null ? _g : void 0,
429
- headers: responseHeaders,
430
- body: rawResponse
431
- },
432
- warnings
433
- };
434
- }
435
- async doStream(options) {
436
- const { args, warnings } = await this.getArgs(options);
437
- const { responseHeaders, value: response } = await postJsonToApi({
438
- url: `${this.config.baseURL}/chat`,
439
- headers: combineHeaders(this.config.headers(), options.headers),
440
- body: { ...args, stream: true },
441
- failedResponseHandler: cohereFailedResponseHandler,
442
- successfulResponseHandler: createEventSourceResponseHandler(
443
- cohereChatChunkSchema
444
- ),
445
- abortSignal: options.abortSignal,
446
- fetch: this.config.fetch
447
- });
448
- let finishReason = {
449
- unified: "other",
450
- raw: void 0
451
- };
452
- let usage = void 0;
453
- let pendingToolCall = null;
454
- let isActiveReasoning = false;
455
- return {
456
- stream: response.pipeThrough(
457
- new TransformStream({
458
- start(controller) {
459
- controller.enqueue({ type: "stream-start", warnings });
460
- },
461
- transform(chunk, controller) {
462
- var _a, _b;
463
- if (options.includeRawChunks) {
464
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
465
- }
466
- if (!chunk.success) {
467
- finishReason = { unified: "error", raw: void 0 };
468
- controller.enqueue({ type: "error", error: chunk.error });
469
- return;
470
- }
471
- const value = chunk.value;
472
- const type = value.type;
473
- switch (type) {
474
- case "content-start": {
475
- if (value.delta.message.content.type === "thinking") {
476
- controller.enqueue({
477
- type: "reasoning-start",
478
- id: String(value.index)
479
- });
480
- isActiveReasoning = true;
481
- return;
482
- }
483
- controller.enqueue({
484
- type: "text-start",
485
- id: String(value.index)
486
- });
487
- return;
488
- }
489
- case "content-delta": {
490
- if ("thinking" in value.delta.message.content) {
491
- controller.enqueue({
492
- type: "reasoning-delta",
493
- id: String(value.index),
494
- delta: value.delta.message.content.thinking
495
- });
496
- return;
497
- }
498
- controller.enqueue({
499
- type: "text-delta",
500
- id: String(value.index),
501
- delta: value.delta.message.content.text
502
- });
503
- return;
504
- }
505
- case "content-end": {
506
- if (isActiveReasoning) {
507
- controller.enqueue({
508
- type: "reasoning-end",
509
- id: String(value.index)
510
- });
511
- isActiveReasoning = false;
512
- return;
513
- }
514
- controller.enqueue({
515
- type: "text-end",
516
- id: String(value.index)
517
- });
518
- return;
519
- }
520
- case "tool-call-start": {
521
- const toolId = value.delta.message.tool_calls.id;
522
- const toolName = value.delta.message.tool_calls.function.name;
523
- const initialArgs = value.delta.message.tool_calls.function.arguments;
524
- pendingToolCall = {
525
- id: toolId,
526
- name: toolName,
527
- arguments: initialArgs,
528
- hasFinished: false
529
- };
530
- controller.enqueue({
531
- type: "tool-input-start",
532
- id: toolId,
533
- toolName
534
- });
535
- if (initialArgs.length > 0) {
536
- controller.enqueue({
537
- type: "tool-input-delta",
538
- id: toolId,
539
- delta: initialArgs
540
- });
541
- }
542
- return;
543
- }
544
- case "tool-call-delta": {
545
- if (pendingToolCall && !pendingToolCall.hasFinished) {
546
- const argsDelta = value.delta.message.tool_calls.function.arguments;
547
- pendingToolCall.arguments += argsDelta;
548
- controller.enqueue({
549
- type: "tool-input-delta",
550
- id: pendingToolCall.id,
551
- delta: argsDelta
552
- });
553
- }
554
- return;
555
- }
556
- case "tool-call-end": {
557
- if (pendingToolCall && !pendingToolCall.hasFinished) {
558
- controller.enqueue({
559
- type: "tool-input-end",
560
- id: pendingToolCall.id
561
- });
562
- controller.enqueue({
563
- type: "tool-call",
564
- toolCallId: pendingToolCall.id,
565
- toolName: pendingToolCall.name,
566
- input: JSON.stringify(
567
- JSON.parse(((_a = pendingToolCall.arguments) == null ? void 0 : _a.trim()) || "{}")
568
- )
569
- });
570
- pendingToolCall.hasFinished = true;
571
- pendingToolCall = null;
572
- }
573
- return;
574
- }
575
- case "message-start": {
576
- controller.enqueue({
577
- type: "response-metadata",
578
- id: (_b = value.id) != null ? _b : void 0
579
- });
580
- return;
581
- }
582
- case "message-end": {
583
- finishReason = {
584
- unified: mapCohereFinishReason(value.delta.finish_reason),
585
- raw: value.delta.finish_reason
586
- };
587
- usage = value.delta.usage.tokens;
588
- return;
589
- }
590
- default: {
591
- return;
592
- }
593
- }
594
- },
595
- flush(controller) {
596
- controller.enqueue({
597
- type: "finish",
598
- finishReason,
599
- usage: convertCohereUsage(usage)
600
- });
601
- }
602
- })
603
- ),
604
- request: { body: { ...args, stream: true } },
605
- response: { headers: responseHeaders }
606
- };
607
- }
608
- };
609
- var cohereChatResponseSchema = z3.object({
610
- generation_id: z3.string().nullish(),
611
- message: z3.object({
612
- role: z3.string(),
613
- content: z3.array(
614
- z3.union([
615
- z3.object({
616
- type: z3.literal("text"),
617
- text: z3.string()
618
- }),
619
- z3.object({
620
- type: z3.literal("thinking"),
621
- thinking: z3.string()
622
- })
623
- ])
624
- ).nullish(),
625
- tool_plan: z3.string().nullish(),
626
- tool_calls: z3.array(
627
- z3.object({
628
- id: z3.string(),
629
- type: z3.literal("function"),
630
- function: z3.object({
631
- name: z3.string(),
632
- arguments: z3.string()
633
- })
634
- })
635
- ).nullish(),
636
- citations: z3.array(
637
- z3.object({
638
- start: z3.number(),
639
- end: z3.number(),
640
- text: z3.string(),
641
- sources: z3.array(
642
- z3.object({
643
- type: z3.string().optional(),
644
- id: z3.string().optional(),
645
- document: z3.object({
646
- id: z3.string().optional(),
647
- text: z3.string(),
648
- title: z3.string()
649
- })
650
- })
651
- ),
652
- type: z3.string().optional()
653
- })
654
- ).nullish()
655
- }),
656
- finish_reason: z3.string(),
657
- usage: z3.object({
658
- billed_units: z3.object({
659
- input_tokens: z3.number(),
660
- output_tokens: z3.number()
661
- }),
662
- tokens: z3.object({
663
- input_tokens: z3.number(),
664
- output_tokens: z3.number()
665
- })
666
- })
667
- });
668
- var cohereChatChunkSchema = z3.discriminatedUnion("type", [
669
- z3.object({
670
- type: z3.literal("citation-start")
671
- }),
672
- z3.object({
673
- type: z3.literal("citation-end")
674
- }),
675
- z3.object({
676
- type: z3.literal("content-start"),
677
- index: z3.number(),
678
- delta: z3.object({
679
- message: z3.object({
680
- content: z3.union([
681
- z3.object({
682
- type: z3.literal("text"),
683
- text: z3.string()
684
- }),
685
- z3.object({
686
- type: z3.literal("thinking"),
687
- thinking: z3.string()
688
- })
689
- ])
690
- })
691
- })
692
- }),
693
- z3.object({
694
- type: z3.literal("content-delta"),
695
- index: z3.number(),
696
- delta: z3.object({
697
- message: z3.object({
698
- content: z3.union([
699
- z3.object({
700
- text: z3.string()
701
- }),
702
- z3.object({
703
- thinking: z3.string()
704
- })
705
- ])
706
- })
707
- })
708
- }),
709
- z3.object({
710
- type: z3.literal("content-end"),
711
- index: z3.number()
712
- }),
713
- z3.object({
714
- type: z3.literal("message-start"),
715
- id: z3.string().nullish()
716
- }),
717
- z3.object({
718
- type: z3.literal("message-end"),
719
- delta: z3.object({
720
- finish_reason: z3.string(),
721
- usage: z3.object({
722
- tokens: z3.object({
723
- input_tokens: z3.number(),
724
- output_tokens: z3.number()
725
- })
726
- })
727
- })
728
- }),
729
- // https://docs.cohere.com/v2/docs/streaming#tool-use-stream-events-for-tool-calling
730
- z3.object({
731
- type: z3.literal("tool-plan-delta"),
732
- delta: z3.object({
733
- message: z3.object({
734
- tool_plan: z3.string()
735
- })
736
- })
737
- }),
738
- z3.object({
739
- type: z3.literal("tool-call-start"),
740
- delta: z3.object({
741
- message: z3.object({
742
- tool_calls: z3.object({
743
- id: z3.string(),
744
- type: z3.literal("function"),
745
- function: z3.object({
746
- name: z3.string(),
747
- arguments: z3.string()
748
- })
749
- })
750
- })
751
- })
752
- }),
753
- // A single tool call's `arguments` stream in chunks and must be accumulated
754
- // in a string and so the full tool object info can only be parsed once we see
755
- // `tool-call-end`.
756
- z3.object({
757
- type: z3.literal("tool-call-delta"),
758
- delta: z3.object({
759
- message: z3.object({
760
- tool_calls: z3.object({
761
- function: z3.object({
762
- arguments: z3.string()
763
- })
764
- })
765
- })
766
- })
767
- }),
768
- z3.object({
769
- type: z3.literal("tool-call-end")
770
- })
771
- ]);
772
-
773
- // src/cohere-embedding-model.ts
774
- import {
775
- TooManyEmbeddingValuesForCallError
776
- } from "@ai-sdk/provider";
777
- import {
778
- combineHeaders as combineHeaders2,
779
- createJsonResponseHandler as createJsonResponseHandler2,
780
- parseProviderOptions as parseProviderOptions2,
781
- postJsonToApi as postJsonToApi2
782
- } from "@ai-sdk/provider-utils";
783
- import { z as z5 } from "zod/v4";
784
-
785
- // src/cohere-embedding-options.ts
786
- import { z as z4 } from "zod/v4";
787
- var cohereEmbeddingModelOptions = z4.object({
788
- /**
789
- * Specifies the type of input passed to the model. Default is `search_query`.
790
- *
791
- * - "search_document": Used for embeddings stored in a vector database for search use-cases.
792
- * - "search_query": Used for embeddings of search queries run against a vector DB to find relevant documents.
793
- * - "classification": Used for embeddings passed through a text classifier.
794
- * - "clustering": Used for embeddings run through a clustering algorithm.
795
- */
796
- inputType: z4.enum(["search_document", "search_query", "classification", "clustering"]).optional(),
797
- /**
798
- * Specifies how the API will handle inputs longer than the maximum token length.
799
- * Default is `END`.
800
- *
801
- * - "NONE": If selected, when the input exceeds the maximum input token length will return an error.
802
- * - "START": Will discard the start of the input until the remaining input is exactly the maximum input token length for the model.
803
- * - "END": Will discard the end of the input until the remaining input is exactly the maximum input token length for the model.
804
- */
805
- truncate: z4.enum(["NONE", "START", "END"]).optional(),
806
- /**
807
- * The number of dimensions of the output embedding.
808
- * Only available for `embed-v4.0` and newer models.
809
- *
810
- * Possible values are `256`, `512`, `1024`, and `1536`.
811
- * The default is `1536`.
812
- */
813
- outputDimension: z4.union([z4.literal(256), z4.literal(512), z4.literal(1024), z4.literal(1536)]).optional()
814
- });
815
-
816
- // src/cohere-embedding-model.ts
817
- var CohereEmbeddingModel = class {
818
- constructor(modelId, config) {
819
- this.specificationVersion = "v3";
820
- this.maxEmbeddingsPerCall = 96;
821
- this.supportsParallelCalls = true;
822
- this.modelId = modelId;
823
- this.config = config;
824
- }
825
- get provider() {
826
- return this.config.provider;
827
- }
828
- async doEmbed({
829
- values,
830
- headers,
831
- abortSignal,
832
- providerOptions
833
- }) {
834
- var _a;
835
- const embeddingOptions = await parseProviderOptions2({
836
- provider: "cohere",
837
- providerOptions,
838
- schema: cohereEmbeddingModelOptions
839
- });
840
- if (values.length > this.maxEmbeddingsPerCall) {
841
- throw new TooManyEmbeddingValuesForCallError({
842
- provider: this.provider,
843
- modelId: this.modelId,
844
- maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
845
- values
846
- });
847
- }
848
- const {
849
- responseHeaders,
850
- value: response,
851
- rawValue
852
- } = await postJsonToApi2({
853
- url: `${this.config.baseURL}/embed`,
854
- headers: combineHeaders2(this.config.headers(), headers),
855
- body: {
856
- model: this.modelId,
857
- // The AI SDK only supports 'float' embeddings. Note that the Cohere API
858
- // supports other embedding types, but they are not currently supported by the AI SDK.
859
- // https://docs.cohere.com/v2/reference/embed#request.body.embedding_types
860
- embedding_types: ["float"],
861
- texts: values,
862
- input_type: (_a = embeddingOptions == null ? void 0 : embeddingOptions.inputType) != null ? _a : "search_query",
863
- truncate: embeddingOptions == null ? void 0 : embeddingOptions.truncate,
864
- output_dimension: embeddingOptions == null ? void 0 : embeddingOptions.outputDimension
865
- },
866
- failedResponseHandler: cohereFailedResponseHandler,
867
- successfulResponseHandler: createJsonResponseHandler2(
868
- cohereTextEmbeddingResponseSchema
869
- ),
870
- abortSignal,
871
- fetch: this.config.fetch
872
- });
873
- return {
874
- warnings: [],
875
- embeddings: response.embeddings.float,
876
- usage: { tokens: response.meta.billed_units.input_tokens },
877
- response: { headers: responseHeaders, body: rawValue }
878
- };
879
- }
880
- };
881
- var cohereTextEmbeddingResponseSchema = z5.object({
882
- embeddings: z5.object({
883
- float: z5.array(z5.array(z5.number()))
884
- }),
885
- meta: z5.object({
886
- billed_units: z5.object({
887
- input_tokens: z5.number()
888
- })
889
- })
890
- });
891
-
892
- // src/reranking/cohere-reranking-model.ts
893
- import {
894
- combineHeaders as combineHeaders3,
895
- createJsonResponseHandler as createJsonResponseHandler3,
896
- parseProviderOptions as parseProviderOptions3,
897
- postJsonToApi as postJsonToApi3
898
- } from "@ai-sdk/provider-utils";
899
-
900
- // src/reranking/cohere-reranking-api.ts
901
- import { lazySchema, zodSchema } from "@ai-sdk/provider-utils";
902
- import { z as z6 } from "zod/v4";
903
- var cohereRerankingResponseSchema = lazySchema(
904
- () => zodSchema(
905
- z6.object({
906
- id: z6.string().nullish(),
907
- results: z6.array(
908
- z6.object({
909
- index: z6.number(),
910
- relevance_score: z6.number()
911
- })
912
- ),
913
- meta: z6.any()
914
- })
915
- )
916
- );
917
-
918
- // src/reranking/cohere-reranking-options.ts
919
- import { lazySchema as lazySchema2, zodSchema as zodSchema2 } from "@ai-sdk/provider-utils";
920
- import { z as z7 } from "zod/v4";
921
- var cohereRerankingModelOptionsSchema = lazySchema2(
922
- () => zodSchema2(
923
- z7.object({
924
- maxTokensPerDoc: z7.number().optional(),
925
- priority: z7.number().optional()
926
- })
927
- )
928
- );
929
-
930
- // src/reranking/cohere-reranking-model.ts
931
- var CohereRerankingModel = class {
932
- constructor(modelId, config) {
933
- this.specificationVersion = "v3";
934
- this.modelId = modelId;
935
- this.config = config;
936
- }
937
- get provider() {
938
- return this.config.provider;
939
- }
940
- // current implementation is based on v2 of the API: https://docs.cohere.com/v2/reference/rerank
941
- async doRerank({
942
- documents,
943
- headers,
944
- query,
945
- topN,
946
- abortSignal,
947
- providerOptions
948
- }) {
949
- var _a;
950
- const rerankingOptions = await parseProviderOptions3({
951
- provider: "cohere",
952
- providerOptions,
953
- schema: cohereRerankingModelOptionsSchema
954
- });
955
- const warnings = [];
956
- if (documents.type === "object") {
957
- warnings.push({
958
- type: "compatibility",
959
- feature: "object documents",
960
- details: "Object documents are converted to strings."
961
- });
962
- }
963
- const {
964
- responseHeaders,
965
- value: response,
966
- rawValue
967
- } = await postJsonToApi3({
968
- url: `${this.config.baseURL}/rerank`,
969
- headers: combineHeaders3(this.config.headers(), headers),
970
- body: {
971
- model: this.modelId,
972
- query,
973
- documents: documents.type === "text" ? documents.values : documents.values.map((value) => JSON.stringify(value)),
974
- top_n: topN,
975
- max_tokens_per_doc: rerankingOptions == null ? void 0 : rerankingOptions.maxTokensPerDoc,
976
- priority: rerankingOptions == null ? void 0 : rerankingOptions.priority
977
- },
978
- failedResponseHandler: cohereFailedResponseHandler,
979
- successfulResponseHandler: createJsonResponseHandler3(
980
- cohereRerankingResponseSchema
981
- ),
982
- abortSignal,
983
- fetch: this.config.fetch
984
- });
985
- return {
986
- ranking: response.results.map((result) => ({
987
- index: result.index,
988
- relevanceScore: result.relevance_score
989
- })),
990
- warnings,
991
- response: {
992
- id: (_a = response.id) != null ? _a : void 0,
993
- headers: responseHeaders,
994
- body: rawValue
995
- }
996
- };
997
- }
998
- };
999
-
1000
- // src/version.ts
1001
- var VERSION = true ? "4.0.0-beta.2" : "0.0.0-test";
1002
-
1003
- // src/cohere-provider.ts
1004
- function createCohere(options = {}) {
1005
- var _a;
1006
- const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.cohere.com/v2";
1007
- const getHeaders = () => withUserAgentSuffix(
1008
- {
1009
- Authorization: `Bearer ${loadApiKey({
1010
- apiKey: options.apiKey,
1011
- environmentVariableName: "COHERE_API_KEY",
1012
- description: "Cohere"
1013
- })}`,
1014
- ...options.headers
1015
- },
1016
- `ai-sdk/cohere/${VERSION}`
1017
- );
1018
- const createChatModel = (modelId) => {
1019
- var _a2;
1020
- return new CohereChatLanguageModel(modelId, {
1021
- provider: "cohere.chat",
1022
- baseURL,
1023
- headers: getHeaders,
1024
- fetch: options.fetch,
1025
- generateId: (_a2 = options.generateId) != null ? _a2 : generateId
1026
- });
1027
- };
1028
- const createEmbeddingModel = (modelId) => new CohereEmbeddingModel(modelId, {
1029
- provider: "cohere.textEmbedding",
1030
- baseURL,
1031
- headers: getHeaders,
1032
- fetch: options.fetch
1033
- });
1034
- const createRerankingModel = (modelId) => new CohereRerankingModel(modelId, {
1035
- provider: "cohere.reranking",
1036
- baseURL,
1037
- headers: getHeaders,
1038
- fetch: options.fetch
1039
- });
1040
- const provider = function(modelId) {
1041
- if (new.target) {
1042
- throw new Error(
1043
- "The Cohere model function cannot be called with the new keyword."
1044
- );
1045
- }
1046
- return createChatModel(modelId);
1047
- };
1048
- provider.specificationVersion = "v3";
1049
- provider.languageModel = createChatModel;
1050
- provider.embedding = createEmbeddingModel;
1051
- provider.embeddingModel = createEmbeddingModel;
1052
- provider.textEmbedding = createEmbeddingModel;
1053
- provider.textEmbeddingModel = createEmbeddingModel;
1054
- provider.reranking = createRerankingModel;
1055
- provider.rerankingModel = createRerankingModel;
1056
- provider.imageModel = (modelId) => {
1057
- throw new NoSuchModelError({ modelId, modelType: "imageModel" });
1058
- };
1059
- return provider;
1060
- }
1061
- var cohere = createCohere();
1062
- export {
1063
- VERSION,
1064
- cohere,
1065
- createCohere
1066
- };
1067
- //# sourceMappingURL=index.mjs.map