@ai-sdk/cohere 4.0.75 → 4.0.77

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.
@@ -33,7 +33,15 @@ import {
33
33
  cohereLanguageModelChatOptions,
34
34
  type CohereChatModelId,
35
35
  } from './cohere-chat-language-model-options';
36
+ import {
37
+ cohereCitationSchema,
38
+ mapCohereCitationToSource,
39
+ } from './cohere-citations';
36
40
  import { cohereFailedResponseHandler } from './cohere-error';
41
+ import {
42
+ getCohereLanguageModelEntry,
43
+ type CohereLanguageModelEntry,
44
+ } from './cohere-model-catalog';
37
45
  import { prepareTools } from './cohere-prepare-tools';
38
46
  import { convertCohereUsage, type CohereUsage } from './convert-cohere-usage';
39
47
  import { convertToCohereChatPrompt } from './convert-to-cohere-chat-prompt';
@@ -153,6 +161,7 @@ export class CohereChatLanguageModel implements LanguageModelV4 {
153
161
 
154
162
  // reasoning:
155
163
  ...resolveCohereThinking({
164
+ modelEntry: getCohereLanguageModelEntry(this.modelId),
156
165
  reasoning,
157
166
  cohereOptions,
158
167
  warnings,
@@ -202,22 +211,15 @@ export class CohereChatLanguageModel implements LanguageModelV4 {
202
211
 
203
212
  // citations:
204
213
  for (const citation of response.message.citations ?? []) {
205
- content.push({
206
- type: 'source',
207
- sourceType: 'document',
208
- id: this.config.generateId(),
209
- mediaType: 'text/plain',
210
- title: citation.sources[0]?.document?.title || 'Document',
211
- providerMetadata: {
212
- cohere: {
213
- start: citation.start,
214
- end: citation.end,
215
- text: citation.text,
216
- sources: citation.sources,
217
- ...(citation.type && { citationType: citation.type }),
218
- },
219
- },
220
- });
214
+ // Tool-sourced citations (e.g. citations of tool results in a follow-up
215
+ // step) have no document to point at, so they are not emitted as sources.
216
+ const source = mapCohereCitationToSource(citation, () =>
217
+ this.config.generateId(),
218
+ );
219
+
220
+ if (source != null) {
221
+ content.push(source);
222
+ }
221
223
  }
222
224
 
223
225
  // tool calls:
@@ -242,7 +244,9 @@ export class CohereChatLanguageModel implements LanguageModelV4 {
242
244
  request: { body: args },
243
245
  response: {
244
246
  // TODO timestamp, model id
245
- id: response.generation_id ?? undefined,
247
+ // Cohere v2 returns `id`; `generation_id` is the v1 field, kept only
248
+ // for compatibility with proxies/mocks that still return it.
249
+ id: response.id ?? response.generation_id ?? undefined,
246
250
  headers: responseHeaders,
247
251
  body: rawResponse,
248
252
  },
@@ -286,6 +290,8 @@ export class CohereChatLanguageModel implements LanguageModelV4 {
286
290
 
287
291
  let isActiveReasoning = false;
288
292
 
293
+ const generateId = this.config.generateId;
294
+
289
295
  return {
290
296
  stream: response.pipeThrough(
291
297
  new TransformStream<
@@ -365,6 +371,29 @@ export class CohereChatLanguageModel implements LanguageModelV4 {
365
371
  return;
366
372
  }
367
373
 
374
+ case 'citation-start': {
375
+ const citations = value.delta?.message?.citations;
376
+ if (citations == null) {
377
+ return;
378
+ }
379
+
380
+ for (const citation of Array.isArray(citations)
381
+ ? citations
382
+ : [citations]) {
383
+ // Tool-only citations have no document, so they are not
384
+ // emitted as sources (matching doGenerate).
385
+ const source = mapCohereCitationToSource(
386
+ citation,
387
+ generateId,
388
+ );
389
+
390
+ if (source != null) {
391
+ controller.enqueue(source);
392
+ }
393
+ }
394
+ return;
395
+ }
396
+
368
397
  case 'tool-call-start': {
369
398
  const toolId = value.delta.message.tool_calls.id;
370
399
  const toolName = value.delta.message.tool_calls.function.name;
@@ -421,9 +450,9 @@ export class CohereChatLanguageModel implements LanguageModelV4 {
421
450
  toolCallId: pendingToolCall.id,
422
451
  toolName: pendingToolCall.name,
423
452
  input: JSON.stringify(
424
- await parseJSON({
453
+ (await parseJSON({
425
454
  text: pendingToolCall.arguments?.trim() || '{}',
426
- }),
455
+ })) ?? {},
427
456
  ),
428
457
  });
429
458
 
@@ -471,18 +500,24 @@ export class CohereChatLanguageModel implements LanguageModelV4 {
471
500
  }
472
501
 
473
502
  function resolveCohereThinking({
503
+ modelEntry,
474
504
  reasoning,
475
505
  cohereOptions,
476
506
  warnings,
477
507
  }: {
508
+ modelEntry: CohereLanguageModelEntry;
478
509
  reasoning: LanguageModelV4CallOptions['reasoning'];
479
510
  cohereOptions: InferSchema<typeof cohereLanguageModelChatOptions>;
480
511
  warnings: SharedV4Warning[];
481
512
  }): { thinking?: { type: string; token_budget?: number } } {
513
+ const {
514
+ capabilities: { language: capabilities },
515
+ requestConfig: { language: defaults },
516
+ } = modelEntry;
482
517
  if (cohereOptions.thinking) {
483
518
  return {
484
519
  thinking: {
485
- type: cohereOptions.thinking.type ?? 'enabled',
520
+ type: cohereOptions.thinking.type ?? defaults.thinkingType,
486
521
  token_budget: cohereOptions.thinking.tokenBudget,
487
522
  },
488
523
  };
@@ -498,8 +533,8 @@ function resolveCohereThinking({
498
533
 
499
534
  const tokenBudget = mapReasoningToProviderBudget({
500
535
  reasoning,
501
- maxOutputTokens: 32768,
502
- maxReasoningBudget: 32768,
536
+ maxOutputTokens: defaults.reasoningMaxOutputTokens,
537
+ maxReasoningBudget: capabilities.reasoning.maxBudget,
503
538
  warnings,
504
539
  });
505
540
 
@@ -507,24 +542,28 @@ function resolveCohereThinking({
507
542
  }
508
543
 
509
544
  // Loose, nested objects included: the parsed value is returned as `usage.raw`.
545
+ // All fields are optional in the API specification, so every field is nullish.
510
546
  const cohereUsageSchema = () =>
511
547
  z.looseObject({
512
548
  billed_units: z
513
549
  .looseObject({
514
- input_tokens: z.number(),
515
- output_tokens: z.number(),
550
+ input_tokens: z.number().nullish(),
551
+ output_tokens: z.number().nullish(),
552
+ })
553
+ .nullish(),
554
+ tokens: z
555
+ .looseObject({
556
+ input_tokens: z.number().nullish(),
557
+ output_tokens: z.number().nullish(),
516
558
  })
517
559
  .nullish(),
518
- tokens: z.looseObject({
519
- input_tokens: z.number(),
520
- output_tokens: z.number(),
521
- }),
522
560
  cached_tokens: z.number().nullish(),
523
561
  });
524
562
 
525
563
  const cohereChatResponseSchema = lazySchema(() =>
526
564
  zodSchema(
527
565
  z.object({
566
+ id: z.string().nullish(),
528
567
  generation_id: z.string().nullish(),
529
568
  message: z.object({
530
569
  role: z.string(),
@@ -555,30 +594,10 @@ const cohereChatResponseSchema = lazySchema(() =>
555
594
  }),
556
595
  )
557
596
  .nullish(),
558
- citations: z
559
- .array(
560
- z.object({
561
- start: z.number(),
562
- end: z.number(),
563
- text: z.string(),
564
- sources: z.array(
565
- z.object({
566
- type: z.string().optional(),
567
- id: z.string().optional(),
568
- document: z.object({
569
- id: z.string().optional(),
570
- text: z.string(),
571
- title: z.string(),
572
- }),
573
- }),
574
- ),
575
- type: z.string().optional(),
576
- }),
577
- )
578
- .nullish(),
597
+ citations: z.array(cohereCitationSchema).nullish(),
579
598
  }),
580
599
  finish_reason: z.string(),
581
- usage: cohereUsageSchema(),
600
+ usage: cohereUsageSchema().nullish(),
582
601
  }),
583
602
  ),
584
603
  );
@@ -588,8 +607,22 @@ const cohereChatResponseSchema = lazySchema(() =>
588
607
  const cohereChatChunkSchema = lazySchema(() =>
589
608
  zodSchema(
590
609
  z.discriminatedUnion('type', [
610
+ // `citation-start` events can arrive without citations, and a single
611
+ // citation may be sent instead of an array.
591
612
  z.object({
592
613
  type: z.literal('citation-start'),
614
+ index: z.number().nullish(),
615
+ delta: z
616
+ .object({
617
+ message: z
618
+ .object({
619
+ citations: z
620
+ .union([cohereCitationSchema, z.array(cohereCitationSchema)])
621
+ .nullish(),
622
+ })
623
+ .nullish(),
624
+ })
625
+ .nullish(),
593
626
  }),
594
627
  z.object({
595
628
  type: z.literal('citation-end'),
@@ -0,0 +1,77 @@
1
+ import type { JSONArray, LanguageModelV4Source } from '@ai-sdk/provider';
2
+ import { z } from 'zod/v4';
3
+
4
+ /**
5
+ * Citation payload Cohere returns for text content, in non-streaming responses
6
+ * and in `citation-start` stream events.
7
+ *
8
+ * All fields are optional in the API specification, and a source can reference
9
+ * either a document or tool output, so partial citations are validated instead
10
+ * of discarding the whole response.
11
+ */
12
+ export const cohereCitationSchema = z.object({
13
+ start: z.number().nullish(),
14
+ end: z.number().nullish(),
15
+ text: z.string().nullish(),
16
+ sources: z
17
+ .array(
18
+ z.object({
19
+ type: z.string().nullish(),
20
+ id: z.string().nullish(),
21
+ // Documents are arbitrary objects; only the fields the provider maps
22
+ // are typed, everything else is passed through as provider metadata.
23
+ document: z
24
+ .looseObject({
25
+ id: z.string().nullish(),
26
+ text: z.string().nullish(),
27
+ title: z.string().nullish(),
28
+ })
29
+ .nullish(),
30
+ tool_output: z.looseObject({}).nullish(),
31
+ }),
32
+ )
33
+ .nullish(),
34
+ type: z.string().nullish(),
35
+ });
36
+
37
+ export type CohereCitation = z.infer<typeof cohereCitationSchema>;
38
+
39
+ /**
40
+ * Maps a Cohere citation to a document source.
41
+ *
42
+ * The first source with a document provides the title; all sources are kept in
43
+ * `providerMetadata`. Citations that only reference tool output have no
44
+ * document to point at and return `undefined` (their data stays in the response
45
+ * body).
46
+ */
47
+ export function mapCohereCitationToSource(
48
+ citation: CohereCitation,
49
+ generateId: () => string,
50
+ ): LanguageModelV4Source | undefined {
51
+ const document = citation.sources?.find(
52
+ source => source.document != null,
53
+ )?.document;
54
+
55
+ if (document == null) {
56
+ return undefined;
57
+ }
58
+
59
+ return {
60
+ type: 'source',
61
+ sourceType: 'document',
62
+ id: generateId(),
63
+ mediaType: 'text/plain',
64
+ title: document.title || 'Document',
65
+ providerMetadata: {
66
+ cohere: {
67
+ ...(citation.start != null && { start: citation.start }),
68
+ ...(citation.end != null && { end: citation.end }),
69
+ ...(citation.text != null && { text: citation.text }),
70
+ ...(citation.sources != null && {
71
+ sources: citation.sources as JSONArray,
72
+ }),
73
+ ...(citation.type != null && { citationType: citation.type }),
74
+ },
75
+ },
76
+ };
77
+ }
@@ -21,6 +21,10 @@ import {
21
21
  type CohereEmbeddingModelOptions,
22
22
  } from './cohere-embedding-model-options';
23
23
  import { cohereFailedResponseHandler } from './cohere-error';
24
+ import {
25
+ cohereEmbeddingModelLimits,
26
+ getCohereEmbeddingModelEntry,
27
+ } from './cohere-model-catalog';
24
28
 
25
29
  type CohereEmbeddingConfig = {
26
30
  provider: string;
@@ -33,8 +37,8 @@ export class CohereEmbeddingModel implements EmbeddingModelV4 {
33
37
  readonly specificationVersion = 'v4';
34
38
  readonly modelId: CohereEmbeddingModelId;
35
39
 
36
- readonly maxEmbeddingsPerCall = 96;
37
- readonly supportsParallelCalls = true;
40
+ readonly maxEmbeddingsPerCall: number;
41
+ readonly supportsParallelCalls: boolean;
38
42
 
39
43
  private readonly config: CohereEmbeddingConfig;
40
44
 
@@ -54,6 +58,11 @@ export class CohereEmbeddingModel implements EmbeddingModelV4 {
54
58
 
55
59
  constructor(modelId: CohereEmbeddingModelId, config: CohereEmbeddingConfig) {
56
60
  this.modelId = modelId;
61
+ const limits =
62
+ getCohereEmbeddingModelEntry(modelId).capabilities.embedding ??
63
+ cohereEmbeddingModelLimits;
64
+ this.maxEmbeddingsPerCall = limits.maxEmbeddingsPerCall;
65
+ this.supportsParallelCalls = limits.supportsParallelCalls;
57
66
  this.config = config;
58
67
  }
59
68
 
@@ -75,7 +84,10 @@ export class CohereEmbeddingModel implements EmbeddingModelV4 {
75
84
  providerOptions,
76
85
  schema: cohereEmbeddingModelOptions,
77
86
  });
78
- const embeddingType = embeddingOptions?.embeddingType ?? 'float';
87
+ const defaults = getCohereEmbeddingModelEntry(this.modelId).requestConfig
88
+ .embedding;
89
+ const embeddingType =
90
+ embeddingOptions?.embeddingType ?? defaults.embeddingType;
79
91
 
80
92
  if (values.length > this.maxEmbeddingsPerCall) {
81
93
  throw new TooManyEmbeddingValuesForCallError({
@@ -97,7 +109,7 @@ export class CohereEmbeddingModel implements EmbeddingModelV4 {
97
109
  model: this.modelId,
98
110
  embedding_types: [embeddingType],
99
111
  texts: values,
100
- input_type: embeddingOptions?.inputType ?? 'search_query',
112
+ input_type: embeddingOptions?.inputType ?? defaults.inputType,
101
113
  truncate: embeddingOptions?.truncate,
102
114
  output_dimension: embeddingOptions?.outputDimension ?? dimensions,
103
115
  },