@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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,62 @@
1
1
  # @ai-sdk/cohere
2
2
 
3
+ ## 4.0.77
4
+
5
+ ### Patch Changes
6
+
7
+ - 3aad18a: fix(cohere): tolerate partial citations and usage in non-streaming responses
8
+
9
+ Cohere citations and usage fields are optional in the API specification, but the
10
+ response schema required `start`, `end`, `text`, every source `document` with
11
+ `text` and `title`, and usage token counts. Responses with untitled documents
12
+ (documents passed without a filename), with tool-sourced citations, or without
13
+ token counts failed with an `AI_TypeValidationError` and discarded the whole
14
+ response.
15
+
16
+ These fields are now validated loosely: citation fields and source `type`/`id`
17
+ are nullish, `document` is a loose object with optional `id`/`text`/`title`, tool
18
+ sources are accepted, and `usage` plus its token counts are nullish. Document
19
+ citations without a title fall back to `"Document"`. Tool-only citations are
20
+ skipped because they have no document to point at; their data stays in the
21
+ response body.
22
+
23
+ `convertCohereUsage` no longer falls back to `billed_units`, which are a
24
+ different measure than `tokens` (e.g. 12 billed vs 507 input tokens in a single
25
+ response) and would go negative when cached tokens are subtracted. A response
26
+ without `tokens` now reports undefined token counts instead of unrelated
27
+ numbers. This usage conversion is shared with streaming.
28
+
29
+ - 73400b2: fix(cohere): read the response id from v2 chat responses
30
+
31
+ The non-streaming response schema read `generation_id`, which Cohere's v2 chat
32
+ response does not return. As a result, `generateText().response.id` was a locally
33
+ generated fallback instead of the provider's id, while `streamText` returned the
34
+ id from the `message-start` event. `doGenerate` now reads `id` and keeps
35
+ `generation_id` (the v1 field) only for compatibility with proxies and mocks that
36
+ still return it.
37
+
38
+ - 033a980: fix(cohere): emit `source` stream parts for citations
39
+
40
+ `streamText` did not produce sources for Cohere RAG responses because `citation-start` stream events were ignored, while `generateText` mapped `message.citations` to document sources. Streaming now maps each cited document to the same `source` part as the non-streaming path. Citations that only reference tool output are not emitted as sources, and `citation-start` events without citations are ignored.
41
+
42
+ ## 4.0.76
43
+
44
+ ### Patch Changes
45
+
46
+ - 64ac130: Migrate Cohere chat, embedding and reranking models to a shared capability catalog, preserving request behavior and generating their capability tables from the catalog.
47
+ - 27c4487: Normalize streamed null tool arguments to an empty object so tools without parameters can execute, matching non-streaming calls.
48
+ - Updated dependencies [36802d4]
49
+ - Updated dependencies [e0143b0]
50
+ - Updated dependencies [934100c]
51
+ - Updated dependencies [892af4d]
52
+ - Updated dependencies [89aff56]
53
+ - Updated dependencies [41465fd]
54
+ - Updated dependencies [9754014]
55
+ - Updated dependencies [4bb73b0]
56
+ - Updated dependencies [2e44144]
57
+ - @ai-sdk/provider@4.0.36
58
+ - @ai-sdk/provider-utils@5.0.75
59
+
3
60
  ## 4.0.75
4
61
 
5
62
  ### Patch Changes
package/dist/index.js CHANGED
@@ -27,6 +27,58 @@ detail: z.enum([
27
27
  "high"
28
28
  ]).optional() })));
29
29
  //#endregion
30
+ //#region src/cohere-citations.ts
31
+ /**
32
+ * Citation payload Cohere returns for text content, in non-streaming responses
33
+ * and in `citation-start` stream events.
34
+ *
35
+ * All fields are optional in the API specification, and a source can reference
36
+ * either a document or tool output, so partial citations are validated instead
37
+ * of discarding the whole response.
38
+ */
39
+ const cohereCitationSchema = z.object({
40
+ start: z.number().nullish(),
41
+ end: z.number().nullish(),
42
+ text: z.string().nullish(),
43
+ sources: z.array(z.object({
44
+ type: z.string().nullish(),
45
+ id: z.string().nullish(),
46
+ document: z.looseObject({
47
+ id: z.string().nullish(),
48
+ text: z.string().nullish(),
49
+ title: z.string().nullish()
50
+ }).nullish(),
51
+ tool_output: z.looseObject({}).nullish()
52
+ })).nullish(),
53
+ type: z.string().nullish()
54
+ });
55
+ /**
56
+ * Maps a Cohere citation to a document source.
57
+ *
58
+ * The first source with a document provides the title; all sources are kept in
59
+ * `providerMetadata`. Citations that only reference tool output have no
60
+ * document to point at and return `undefined` (their data stays in the response
61
+ * body).
62
+ */
63
+ function mapCohereCitationToSource(citation, generateId) {
64
+ const document = citation.sources?.find((source) => source.document != null)?.document;
65
+ if (document == null) return;
66
+ return {
67
+ type: "source",
68
+ sourceType: "document",
69
+ id: generateId(),
70
+ mediaType: "text/plain",
71
+ title: document.title || "Document",
72
+ providerMetadata: { cohere: {
73
+ ...citation.start != null && { start: citation.start },
74
+ ...citation.end != null && { end: citation.end },
75
+ ...citation.text != null && { text: citation.text },
76
+ ...citation.sources != null && { sources: citation.sources },
77
+ ...citation.type != null && { citationType: citation.type }
78
+ } }
79
+ };
80
+ }
81
+ //#endregion
30
82
  //#region src/cohere-error.ts
31
83
  const cohereErrorDataSchema = lazySchema(() => zodSchema(z.object({ message: z.string() })));
32
84
  const cohereFailedResponseHandler = createJsonErrorResponseHandler({
@@ -34,6 +86,190 @@ const cohereFailedResponseHandler = createJsonErrorResponseHandler({
34
86
  errorToMessage: (data) => data.message
35
87
  });
36
88
  //#endregion
89
+ //#region src/cohere-model-catalog.ts
90
+ const cohereProviderOptions = {
91
+ language: { thinking: { description: "Enable or disable reasoning and set its token budget." } },
92
+ embedding: {
93
+ embeddingType: { description: "Embedding format returned by the API." },
94
+ inputType: { description: "Intended use of the input embeddings." },
95
+ truncate: { description: "How to truncate inputs exceeding the token limit." },
96
+ outputDimension: { description: "Output embedding dimensions." }
97
+ },
98
+ reranking: {
99
+ maxTokensPerDoc: { description: "Token limit for each document." },
100
+ priority: { description: "Request processing priority." }
101
+ }
102
+ };
103
+ const standard = {
104
+ image: false,
105
+ objectGeneration: true,
106
+ tools: true
107
+ };
108
+ const legacy = {
109
+ image: false,
110
+ objectGeneration: false,
111
+ tools: false
112
+ };
113
+ const languageDefinitions = {
114
+ "command-a-03-2025": standard,
115
+ "command-a-reasoning-08-2025": {
116
+ ...standard,
117
+ reasoning: true
118
+ },
119
+ "command-a-vision-07-2025": {
120
+ ...standard,
121
+ image: true
122
+ },
123
+ "command-r7b-12-2024": standard,
124
+ "command-r-plus-04-2024": standard,
125
+ "command-r-plus": standard,
126
+ "command-r-08-2024": standard,
127
+ "command-r-03-2024": standard,
128
+ "command-r": standard,
129
+ command: legacy,
130
+ "command-nightly": legacy,
131
+ "command-light": legacy,
132
+ "command-light-nightly": legacy
133
+ };
134
+ function createLanguageModelEntry(definition) {
135
+ const reasoningSupport = definition?.reasoning ?? "unknown";
136
+ return {
137
+ capabilities: { language: {
138
+ inputs: {
139
+ image: definition?.image ?? "unknown",
140
+ audio: false
141
+ },
142
+ objectGeneration: definition?.objectGeneration ?? "unknown",
143
+ tools: {
144
+ usage: definition?.tools ?? "unknown",
145
+ streaming: definition?.tools ?? "unknown"
146
+ },
147
+ reasoning: {
148
+ support: reasoningSupport,
149
+ maxBudget: 32768
150
+ },
151
+ sampling: {
152
+ temperature: "unknown",
153
+ topP: "unknown",
154
+ logprobs: false
155
+ }
156
+ } },
157
+ providerOptions: { language: declareProviderOptions(cohereProviderOptions.language, definition != null ? true : "unknown", { thinking: reasoningSupport }) },
158
+ requestConfig: { language: {
159
+ thinkingType: "enabled",
160
+ reasoningMaxOutputTokens: 32768
161
+ } }
162
+ };
163
+ }
164
+ const cohereEmbeddingModelLimits = {
165
+ maxEmbeddingsPerCall: 96,
166
+ supportsParallelCalls: true
167
+ };
168
+ const embeddingRequestConfig = {
169
+ embeddingType: "float",
170
+ inputType: "search_query"
171
+ };
172
+ const embeddingTypes = [
173
+ "float",
174
+ "int8",
175
+ "uint8",
176
+ "binary",
177
+ "ubinary"
178
+ ];
179
+ function createEmbeddingModelEntry(defaultDimensions, dimensions, formats = embeddingTypes) {
180
+ const customDimensions = dimensions.length > 1;
181
+ return {
182
+ capabilities: { embedding: {
183
+ defaultDimensions,
184
+ customDimensions,
185
+ dimensions,
186
+ embeddingTypes: formats,
187
+ ...cohereEmbeddingModelLimits
188
+ } },
189
+ providerOptions: { embedding: declareProviderOptions(cohereProviderOptions.embedding, true, {
190
+ outputDimension: customDimensions,
191
+ embeddingType: formats.length === 1 ? { condition: "Only embeddingType: 'float' is supported." } : true
192
+ }) },
193
+ requestConfig: { embedding: embeddingRequestConfig }
194
+ };
195
+ }
196
+ function createRerankingModelEntry(declared) {
197
+ const support = declared ? true : "unknown";
198
+ return {
199
+ capabilities: { reranking: {
200
+ documents: {
201
+ text: support,
202
+ object: declared ? { condition: "Objects are converted to JSON strings with a compatibility warning." } : "unknown"
203
+ },
204
+ topN: support
205
+ } },
206
+ providerOptions: { reranking: declareProviderOptions(cohereProviderOptions.reranking, support, {}) }
207
+ };
208
+ }
209
+ const cohereModelCatalog = {
210
+ ...Object.fromEntries(Object.entries(languageDefinitions).map(([modelId, definition]) => [modelId, createLanguageModelEntry(definition)])),
211
+ "embed-v5.0-pro": createEmbeddingModelEntry(2048, [
212
+ 256,
213
+ 512,
214
+ 768,
215
+ 1024,
216
+ 1536,
217
+ 2048
218
+ ]),
219
+ "embed-v5.0-fast": createEmbeddingModelEntry(2048, [
220
+ 256,
221
+ 512,
222
+ 768,
223
+ 1024,
224
+ 1536,
225
+ 2048
226
+ ]),
227
+ "embed-v4.0": createEmbeddingModelEntry(1536, [
228
+ 256,
229
+ 512,
230
+ 1024,
231
+ 1536
232
+ ]),
233
+ "embed-english-v3.0": createEmbeddingModelEntry(1024, [1024]),
234
+ "embed-multilingual-v3.0": createEmbeddingModelEntry(1024, [1024]),
235
+ "embed-english-light-v3.0": createEmbeddingModelEntry(384, [384]),
236
+ "embed-multilingual-light-v3.0": createEmbeddingModelEntry(384, [384]),
237
+ "embed-english-v2.0": createEmbeddingModelEntry(4096, [4096], ["float"]),
238
+ "embed-english-light-v2.0": createEmbeddingModelEntry(1024, [1024], ["float"]),
239
+ "embed-multilingual-v2.0": createEmbeddingModelEntry(768, [768], ["float"]),
240
+ "rerank-v4.0-pro": createRerankingModelEntry(true),
241
+ "rerank-v4.0-fast": createRerankingModelEntry(true),
242
+ "rerank-v3.5": createRerankingModelEntry(true),
243
+ "rerank-english-v3.0": createRerankingModelEntry(true),
244
+ "rerank-multilingual-v3.0": createRerankingModelEntry(true)
245
+ };
246
+ function findModelEntry(modelId) {
247
+ return Object.prototype.hasOwnProperty.call(cohereModelCatalog, modelId) ? cohereModelCatalog[modelId] : void 0;
248
+ }
249
+ function getCohereLanguageModelEntry(modelId) {
250
+ const entry = findModelEntry(modelId);
251
+ return entry?.capabilities.language != null && entry.providerOptions?.language != null && entry.requestConfig?.language != null ? {
252
+ capabilities: { language: entry.capabilities.language },
253
+ providerOptions: { language: entry.providerOptions.language },
254
+ requestConfig: { language: entry.requestConfig.language }
255
+ } : createLanguageModelEntry();
256
+ }
257
+ function getCohereEmbeddingModelEntry(modelId) {
258
+ const entry = findModelEntry(modelId);
259
+ return entry?.capabilities.embedding != null && entry.providerOptions?.embedding != null && entry.requestConfig?.embedding != null ? {
260
+ capabilities: { embedding: entry.capabilities.embedding },
261
+ providerOptions: { embedding: entry.providerOptions.embedding },
262
+ requestConfig: { embedding: entry.requestConfig.embedding }
263
+ } : {
264
+ capabilities: {},
265
+ providerOptions: { embedding: declareProviderOptions(cohereProviderOptions.embedding, "unknown", {}) },
266
+ requestConfig: { embedding: embeddingRequestConfig }
267
+ };
268
+ }
269
+ function declareProviderOptions(definitions, support, exceptions) {
270
+ return Object.fromEntries(Object.keys(definitions).map((option) => [option, exceptions[option] ?? support]));
271
+ }
272
+ //#endregion
37
273
  //#region src/cohere-prepare-tools.ts
38
274
  function prepareTools({ tools, toolChoice }) {
39
275
  tools = tools?.length ? tools : void 0;
@@ -90,14 +326,13 @@ function prepareTools({ tools, toolChoice }) {
90
326
  //#region src/convert-cohere-usage.ts
91
327
  function convertCohereUsage(usage) {
92
328
  if (usage == null) return createNullLanguageModelUsage();
93
- const tokens = usage.tokens;
94
- const inputTokens = tokens.input_tokens;
95
- const outputTokens = tokens.output_tokens;
329
+ const inputTokens = usage.tokens?.input_tokens ?? void 0;
330
+ const outputTokens = usage.tokens?.output_tokens ?? void 0;
96
331
  const cacheReadTokens = usage.cached_tokens ?? void 0;
97
332
  return {
98
333
  inputTokens: {
99
334
  total: inputTokens,
100
- noCache: cacheReadTokens != null ? inputTokens - cacheReadTokens : inputTokens,
335
+ noCache: inputTokens != null && cacheReadTokens != null ? inputTokens - cacheReadTokens : inputTokens,
101
336
  cacheRead: cacheReadTokens,
102
337
  cacheWrite: void 0
103
338
  },
@@ -317,6 +552,7 @@ var CohereChatLanguageModel = class CohereChatLanguageModel {
317
552
  tool_choice: cohereToolChoice,
318
553
  ...cohereDocuments.length > 0 && { documents: cohereDocuments },
319
554
  ...resolveCohereThinking({
555
+ modelEntry: getCohereLanguageModelEntry(this.modelId),
320
556
  reasoning,
321
557
  cohereOptions,
322
558
  warnings
@@ -353,20 +589,10 @@ var CohereChatLanguageModel = class CohereChatLanguageModel {
353
589
  continue;
354
590
  }
355
591
  }
356
- for (const citation of response.message.citations ?? []) content.push({
357
- type: "source",
358
- sourceType: "document",
359
- id: this.config.generateId(),
360
- mediaType: "text/plain",
361
- title: citation.sources[0]?.document?.title || "Document",
362
- providerMetadata: { cohere: {
363
- start: citation.start,
364
- end: citation.end,
365
- text: citation.text,
366
- sources: citation.sources,
367
- ...citation.type && { citationType: citation.type }
368
- } }
369
- });
592
+ for (const citation of response.message.citations ?? []) {
593
+ const source = mapCohereCitationToSource(citation, () => this.config.generateId());
594
+ if (source != null) content.push(source);
595
+ }
370
596
  for (const toolCall of response.message.tool_calls ?? []) content.push({
371
597
  type: "tool-call",
372
598
  toolCallId: toolCall.id,
@@ -382,7 +608,7 @@ var CohereChatLanguageModel = class CohereChatLanguageModel {
382
608
  usage: convertCohereUsage(response.usage),
383
609
  request: { body: args },
384
610
  response: {
385
- id: response.generation_id ?? void 0,
611
+ id: response.id ?? response.generation_id ?? void 0,
386
612
  headers: responseHeaders,
387
613
  body: rawResponse
388
614
  },
@@ -410,6 +636,7 @@ var CohereChatLanguageModel = class CohereChatLanguageModel {
410
636
  let usage = void 0;
411
637
  let pendingToolCall = null;
412
638
  let isActiveReasoning = false;
639
+ const generateId = this.config.generateId;
413
640
  return {
414
641
  stream: response.pipeThrough(new TransformStream({
415
642
  start(controller) {
@@ -479,6 +706,15 @@ var CohereChatLanguageModel = class CohereChatLanguageModel {
479
706
  id: String(value.index)
480
707
  });
481
708
  return;
709
+ case "citation-start": {
710
+ const citations = value.delta?.message?.citations;
711
+ if (citations == null) return;
712
+ for (const citation of Array.isArray(citations) ? citations : [citations]) {
713
+ const source = mapCohereCitationToSource(citation, generateId);
714
+ if (source != null) controller.enqueue(source);
715
+ }
716
+ return;
717
+ }
482
718
  case "tool-call-start": {
483
719
  const toolId = value.delta.message.tool_calls.id;
484
720
  const toolName = value.delta.message.tool_calls.function.name;
@@ -522,7 +758,7 @@ var CohereChatLanguageModel = class CohereChatLanguageModel {
522
758
  type: "tool-call",
523
759
  toolCallId: pendingToolCall.id,
524
760
  toolName: pendingToolCall.name,
525
- input: JSON.stringify(await parseJSON({ text: pendingToolCall.arguments?.trim() || "{}" }))
761
+ input: JSON.stringify(await parseJSON({ text: pendingToolCall.arguments?.trim() || "{}" }) ?? {})
526
762
  });
527
763
  pendingToolCall.hasFinished = true;
528
764
  pendingToolCall = null;
@@ -559,9 +795,10 @@ var CohereChatLanguageModel = class CohereChatLanguageModel {
559
795
  };
560
796
  }
561
797
  };
562
- function resolveCohereThinking({ reasoning, cohereOptions, warnings }) {
798
+ function resolveCohereThinking({ modelEntry, reasoning, cohereOptions, warnings }) {
799
+ const { capabilities: { language: capabilities }, requestConfig: { language: defaults } } = modelEntry;
563
800
  if (cohereOptions.thinking) return { thinking: {
564
- type: cohereOptions.thinking.type ?? "enabled",
801
+ type: cohereOptions.thinking.type ?? defaults.thinkingType,
565
802
  token_budget: cohereOptions.thinking.tokenBudget
566
803
  } };
567
804
  if (!isCustomReasoning(reasoning)) return {};
@@ -570,24 +807,25 @@ function resolveCohereThinking({ reasoning, cohereOptions, warnings }) {
570
807
  type: "enabled",
571
808
  token_budget: mapReasoningToProviderBudget({
572
809
  reasoning,
573
- maxOutputTokens: 32768,
574
- maxReasoningBudget: 32768,
810
+ maxOutputTokens: defaults.reasoningMaxOutputTokens,
811
+ maxReasoningBudget: capabilities.reasoning.maxBudget,
575
812
  warnings
576
813
  })
577
814
  } };
578
815
  }
579
816
  const cohereUsageSchema = () => z.looseObject({
580
817
  billed_units: z.looseObject({
581
- input_tokens: z.number(),
582
- output_tokens: z.number()
818
+ input_tokens: z.number().nullish(),
819
+ output_tokens: z.number().nullish()
583
820
  }).nullish(),
584
821
  tokens: z.looseObject({
585
- input_tokens: z.number(),
586
- output_tokens: z.number()
587
- }),
822
+ input_tokens: z.number().nullish(),
823
+ output_tokens: z.number().nullish()
824
+ }).nullish(),
588
825
  cached_tokens: z.number().nullish()
589
826
  });
590
827
  const cohereChatResponseSchema = lazySchema(() => zodSchema(z.object({
828
+ id: z.string().nullish(),
591
829
  generation_id: z.string().nullish(),
592
830
  message: z.object({
593
831
  role: z.string(),
@@ -607,27 +845,17 @@ const cohereChatResponseSchema = lazySchema(() => zodSchema(z.object({
607
845
  arguments: z.string()
608
846
  })
609
847
  })).nullish(),
610
- citations: z.array(z.object({
611
- start: z.number(),
612
- end: z.number(),
613
- text: z.string(),
614
- sources: z.array(z.object({
615
- type: z.string().optional(),
616
- id: z.string().optional(),
617
- document: z.object({
618
- id: z.string().optional(),
619
- text: z.string(),
620
- title: z.string()
621
- })
622
- })),
623
- type: z.string().optional()
624
- })).nullish()
848
+ citations: z.array(cohereCitationSchema).nullish()
625
849
  }),
626
850
  finish_reason: z.string(),
627
- usage: cohereUsageSchema()
851
+ usage: cohereUsageSchema().nullish()
628
852
  })));
629
853
  const cohereChatChunkSchema = lazySchema(() => zodSchema(z.discriminatedUnion("type", [
630
- z.object({ type: z.literal("citation-start") }),
854
+ z.object({
855
+ type: z.literal("citation-start"),
856
+ index: z.number().nullish(),
857
+ delta: z.object({ message: z.object({ citations: z.union([cohereCitationSchema, z.array(cohereCitationSchema)]).nullish() }).nullish() }).nullish()
858
+ }),
631
859
  z.object({ type: z.literal("citation-end") }),
632
860
  z.object({
633
861
  type: z.literal("content-start"),
@@ -753,9 +981,10 @@ var CohereEmbeddingModel = class CohereEmbeddingModel {
753
981
  }
754
982
  constructor(modelId, config) {
755
983
  this.specificationVersion = "v4";
756
- this.maxEmbeddingsPerCall = 96;
757
- this.supportsParallelCalls = true;
758
984
  this.modelId = modelId;
985
+ const limits = getCohereEmbeddingModelEntry(modelId).capabilities.embedding ?? cohereEmbeddingModelLimits;
986
+ this.maxEmbeddingsPerCall = limits.maxEmbeddingsPerCall;
987
+ this.supportsParallelCalls = limits.supportsParallelCalls;
759
988
  this.config = config;
760
989
  }
761
990
  get provider() {
@@ -767,7 +996,8 @@ var CohereEmbeddingModel = class CohereEmbeddingModel {
767
996
  providerOptions,
768
997
  schema: cohereEmbeddingModelOptions
769
998
  });
770
- const embeddingType = embeddingOptions?.embeddingType ?? "float";
999
+ const defaults = getCohereEmbeddingModelEntry(this.modelId).requestConfig.embedding;
1000
+ const embeddingType = embeddingOptions?.embeddingType ?? defaults.embeddingType;
771
1001
  if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError({
772
1002
  provider: this.provider,
773
1003
  modelId: this.modelId,
@@ -781,7 +1011,7 @@ var CohereEmbeddingModel = class CohereEmbeddingModel {
781
1011
  model: this.modelId,
782
1012
  embedding_types: [embeddingType],
783
1013
  texts: values,
784
- input_type: embeddingOptions?.inputType ?? "search_query",
1014
+ input_type: embeddingOptions?.inputType ?? defaults.inputType,
785
1015
  truncate: embeddingOptions?.truncate,
786
1016
  output_dimension: embeddingOptions?.outputDimension ?? dimensions
787
1017
  },
@@ -876,7 +1106,7 @@ var CohereRerankingModel = class {
876
1106
  };
877
1107
  //#endregion
878
1108
  //#region src/version.ts
879
- const VERSION = "4.0.75";
1109
+ const VERSION = "4.0.77";
880
1110
  //#endregion
881
1111
  //#region src/cohere-provider.ts
882
1112
  /**