@ai-sdk/cohere 4.0.76 → 4.0.78
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 +51 -0
- package/dist/index.js +85 -44
- package/dist/index.js.map +1 -1
- package/docs/25-cohere.mdx +69 -0
- package/package.json +3 -3
- package/src/cohere-chat-language-model.ts +67 -45
- package/src/cohere-citations.ts +77 -0
- package/src/convert-cohere-usage.ts +11 -7
- package/src/reranking/cohere-reranking-api.ts +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,56 @@
|
|
|
1
1
|
# @ai-sdk/cohere
|
|
2
2
|
|
|
3
|
+
## 4.0.78
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 84e83a0: fix(cohere): stop requiring `meta` in reranking responses, which failed validation on Zod >= 4.4 when a response omitted it
|
|
8
|
+
- Updated dependencies [6400cf8]
|
|
9
|
+
- Updated dependencies [f608c05]
|
|
10
|
+
- Updated dependencies [cab9c1f]
|
|
11
|
+
- Updated dependencies [c70adf6]
|
|
12
|
+
- @ai-sdk/provider-utils@5.0.76
|
|
13
|
+
- @ai-sdk/provider@4.0.37
|
|
14
|
+
|
|
15
|
+
## 4.0.77
|
|
16
|
+
|
|
17
|
+
### Patch Changes
|
|
18
|
+
|
|
19
|
+
- 3aad18a: fix(cohere): tolerate partial citations and usage in non-streaming responses
|
|
20
|
+
|
|
21
|
+
Cohere citations and usage fields are optional in the API specification, but the
|
|
22
|
+
response schema required `start`, `end`, `text`, every source `document` with
|
|
23
|
+
`text` and `title`, and usage token counts. Responses with untitled documents
|
|
24
|
+
(documents passed without a filename), with tool-sourced citations, or without
|
|
25
|
+
token counts failed with an `AI_TypeValidationError` and discarded the whole
|
|
26
|
+
response.
|
|
27
|
+
|
|
28
|
+
These fields are now validated loosely: citation fields and source `type`/`id`
|
|
29
|
+
are nullish, `document` is a loose object with optional `id`/`text`/`title`, tool
|
|
30
|
+
sources are accepted, and `usage` plus its token counts are nullish. Document
|
|
31
|
+
citations without a title fall back to `"Document"`. Tool-only citations are
|
|
32
|
+
skipped because they have no document to point at; their data stays in the
|
|
33
|
+
response body.
|
|
34
|
+
|
|
35
|
+
`convertCohereUsage` no longer falls back to `billed_units`, which are a
|
|
36
|
+
different measure than `tokens` (e.g. 12 billed vs 507 input tokens in a single
|
|
37
|
+
response) and would go negative when cached tokens are subtracted. A response
|
|
38
|
+
without `tokens` now reports undefined token counts instead of unrelated
|
|
39
|
+
numbers. This usage conversion is shared with streaming.
|
|
40
|
+
|
|
41
|
+
- 73400b2: fix(cohere): read the response id from v2 chat responses
|
|
42
|
+
|
|
43
|
+
The non-streaming response schema read `generation_id`, which Cohere's v2 chat
|
|
44
|
+
response does not return. As a result, `generateText().response.id` was a locally
|
|
45
|
+
generated fallback instead of the provider's id, while `streamText` returned the
|
|
46
|
+
id from the `message-start` event. `doGenerate` now reads `id` and keeps
|
|
47
|
+
`generation_id` (the v1 field) only for compatibility with proxies and mocks that
|
|
48
|
+
still return it.
|
|
49
|
+
|
|
50
|
+
- 033a980: fix(cohere): emit `source` stream parts for citations
|
|
51
|
+
|
|
52
|
+
`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.
|
|
53
|
+
|
|
3
54
|
## 4.0.76
|
|
4
55
|
|
|
5
56
|
### 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({
|
|
@@ -274,14 +326,13 @@ function prepareTools({ tools, toolChoice }) {
|
|
|
274
326
|
//#region src/convert-cohere-usage.ts
|
|
275
327
|
function convertCohereUsage(usage) {
|
|
276
328
|
if (usage == null) return createNullLanguageModelUsage();
|
|
277
|
-
const
|
|
278
|
-
const
|
|
279
|
-
const outputTokens = tokens.output_tokens;
|
|
329
|
+
const inputTokens = usage.tokens?.input_tokens ?? void 0;
|
|
330
|
+
const outputTokens = usage.tokens?.output_tokens ?? void 0;
|
|
280
331
|
const cacheReadTokens = usage.cached_tokens ?? void 0;
|
|
281
332
|
return {
|
|
282
333
|
inputTokens: {
|
|
283
334
|
total: inputTokens,
|
|
284
|
-
noCache: cacheReadTokens != null ? inputTokens - cacheReadTokens : inputTokens,
|
|
335
|
+
noCache: inputTokens != null && cacheReadTokens != null ? inputTokens - cacheReadTokens : inputTokens,
|
|
285
336
|
cacheRead: cacheReadTokens,
|
|
286
337
|
cacheWrite: void 0
|
|
287
338
|
},
|
|
@@ -538,20 +589,10 @@ var CohereChatLanguageModel = class CohereChatLanguageModel {
|
|
|
538
589
|
continue;
|
|
539
590
|
}
|
|
540
591
|
}
|
|
541
|
-
for (const citation of response.message.citations ?? [])
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
mediaType: "text/plain",
|
|
546
|
-
title: citation.sources[0]?.document?.title || "Document",
|
|
547
|
-
providerMetadata: { cohere: {
|
|
548
|
-
start: citation.start,
|
|
549
|
-
end: citation.end,
|
|
550
|
-
text: citation.text,
|
|
551
|
-
sources: citation.sources,
|
|
552
|
-
...citation.type && { citationType: citation.type }
|
|
553
|
-
} }
|
|
554
|
-
});
|
|
592
|
+
for (const citation of response.message.citations ?? []) {
|
|
593
|
+
const source = mapCohereCitationToSource(citation, () => this.config.generateId());
|
|
594
|
+
if (source != null) content.push(source);
|
|
595
|
+
}
|
|
555
596
|
for (const toolCall of response.message.tool_calls ?? []) content.push({
|
|
556
597
|
type: "tool-call",
|
|
557
598
|
toolCallId: toolCall.id,
|
|
@@ -567,7 +608,7 @@ var CohereChatLanguageModel = class CohereChatLanguageModel {
|
|
|
567
608
|
usage: convertCohereUsage(response.usage),
|
|
568
609
|
request: { body: args },
|
|
569
610
|
response: {
|
|
570
|
-
id: response.generation_id ?? void 0,
|
|
611
|
+
id: response.id ?? response.generation_id ?? void 0,
|
|
571
612
|
headers: responseHeaders,
|
|
572
613
|
body: rawResponse
|
|
573
614
|
},
|
|
@@ -595,6 +636,7 @@ var CohereChatLanguageModel = class CohereChatLanguageModel {
|
|
|
595
636
|
let usage = void 0;
|
|
596
637
|
let pendingToolCall = null;
|
|
597
638
|
let isActiveReasoning = false;
|
|
639
|
+
const generateId = this.config.generateId;
|
|
598
640
|
return {
|
|
599
641
|
stream: response.pipeThrough(new TransformStream({
|
|
600
642
|
start(controller) {
|
|
@@ -664,6 +706,15 @@ var CohereChatLanguageModel = class CohereChatLanguageModel {
|
|
|
664
706
|
id: String(value.index)
|
|
665
707
|
});
|
|
666
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
|
+
}
|
|
667
718
|
case "tool-call-start": {
|
|
668
719
|
const toolId = value.delta.message.tool_calls.id;
|
|
669
720
|
const toolName = value.delta.message.tool_calls.function.name;
|
|
@@ -764,16 +815,17 @@ function resolveCohereThinking({ modelEntry, reasoning, cohereOptions, warnings
|
|
|
764
815
|
}
|
|
765
816
|
const cohereUsageSchema = () => z.looseObject({
|
|
766
817
|
billed_units: z.looseObject({
|
|
767
|
-
input_tokens: z.number(),
|
|
768
|
-
output_tokens: z.number()
|
|
818
|
+
input_tokens: z.number().nullish(),
|
|
819
|
+
output_tokens: z.number().nullish()
|
|
769
820
|
}).nullish(),
|
|
770
821
|
tokens: z.looseObject({
|
|
771
|
-
input_tokens: z.number(),
|
|
772
|
-
output_tokens: z.number()
|
|
773
|
-
}),
|
|
822
|
+
input_tokens: z.number().nullish(),
|
|
823
|
+
output_tokens: z.number().nullish()
|
|
824
|
+
}).nullish(),
|
|
774
825
|
cached_tokens: z.number().nullish()
|
|
775
826
|
});
|
|
776
827
|
const cohereChatResponseSchema = lazySchema(() => zodSchema(z.object({
|
|
828
|
+
id: z.string().nullish(),
|
|
777
829
|
generation_id: z.string().nullish(),
|
|
778
830
|
message: z.object({
|
|
779
831
|
role: z.string(),
|
|
@@ -793,27 +845,17 @@ const cohereChatResponseSchema = lazySchema(() => zodSchema(z.object({
|
|
|
793
845
|
arguments: z.string()
|
|
794
846
|
})
|
|
795
847
|
})).nullish(),
|
|
796
|
-
citations: z.array(
|
|
797
|
-
start: z.number(),
|
|
798
|
-
end: z.number(),
|
|
799
|
-
text: z.string(),
|
|
800
|
-
sources: z.array(z.object({
|
|
801
|
-
type: z.string().optional(),
|
|
802
|
-
id: z.string().optional(),
|
|
803
|
-
document: z.object({
|
|
804
|
-
id: z.string().optional(),
|
|
805
|
-
text: z.string(),
|
|
806
|
-
title: z.string()
|
|
807
|
-
})
|
|
808
|
-
})),
|
|
809
|
-
type: z.string().optional()
|
|
810
|
-
})).nullish()
|
|
848
|
+
citations: z.array(cohereCitationSchema).nullish()
|
|
811
849
|
}),
|
|
812
850
|
finish_reason: z.string(),
|
|
813
|
-
usage: cohereUsageSchema()
|
|
851
|
+
usage: cohereUsageSchema().nullish()
|
|
814
852
|
})));
|
|
815
853
|
const cohereChatChunkSchema = lazySchema(() => zodSchema(z.discriminatedUnion("type", [
|
|
816
|
-
z.object({
|
|
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
|
+
}),
|
|
817
859
|
z.object({ type: z.literal("citation-end") }),
|
|
818
860
|
z.object({
|
|
819
861
|
type: z.literal("content-start"),
|
|
@@ -1000,8 +1042,7 @@ const cohereRerankingResponseSchema = lazySchema(() => zodSchema(z.object({
|
|
|
1000
1042
|
results: z.array(z.object({
|
|
1001
1043
|
index: z.number(),
|
|
1002
1044
|
relevance_score: z.number()
|
|
1003
|
-
}))
|
|
1004
|
-
meta: z.any()
|
|
1045
|
+
}))
|
|
1005
1046
|
})));
|
|
1006
1047
|
//#endregion
|
|
1007
1048
|
//#region src/reranking/cohere-reranking-model-options.ts
|
|
@@ -1064,7 +1105,7 @@ var CohereRerankingModel = class {
|
|
|
1064
1105
|
};
|
|
1065
1106
|
//#endregion
|
|
1066
1107
|
//#region src/version.ts
|
|
1067
|
-
const VERSION = "4.0.
|
|
1108
|
+
const VERSION = "4.0.78";
|
|
1068
1109
|
//#endregion
|
|
1069
1110
|
//#region src/cohere-provider.ts
|
|
1070
1111
|
/**
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_exhaustiveCheck","_exhaustiveCheck"],"sources":["../src/cohere-chat-language-model-options.ts","../src/cohere-error.ts","../src/cohere-model-catalog.ts","../src/cohere-prepare-tools.ts","../src/convert-cohere-usage.ts","../src/convert-to-cohere-chat-prompt.ts","../src/map-cohere-finish-reason.ts","../src/cohere-chat-language-model.ts","../src/cohere-embedding-model-options.ts","../src/cohere-embedding-model.ts","../src/reranking/cohere-reranking-api.ts","../src/reranking/cohere-reranking-model-options.ts","../src/reranking/cohere-reranking-model.ts","../src/version.ts","../src/cohere-provider.ts"],"sourcesContent":["import {\n lazySchema,\n zodSchema,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// https://docs.cohere.com/docs/models\nexport type CohereChatModelId =\n | 'command-a-03-2025'\n | 'command-a-reasoning-08-2025'\n | 'command-a-vision-07-2025'\n | 'command-r7b-12-2024'\n | 'command-r-plus-04-2024'\n | 'command-r-plus'\n | 'command-r-08-2024'\n | 'command-r-03-2024'\n | 'command-r'\n | 'command'\n | 'command-nightly'\n | 'command-light'\n | 'command-light-nightly'\n | (string & {});\n\nexport const cohereLanguageModelChatOptions = lazySchema(() =>\n zodSchema(\n z.object({\n /**\n * Configuration for reasoning features (optional)\n *\n * Can be set to an object with the two properties `type` and `tokenBudget`. `type` can be set to `'enabled'` or `'disabled'` (defaults to `'enabled'`).\n * `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\n *\n * @see https://docs.cohere.com/reference/chat#request.body.thinking\n */\n thinking: z\n .object({\n type: z.enum(['enabled', 'disabled']).optional(),\n tokenBudget: z.number().optional(),\n })\n .optional(),\n }),\n ),\n);\n\nexport type CohereLanguageModelChatOptions = InferSchema<\n typeof cohereLanguageModelChatOptions\n>;\n\nexport const cohereImagePartProviderOptions = lazySchema(() =>\n zodSchema(\n z.object({\n /**\n * Image fidelity level passed through as `image_url.detail` on the Cohere chat API.\n *\n * @see https://docs.cohere.com/docs/image-inputs\n */\n detail: z.enum(['auto', 'low', 'high']).optional(),\n }),\n ),\n);\n\nexport type CohereImagePartProviderOptions = InferSchema<\n typeof cohereImagePartProviderOptions\n>;\n","import {\n lazySchema,\n zodSchema,\n type InferSchema,\n createJsonErrorResponseHandler,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nconst cohereErrorDataSchema = lazySchema(() =>\n zodSchema(\n z.object({\n message: z.string(),\n }),\n ),\n);\n\nexport type CohereErrorData = InferSchema<typeof cohereErrorDataSchema>;\n\nexport const cohereFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: cohereErrorDataSchema,\n errorToMessage: data => data.message,\n});\n","import type {\n ModelCapabilities,\n ModelCapability,\n ModelEntry,\n ProviderOptionDefinition,\n ProviderOptionDefinitions,\n} from '@ai-sdk/provider';\nimport type { CohereLanguageModelChatOptions } from './cohere-chat-language-model-options';\nimport type { CohereEmbeddingModelOptions } from './cohere-embedding-model-options';\nimport type { CohereRerankingModelOptions } from './reranking/cohere-reranking-model-options';\n\nexport const cohereProviderOptions = {\n language: {\n thinking: {\n description: 'Enable or disable reasoning and set its token budget.',\n },\n } satisfies Record<\n keyof CohereLanguageModelChatOptions,\n ProviderOptionDefinition\n >,\n embedding: {\n embeddingType: { description: 'Embedding format returned by the API.' },\n inputType: { description: 'Intended use of the input embeddings.' },\n truncate: {\n description: 'How to truncate inputs exceeding the token limit.',\n },\n outputDimension: { description: 'Output embedding dimensions.' },\n } satisfies Record<\n keyof CohereEmbeddingModelOptions,\n ProviderOptionDefinition\n >,\n reranking: {\n maxTokensPerDoc: { description: 'Token limit for each document.' },\n priority: { description: 'Request processing priority.' },\n } satisfies Record<\n keyof CohereRerankingModelOptions,\n ProviderOptionDefinition\n >,\n} as const satisfies ProviderOptionDefinitions;\n\ntype LanguageCapabilities = NonNullable<ModelCapabilities['language']> & {\n reasoning: NonNullable<ModelCapabilities['language']>['reasoning'] & {\n maxBudget: number;\n };\n};\n\ntype LanguageRequestConfig = {\n thinkingType: 'enabled';\n reasoningMaxOutputTokens: number;\n};\n\ntype EmbeddingType = NonNullable<CohereEmbeddingModelOptions['embeddingType']>;\n\ntype EmbeddingCapabilities = NonNullable<ModelCapabilities['embedding']> & {\n dimensions: readonly number[];\n embeddingTypes: readonly EmbeddingType[];\n maxEmbeddingsPerCall: number;\n supportsParallelCalls: boolean;\n};\n\ntype EmbeddingRequestConfig = {\n embeddingType: EmbeddingType;\n inputType: NonNullable<CohereEmbeddingModelOptions['inputType']>;\n};\n\nexport type CohereLanguageModelEntry = {\n capabilities: { language: LanguageCapabilities };\n providerOptions: {\n language: Record<keyof CohereLanguageModelChatOptions, ModelCapability>;\n };\n requestConfig: { language: LanguageRequestConfig };\n};\n\ntype CohereEmbeddingModelEntry = {\n // Unknown model IDs do not invent a default dimension.\n capabilities: { embedding?: EmbeddingCapabilities };\n providerOptions: {\n embedding: Record<keyof CohereEmbeddingModelOptions, ModelCapability>;\n };\n requestConfig: { embedding: EmbeddingRequestConfig };\n};\n\ntype CohereRerankingModelEntry = {\n capabilities: { reranking: NonNullable<ModelCapabilities['reranking']> };\n providerOptions: {\n reranking: Record<keyof CohereRerankingModelOptions, ModelCapability>;\n };\n};\n\ntype CohereModelEntry = ModelEntry<{\n language?: LanguageRequestConfig;\n embedding?: EmbeddingRequestConfig;\n}> & {\n capabilities: ModelCapabilities & {\n language?: LanguageCapabilities;\n embedding?: EmbeddingCapabilities;\n };\n providerOptions?: {\n [Section in keyof typeof cohereProviderOptions]?: Record<\n keyof (typeof cohereProviderOptions)[Section],\n ModelCapability\n >;\n };\n};\n\ntype LanguageDefinition = {\n image: boolean;\n objectGeneration: boolean;\n tools: boolean;\n reasoning?: boolean;\n};\n\nconst standard = { image: false, objectGeneration: true, tools: true };\nconst legacy = { image: false, objectGeneration: false, tools: false };\n\n// Preserve the provider page's model set and per-model exceptions.\nconst languageDefinitions: Record<string, LanguageDefinition> = {\n 'command-a-03-2025': standard,\n 'command-a-reasoning-08-2025': { ...standard, reasoning: true },\n 'command-a-vision-07-2025': { ...standard, image: true },\n 'command-r7b-12-2024': standard,\n 'command-r-plus-04-2024': standard,\n 'command-r-plus': standard,\n 'command-r-08-2024': standard,\n 'command-r-03-2024': standard,\n 'command-r': standard,\n command: legacy,\n 'command-nightly': legacy,\n 'command-light': legacy,\n 'command-light-nightly': legacy,\n};\n\nfunction createLanguageModelEntry(\n definition?: LanguageDefinition,\n): CohereLanguageModelEntry {\n const reasoningSupport = definition?.reasoning ?? 'unknown';\n return {\n capabilities: {\n language: {\n inputs: { image: definition?.image ?? 'unknown', audio: false },\n objectGeneration: definition?.objectGeneration ?? 'unknown',\n tools: {\n usage: definition?.tools ?? 'unknown',\n streaming: definition?.tools ?? 'unknown',\n },\n reasoning: { support: reasoningSupport, maxBudget: 32768 },\n sampling: { temperature: 'unknown', topP: 'unknown', logprobs: false },\n },\n },\n providerOptions: {\n language: declareProviderOptions(\n cohereProviderOptions.language,\n definition != null ? true : 'unknown',\n { thinking: reasoningSupport },\n ),\n },\n requestConfig: {\n language: { thinkingType: 'enabled', reasoningMaxOutputTokens: 32768 },\n },\n };\n}\n\n// These SDK limits apply to custom model IDs as well as catalog models.\nexport const cohereEmbeddingModelLimits = {\n maxEmbeddingsPerCall: 96,\n supportsParallelCalls: true,\n} as const;\n\nconst embeddingRequestConfig: EmbeddingRequestConfig = {\n embeddingType: 'float',\n inputType: 'search_query',\n};\n\nconst embeddingTypes: readonly EmbeddingType[] = [\n 'float',\n 'int8',\n 'uint8',\n 'binary',\n 'ubinary',\n];\n\nfunction createEmbeddingModelEntry(\n defaultDimensions: number,\n dimensions: readonly number[],\n formats: readonly EmbeddingType[] = embeddingTypes,\n) {\n const customDimensions = dimensions.length > 1;\n return {\n capabilities: {\n embedding: {\n defaultDimensions,\n customDimensions,\n dimensions,\n embeddingTypes: formats,\n ...cohereEmbeddingModelLimits,\n },\n },\n providerOptions: {\n embedding: declareProviderOptions(cohereProviderOptions.embedding, true, {\n outputDimension: customDimensions,\n embeddingType:\n formats.length === 1\n ? { condition: \"Only embeddingType: 'float' is supported.\" }\n : true,\n }),\n },\n requestConfig: { embedding: embeddingRequestConfig },\n };\n}\n\nfunction createRerankingModelEntry(\n declared: boolean,\n): CohereRerankingModelEntry {\n const support = declared ? true : 'unknown';\n return {\n capabilities: {\n reranking: {\n documents: {\n text: support,\n object: declared\n ? {\n condition:\n 'Objects are converted to JSON strings with a compatibility warning.',\n }\n : 'unknown',\n },\n topN: support,\n },\n },\n providerOptions: {\n reranking: declareProviderOptions(\n cohereProviderOptions.reranking,\n support,\n {},\n ),\n },\n };\n}\n\nexport const cohereModelCatalog: Readonly<Record<string, CohereModelEntry>> = {\n ...Object.fromEntries(\n Object.entries(languageDefinitions).map(([modelId, definition]) => [\n modelId,\n createLanguageModelEntry(definition),\n ]),\n ),\n 'embed-v5.0-pro': createEmbeddingModelEntry(\n 2048,\n [256, 512, 768, 1024, 1536, 2048],\n ),\n 'embed-v5.0-fast': createEmbeddingModelEntry(\n 2048,\n [256, 512, 768, 1024, 1536, 2048],\n ),\n 'embed-v4.0': createEmbeddingModelEntry(1536, [256, 512, 1024, 1536]),\n 'embed-english-v3.0': createEmbeddingModelEntry(1024, [1024]),\n 'embed-multilingual-v3.0': createEmbeddingModelEntry(1024, [1024]),\n 'embed-english-light-v3.0': createEmbeddingModelEntry(384, [384]),\n 'embed-multilingual-light-v3.0': createEmbeddingModelEntry(384, [384]),\n 'embed-english-v2.0': createEmbeddingModelEntry(4096, [4096], ['float']),\n 'embed-english-light-v2.0': createEmbeddingModelEntry(\n 1024,\n [1024],\n ['float'],\n ),\n 'embed-multilingual-v2.0': createEmbeddingModelEntry(768, [768], ['float']),\n 'rerank-v4.0-pro': createRerankingModelEntry(true),\n 'rerank-v4.0-fast': createRerankingModelEntry(true),\n 'rerank-v3.5': createRerankingModelEntry(true),\n 'rerank-english-v3.0': createRerankingModelEntry(true),\n 'rerank-multilingual-v3.0': createRerankingModelEntry(true),\n};\n\nfunction findModelEntry(modelId: string) {\n return Object.prototype.hasOwnProperty.call(cohereModelCatalog, modelId)\n ? cohereModelCatalog[modelId]\n : undefined;\n}\n\nexport function getCohereLanguageModelEntry(\n modelId: string,\n): CohereLanguageModelEntry {\n const entry = findModelEntry(modelId);\n return entry?.capabilities.language != null &&\n entry.providerOptions?.language != null &&\n entry.requestConfig?.language != null\n ? {\n capabilities: { language: entry.capabilities.language },\n providerOptions: { language: entry.providerOptions.language },\n requestConfig: { language: entry.requestConfig.language },\n }\n : createLanguageModelEntry();\n}\n\nexport function getCohereEmbeddingModelEntry(\n modelId: string,\n): CohereEmbeddingModelEntry {\n const entry = findModelEntry(modelId);\n return entry?.capabilities.embedding != null &&\n entry.providerOptions?.embedding != null &&\n entry.requestConfig?.embedding != null\n ? {\n capabilities: { embedding: entry.capabilities.embedding },\n providerOptions: { embedding: entry.providerOptions.embedding },\n requestConfig: { embedding: entry.requestConfig.embedding },\n }\n : {\n capabilities: {},\n providerOptions: {\n embedding: declareProviderOptions(\n cohereProviderOptions.embedding,\n 'unknown',\n {},\n ),\n },\n requestConfig: { embedding: embeddingRequestConfig },\n };\n}\n\nexport function getCohereRerankingModelEntry(\n modelId: string,\n): CohereRerankingModelEntry {\n const entry = findModelEntry(modelId);\n return entry?.capabilities.reranking != null &&\n entry.providerOptions?.reranking != null\n ? {\n capabilities: { reranking: entry.capabilities.reranking },\n providerOptions: { reranking: entry.providerOptions.reranking },\n }\n : createRerankingModelEntry(false);\n}\n\nfunction declareProviderOptions<Option extends string>(\n definitions: Readonly<Record<Option, ProviderOptionDefinition>>,\n support: ModelCapability,\n exceptions: Partial<Record<Option, ModelCapability>>,\n): Record<Option, ModelCapability> {\n return Object.fromEntries(\n (Object.keys(definitions) as Option[]).map(option => [\n option,\n exceptions[option] ?? support,\n ]),\n ) as Record<Option, ModelCapability>;\n}\n","import {\n UnsupportedFunctionalityError,\n type LanguageModelV4CallOptions,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nimport type { CohereToolChoice } from './cohere-chat-prompt';\n\nexport function prepareTools({\n tools,\n toolChoice,\n}: {\n tools: LanguageModelV4CallOptions['tools'];\n toolChoice?: LanguageModelV4CallOptions['toolChoice'];\n}): {\n tools:\n | Array<{\n type: 'function';\n function: {\n name: string | undefined;\n description: string | undefined;\n parameters: unknown;\n };\n }>\n | undefined;\n toolChoice: CohereToolChoice;\n toolWarnings: SharedV4Warning[];\n} {\n // when the tools array is empty, change it to undefined to prevent errors:\n tools = tools?.length ? tools : undefined;\n\n const toolWarnings: SharedV4Warning[] = [];\n\n if (tools == null) {\n return { tools: undefined, toolChoice: undefined, toolWarnings };\n }\n\n const cohereTools: Array<{\n type: 'function';\n function: {\n name: string;\n description: string | undefined;\n parameters: unknown;\n };\n }> = [];\n\n for (const tool of tools) {\n if (tool.type === 'provider') {\n toolWarnings.push({\n type: 'unsupported',\n feature: `provider-defined tool ${tool.id}`,\n });\n } else {\n cohereTools.push({\n type: 'function',\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n });\n }\n }\n\n if (toolChoice == null) {\n return { tools: cohereTools, toolChoice: undefined, toolWarnings };\n }\n\n const type = toolChoice.type;\n\n switch (type) {\n case 'auto':\n return { tools: cohereTools, toolChoice: undefined, toolWarnings };\n\n case 'none':\n return { tools: cohereTools, toolChoice: 'NONE', toolWarnings };\n\n case 'required':\n return { tools: cohereTools, toolChoice: 'REQUIRED', toolWarnings };\n\n case 'tool':\n return {\n tools: cohereTools.filter(\n tool => tool.function.name === toolChoice.toolName,\n ),\n toolChoice: 'REQUIRED',\n toolWarnings,\n };\n\n default: {\n const _exhaustiveCheck: never = type;\n throw new UnsupportedFunctionalityError({\n functionality: `tool choice type: ${_exhaustiveCheck}`,\n });\n }\n }\n}\n","import type { LanguageModelV4Usage } from '@ai-sdk/provider';\nimport { createNullLanguageModelUsage } from '@ai-sdk/provider-utils';\n\nexport type CohereUsageTokens = {\n input_tokens: number;\n output_tokens: number;\n};\n\nexport type CohereUsage = {\n billed_units?: CohereUsageTokens | null;\n tokens: CohereUsageTokens;\n cached_tokens?: number | null;\n};\n\nexport function convertCohereUsage(\n usage: CohereUsage | undefined | null,\n): LanguageModelV4Usage {\n if (usage == null) {\n return createNullLanguageModelUsage();\n }\n\n const tokens = usage.tokens;\n const inputTokens = tokens.input_tokens;\n const outputTokens = tokens.output_tokens;\n const cacheReadTokens = usage.cached_tokens ?? undefined;\n\n return {\n inputTokens: {\n total: inputTokens,\n noCache:\n cacheReadTokens != null ? inputTokens - cacheReadTokens : inputTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: outputTokens,\n text: outputTokens,\n reasoning: undefined,\n },\n raw: usage,\n };\n}\n","import {\n UnsupportedFunctionalityError,\n type LanguageModelV4FilePart,\n type LanguageModelV4Prompt,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nimport {\n secureJsonParse,\n stringifyWithBigIntAndCycles,\n convertBase64ToUint8Array,\n convertToBase64,\n getTopLevelMediaType,\n parseProviderOptions,\n resolveFullMediaType,\n} from '@ai-sdk/provider-utils';\nimport { cohereImagePartProviderOptions } from './cohere-chat-language-model-options';\nimport type {\n CohereAssistantMessage,\n CohereChatPrompt,\n CohereUserMessageContent,\n} from './cohere-chat-prompt';\n\nfunction serializeCohereToolCallArguments(input: unknown): string {\n if (typeof input === 'string') {\n try {\n secureJsonParse(input);\n return input;\n } catch {\n return JSON.stringify(input);\n }\n }\n return stringifyWithBigIntAndCycles(input);\n}\n\nexport async function convertToCohereChatPrompt(\n prompt: LanguageModelV4Prompt,\n): Promise<{\n messages: CohereChatPrompt;\n documents: Array<{\n data: { text: string; title?: string };\n }>;\n warnings: SharedV4Warning[];\n}> {\n const messages: CohereChatPrompt = [];\n const documents: Array<{ data: { text: string; title?: string } }> = [];\n const warnings: SharedV4Warning[] = [];\n\n for (const { role, content } of prompt) {\n switch (role) {\n case 'system': {\n messages.push({ role: 'system', content });\n break;\n }\n\n case 'user': {\n const userContentParts: Array<CohereUserMessageContent> = [];\n let hasImage = false;\n\n for (const part of content) {\n switch (part.type) {\n case 'text': {\n if (part.text.length > 0) {\n userContentParts.push({ type: 'text', text: part.text });\n }\n break;\n }\n case 'file': {\n if (getTopLevelMediaType(part.mediaType) === 'image') {\n hasImage = true;\n const url = buildImageUrl({ part });\n const cohereOptions =\n (await parseProviderOptions({\n provider: 'cohere',\n providerOptions: part.providerOptions,\n schema: cohereImagePartProviderOptions,\n })) ?? {};\n\n userContentParts.push({\n type: 'image_url',\n image_url: {\n url,\n ...(cohereOptions.detail\n ? { detail: cohereOptions.detail }\n : {}),\n },\n });\n break;\n }\n\n let textContent: string;\n switch (part.data.type) {\n case 'reference': {\n throw new UnsupportedFunctionalityError({\n functionality: 'file parts with provider references',\n });\n }\n case 'url': {\n throw new UnsupportedFunctionalityError({\n functionality: 'File URL data',\n message:\n 'URLs should be downloaded by the AI SDK and not reach this point. This indicates a configuration issue.',\n });\n }\n case 'text': {\n textContent = part.data.text;\n break;\n }\n case 'data': {\n textContent = new TextDecoder().decode(\n typeof part.data.data === 'string'\n ? convertBase64ToUint8Array(part.data.data)\n : part.data.data,\n );\n break;\n }\n }\n\n documents.push({\n data: {\n text: textContent,\n title: part.filename,\n },\n });\n break;\n }\n }\n }\n\n if (hasImage) {\n messages.push({ role: 'user', content: userContentParts });\n } else {\n messages.push({\n role: 'user',\n content: userContentParts\n .map(p => (p.type === 'text' ? p.text : ''))\n .join(''),\n });\n }\n break;\n }\n\n case 'assistant': {\n let text = '';\n const toolCalls: CohereAssistantMessage['tool_calls'] = [];\n\n for (const part of content) {\n switch (part.type) {\n case 'text': {\n text += part.text;\n break;\n }\n case 'tool-call': {\n toolCalls.push({\n id: part.toolCallId,\n type: 'function' as const,\n function: {\n name: part.toolName,\n arguments: serializeCohereToolCallArguments(part.input),\n },\n });\n break;\n }\n }\n }\n\n messages.push({\n role: 'assistant',\n content: toolCalls.length > 0 ? undefined : text,\n tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\n tool_plan: undefined,\n });\n\n break;\n }\n case 'tool': {\n messages.push(\n ...content\n .filter(toolResult => toolResult.type !== 'tool-approval-response')\n .map(toolResult => {\n const output = toolResult.output;\n\n let contentValue: string;\n switch (output.type) {\n case 'text':\n case 'error-text':\n contentValue = output.value;\n break;\n case 'execution-denied':\n contentValue = output.reason ?? 'Tool call execution denied.';\n break;\n case 'content':\n case 'json':\n case 'error-json':\n contentValue = stringifyWithBigIntAndCycles(output.value);\n break;\n }\n\n return {\n role: 'tool' as const,\n content: contentValue,\n tool_call_id: toolResult.toolCallId,\n };\n }),\n );\n\n break;\n }\n default: {\n const _exhaustiveCheck: never = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n\n return { messages, documents, warnings };\n}\n\nfunction buildImageUrl({ part }: { part: LanguageModelV4FilePart }): string {\n switch (part.data.type) {\n case 'url': {\n return part.data.url.toString();\n }\n case 'data': {\n return `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}`;\n }\n case 'reference': {\n throw new UnsupportedFunctionalityError({\n functionality: 'image file parts with provider references',\n });\n }\n case 'text': {\n throw new UnsupportedFunctionalityError({\n functionality: 'image file parts with text data',\n });\n }\n }\n}\n","import type { LanguageModelV4FinishReason } from '@ai-sdk/provider';\n\nexport function mapCohereFinishReason(\n finishReason: string | null | undefined,\n): LanguageModelV4FinishReason['unified'] {\n switch (finishReason) {\n case 'COMPLETE':\n case 'STOP_SEQUENCE':\n return 'stop';\n\n case 'MAX_TOKENS':\n return 'length';\n\n case 'ERROR':\n return 'error';\n\n case 'TOOL_CALL':\n return 'tool-calls';\n\n default:\n return 'other';\n }\n}\n","import type {\n LanguageModelV4,\n LanguageModelV4CallOptions,\n LanguageModelV4Content,\n LanguageModelV4FinishReason,\n LanguageModelV4GenerateResult,\n LanguageModelV4StreamPart,\n LanguageModelV4StreamResult,\n SharedV4Warning,\n} from '@ai-sdk/provider';\nimport {\n resolve,\n type Resolvable,\n lazySchema,\n zodSchema,\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n isCustomReasoning,\n mapReasoningToProviderBudget,\n parseProviderOptions,\n parseJSON,\n postJsonToApi,\n serializeModelOptions,\n WORKFLOW_SERIALIZE,\n WORKFLOW_DESERIALIZE,\n type InferSchema,\n type FetchFunction,\n type ParseResult,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport {\n cohereLanguageModelChatOptions,\n type CohereChatModelId,\n} from './cohere-chat-language-model-options';\nimport { cohereFailedResponseHandler } from './cohere-error';\nimport {\n getCohereLanguageModelEntry,\n type CohereLanguageModelEntry,\n} from './cohere-model-catalog';\nimport { prepareTools } from './cohere-prepare-tools';\nimport { convertCohereUsage, type CohereUsage } from './convert-cohere-usage';\nimport { convertToCohereChatPrompt } from './convert-to-cohere-chat-prompt';\nimport { mapCohereFinishReason } from './map-cohere-finish-reason';\n\ntype CohereChatConfig = {\n provider: string;\n baseURL: string;\n headers?: Resolvable<Record<string, string | undefined>>;\n fetch?: FetchFunction;\n generateId: () => string;\n};\n\nexport class CohereChatLanguageModel implements LanguageModelV4 {\n readonly specificationVersion = 'v4';\n\n readonly modelId: CohereChatModelId;\n\n readonly supportedUrls: Record<string, RegExp[]> = {\n 'image/*': [/^https?:\\/\\/.*$/],\n };\n\n private readonly config: CohereChatConfig;\n\n static [WORKFLOW_SERIALIZE](model: CohereChatLanguageModel) {\n return serializeModelOptions({\n modelId: model.modelId,\n config: model.config,\n });\n }\n\n static [WORKFLOW_DESERIALIZE](options: {\n modelId: CohereChatModelId;\n config: CohereChatConfig;\n }) {\n return new CohereChatLanguageModel(options.modelId, options.config);\n }\n\n constructor(modelId: CohereChatModelId, config: CohereChatConfig) {\n this.modelId = modelId;\n this.config = config;\n }\n\n get provider(): string {\n return this.config.provider;\n }\n\n private async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n reasoning,\n tools,\n toolChoice,\n providerOptions,\n }: LanguageModelV4CallOptions) {\n const warnings: SharedV4Warning[] = [];\n\n const cohereOptions =\n (await parseProviderOptions({\n provider: 'cohere',\n providerOptions,\n schema: cohereLanguageModelChatOptions,\n })) ?? {};\n\n const {\n messages: chatPrompt,\n documents: cohereDocuments,\n warnings: promptWarnings,\n } = await convertToCohereChatPrompt(prompt);\n\n const {\n tools: cohereTools,\n toolChoice: cohereToolChoice,\n toolWarnings,\n } = prepareTools({ tools, toolChoice });\n\n warnings.push(...toolWarnings, ...promptWarnings);\n\n return {\n args: {\n // model id:\n model: this.modelId,\n\n // standardized settings:\n frequency_penalty: frequencyPenalty,\n presence_penalty: presencePenalty,\n max_tokens: maxOutputTokens,\n temperature,\n p: topP,\n k: topK,\n seed,\n stop_sequences: stopSequences,\n\n // response format:\n response_format:\n responseFormat?.type === 'json'\n ? { type: 'json_object', json_schema: responseFormat.schema }\n : undefined,\n\n // messages:\n messages: chatPrompt,\n\n // tools:\n tools: cohereTools,\n tool_choice: cohereToolChoice,\n\n // documents for RAG:\n ...(cohereDocuments.length > 0 && { documents: cohereDocuments }),\n\n // reasoning:\n ...resolveCohereThinking({\n modelEntry: getCohereLanguageModelEntry(this.modelId),\n reasoning,\n cohereOptions,\n warnings,\n }),\n },\n warnings,\n };\n }\n\n async doGenerate(\n options: LanguageModelV4CallOptions,\n ): Promise<LanguageModelV4GenerateResult> {\n const { args, warnings } = await this.getArgs(options);\n\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse,\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat`,\n headers: combineHeaders(\n await resolve(this.config.headers),\n options.headers,\n ),\n body: args,\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n cohereChatResponseSchema,\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n const content: Array<LanguageModelV4Content> = [];\n\n for (const item of response.message.content ?? []) {\n if (item.type === 'text' && item.text.length > 0) {\n content.push({ type: 'text', text: item.text });\n continue;\n }\n\n if (item.type === 'thinking' && item.thinking.length > 0) {\n content.push({ type: 'reasoning', text: item.thinking });\n continue;\n }\n }\n\n // citations:\n for (const citation of response.message.citations ?? []) {\n content.push({\n type: 'source',\n sourceType: 'document',\n id: this.config.generateId(),\n mediaType: 'text/plain',\n title: citation.sources[0]?.document?.title || 'Document',\n providerMetadata: {\n cohere: {\n start: citation.start,\n end: citation.end,\n text: citation.text,\n sources: citation.sources,\n ...(citation.type && { citationType: citation.type }),\n },\n },\n });\n }\n\n // tool calls:\n for (const toolCall of response.message.tool_calls ?? []) {\n content.push({\n type: 'tool-call' as const,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n // Cohere sometimes returns `null` for tool call arguments for tools\n // defined as having no arguments.\n input: toolCall.function.arguments.replace(/^null$/, '{}'),\n });\n }\n\n return {\n content,\n finishReason: {\n unified: mapCohereFinishReason(response.finish_reason),\n raw: response.finish_reason ?? undefined,\n },\n usage: convertCohereUsage(response.usage),\n request: { body: args },\n response: {\n // TODO timestamp, model id\n id: response.generation_id ?? undefined,\n headers: responseHeaders,\n body: rawResponse,\n },\n warnings,\n };\n }\n\n async doStream(\n options: LanguageModelV4CallOptions,\n ): Promise<LanguageModelV4StreamResult> {\n const { args, warnings } = await this.getArgs(options);\n\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat`,\n headers: combineHeaders(\n await resolve(this.config.headers),\n options.headers,\n ),\n body: { ...args, stream: true },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n cohereChatChunkSchema,\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n // A clean end without the provider's completion signal is interrupted.\n let finishReason: LanguageModelV4FinishReason = {\n unified: 'interrupted',\n raw: undefined,\n };\n let usage: CohereUsage | undefined = undefined;\n\n let pendingToolCall: {\n id: string;\n name: string;\n arguments: string;\n hasFinished: boolean;\n } | null = null;\n\n let isActiveReasoning = false;\n\n return {\n stream: response.pipeThrough(\n new TransformStream<\n ParseResult<InferSchema<typeof cohereChatChunkSchema>>,\n LanguageModelV4StreamPart\n >({\n start(controller) {\n controller.enqueue({ type: 'stream-start', warnings });\n },\n\n async transform(chunk, controller) {\n if (options.includeRawChunks) {\n controller.enqueue({ type: 'raw', rawValue: chunk.rawValue });\n }\n\n // handle failed chunk parsing / validation:\n if (!chunk.success) {\n finishReason = { unified: 'error', raw: undefined };\n controller.enqueue({ type: 'error', error: chunk.error });\n return;\n }\n\n const value = chunk.value;\n const type = value.type;\n\n switch (type) {\n case 'content-start': {\n if (value.delta.message.content.type === 'thinking') {\n controller.enqueue({\n type: 'reasoning-start',\n id: String(value.index),\n });\n isActiveReasoning = true;\n return;\n }\n\n controller.enqueue({\n type: 'text-start',\n id: String(value.index),\n });\n return;\n }\n\n case 'content-delta': {\n if ('thinking' in value.delta.message.content) {\n controller.enqueue({\n type: 'reasoning-delta',\n id: String(value.index),\n delta: value.delta.message.content.thinking,\n });\n return;\n }\n\n controller.enqueue({\n type: 'text-delta',\n id: String(value.index),\n delta: value.delta.message.content.text,\n });\n return;\n }\n\n case 'content-end': {\n if (isActiveReasoning) {\n controller.enqueue({\n type: 'reasoning-end',\n id: String(value.index),\n });\n isActiveReasoning = false;\n return;\n }\n\n controller.enqueue({\n type: 'text-end',\n id: String(value.index),\n });\n\n return;\n }\n\n case 'tool-call-start': {\n const toolId = value.delta.message.tool_calls.id;\n const toolName = value.delta.message.tool_calls.function.name;\n const initialArgs =\n value.delta.message.tool_calls.function.arguments;\n\n pendingToolCall = {\n id: toolId,\n name: toolName,\n arguments: initialArgs,\n hasFinished: false,\n };\n\n controller.enqueue({\n type: 'tool-input-start',\n id: toolId,\n toolName,\n });\n\n if (initialArgs.length > 0) {\n controller.enqueue({\n type: 'tool-input-delta',\n id: toolId,\n delta: initialArgs,\n });\n }\n return;\n }\n\n case 'tool-call-delta': {\n if (pendingToolCall && !pendingToolCall.hasFinished) {\n const argsDelta =\n value.delta.message.tool_calls.function.arguments;\n pendingToolCall.arguments += argsDelta;\n\n controller.enqueue({\n type: 'tool-input-delta',\n id: pendingToolCall.id,\n delta: argsDelta,\n });\n }\n return;\n }\n\n case 'tool-call-end': {\n if (pendingToolCall && !pendingToolCall.hasFinished) {\n controller.enqueue({\n type: 'tool-input-end',\n id: pendingToolCall.id,\n });\n\n controller.enqueue({\n type: 'tool-call',\n toolCallId: pendingToolCall.id,\n toolName: pendingToolCall.name,\n input: JSON.stringify(\n (await parseJSON({\n text: pendingToolCall.arguments?.trim() || '{}',\n })) ?? {},\n ),\n });\n\n pendingToolCall.hasFinished = true;\n pendingToolCall = null;\n }\n return;\n }\n\n case 'message-start': {\n controller.enqueue({\n type: 'response-metadata',\n id: value.id ?? undefined,\n });\n return;\n }\n\n case 'message-end': {\n finishReason = {\n unified: mapCohereFinishReason(value.delta.finish_reason),\n raw: value.delta.finish_reason,\n };\n usage = value.delta.usage;\n return;\n }\n\n default: {\n }\n }\n },\n\n flush(controller) {\n controller.enqueue({\n type: 'finish',\n finishReason,\n usage: convertCohereUsage(usage),\n });\n },\n }),\n ),\n request: { body: { ...args, stream: true } },\n response: { headers: responseHeaders },\n };\n }\n}\n\nfunction resolveCohereThinking({\n modelEntry,\n reasoning,\n cohereOptions,\n warnings,\n}: {\n modelEntry: CohereLanguageModelEntry;\n reasoning: LanguageModelV4CallOptions['reasoning'];\n cohereOptions: InferSchema<typeof cohereLanguageModelChatOptions>;\n warnings: SharedV4Warning[];\n}): { thinking?: { type: string; token_budget?: number } } {\n const {\n capabilities: { language: capabilities },\n requestConfig: { language: defaults },\n } = modelEntry;\n if (cohereOptions.thinking) {\n return {\n thinking: {\n type: cohereOptions.thinking.type ?? defaults.thinkingType,\n token_budget: cohereOptions.thinking.tokenBudget,\n },\n };\n }\n\n if (!isCustomReasoning(reasoning)) {\n return {};\n }\n\n if (reasoning === 'none') {\n return { thinking: { type: 'disabled' } };\n }\n\n const tokenBudget = mapReasoningToProviderBudget({\n reasoning,\n maxOutputTokens: defaults.reasoningMaxOutputTokens,\n maxReasoningBudget: capabilities.reasoning.maxBudget,\n warnings,\n });\n\n return { thinking: { type: 'enabled', token_budget: tokenBudget } };\n}\n\n// Loose, nested objects included: the parsed value is returned as `usage.raw`.\nconst cohereUsageSchema = () =>\n z.looseObject({\n billed_units: z\n .looseObject({\n input_tokens: z.number(),\n output_tokens: z.number(),\n })\n .nullish(),\n tokens: z.looseObject({\n input_tokens: z.number(),\n output_tokens: z.number(),\n }),\n cached_tokens: z.number().nullish(),\n });\n\nconst cohereChatResponseSchema = lazySchema(() =>\n zodSchema(\n z.object({\n generation_id: z.string().nullish(),\n message: z.object({\n role: z.string(),\n content: z\n .array(\n z.union([\n z.object({\n type: z.literal('text'),\n text: z.string(),\n }),\n z.object({\n type: z.literal('thinking'),\n thinking: z.string(),\n }),\n ]),\n )\n .nullish(),\n tool_plan: z.string().nullish(),\n tool_calls: z\n .array(\n z.object({\n id: z.string(),\n type: z.literal('function'),\n function: z.object({\n name: z.string(),\n arguments: z.string(),\n }),\n }),\n )\n .nullish(),\n citations: z\n .array(\n z.object({\n start: z.number(),\n end: z.number(),\n text: z.string(),\n sources: z.array(\n z.object({\n type: z.string().optional(),\n id: z.string().optional(),\n document: z.object({\n id: z.string().optional(),\n text: z.string(),\n title: z.string(),\n }),\n }),\n ),\n type: z.string().optional(),\n }),\n )\n .nullish(),\n }),\n finish_reason: z.string(),\n usage: cohereUsageSchema(),\n }),\n ),\n);\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nconst cohereChatChunkSchema = lazySchema(() =>\n zodSchema(\n z.discriminatedUnion('type', [\n z.object({\n type: z.literal('citation-start'),\n }),\n z.object({\n type: z.literal('citation-end'),\n }),\n z.object({\n type: z.literal('content-start'),\n index: z.number(),\n delta: z.object({\n message: z.object({\n content: z.union([\n z.object({\n type: z.literal('text'),\n text: z.string(),\n }),\n z.object({\n type: z.literal('thinking'),\n thinking: z.string(),\n }),\n ]),\n }),\n }),\n }),\n z.object({\n type: z.literal('content-delta'),\n index: z.number(),\n delta: z.object({\n message: z.object({\n content: z.union([\n z.object({\n text: z.string(),\n }),\n z.object({\n thinking: z.string(),\n }),\n ]),\n }),\n }),\n }),\n z.object({\n type: z.literal('content-end'),\n index: z.number(),\n }),\n z.object({\n type: z.literal('message-start'),\n id: z.string().nullish(),\n }),\n z.object({\n type: z.literal('message-end'),\n delta: z.object({\n finish_reason: z.string(),\n usage: cohereUsageSchema(),\n }),\n }),\n // https://docs.cohere.com/v2/docs/streaming#tool-use-stream-events-for-tool-calling\n z.object({\n type: z.literal('tool-plan-delta'),\n delta: z.object({\n message: z.object({\n tool_plan: z.string(),\n }),\n }),\n }),\n z.object({\n type: z.literal('tool-call-start'),\n delta: z.object({\n message: z.object({\n tool_calls: z.object({\n id: z.string(),\n type: z.literal('function'),\n function: z.object({\n name: z.string(),\n arguments: z.string(),\n }),\n }),\n }),\n }),\n }),\n // A single tool call's `arguments` stream in chunks and must be accumulated\n // in a string and so the full tool object info can only be parsed once we see\n // `tool-call-end`.\n z.object({\n type: z.literal('tool-call-delta'),\n delta: z.object({\n message: z.object({\n tool_calls: z.object({\n function: z.object({\n arguments: z.string(),\n }),\n }),\n }),\n }),\n }),\n z.object({\n type: z.literal('tool-call-end'),\n }),\n ]),\n ),\n);\n","import {\n lazySchema,\n zodSchema,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport type CohereEmbeddingModelId =\n | 'embed-english-v3.0'\n | 'embed-multilingual-v3.0'\n | 'embed-english-light-v3.0'\n | 'embed-multilingual-light-v3.0'\n | 'embed-english-v2.0'\n | 'embed-english-light-v2.0'\n | 'embed-multilingual-v2.0'\n | (string & {});\n\nexport const cohereEmbeddingModelOptions = lazySchema(() =>\n zodSchema(\n z.object({\n /**\n * The format of the returned embedding. Defaults to `float`.\n * Non-float formats require Embed v3.0 or newer.\n * Binary formats contain packed bytes, not individual vector dimensions.\n */\n embeddingType: z\n .enum(['float', 'int8', 'uint8', 'binary', 'ubinary'])\n .optional(),\n\n /**\n * Specifies the type of input passed to the model. Default is `search_query`.\n *\n * - \"search_document\": Used for embeddings stored in a vector database for search use-cases.\n * - \"search_query\": Used for embeddings of search queries run against a vector DB to find relevant documents.\n * - \"classification\": Used for embeddings passed through a text classifier.\n * - \"clustering\": Used for embeddings run through a clustering algorithm.\n */\n inputType: z\n .enum([\n 'search_document',\n 'search_query',\n 'classification',\n 'clustering',\n ])\n .optional(),\n\n /**\n * Specifies how the API will handle inputs longer than the maximum token length.\n * Default is `END`.\n *\n * - \"NONE\": If selected, when the input exceeds the maximum input token length will return an error.\n * - \"START\": Will discard the start of the input until the remaining input is exactly the maximum input token length for the model.\n * - \"END\": Will discard the end of the input until the remaining input is exactly the maximum input token length for the model.\n */\n truncate: z.enum(['NONE', 'START', 'END']).optional(),\n\n /**\n * The number of dimensions of the output embedding.\n * Only available for `embed-v4.0` and newer models.\n *\n * Embed v4.0 supports `256`, `512`, `1024`, and `1536` (default).\n * Embed v5.0 Pro and Fast also support `768` and `2048` (default).\n */\n outputDimension: z\n .union([\n z.literal(256),\n z.literal(512),\n z.literal(768),\n z.literal(1024),\n z.literal(1536),\n z.literal(2048),\n ])\n .optional(),\n }),\n ),\n);\n\nexport type CohereEmbeddingModelOptions = InferSchema<\n typeof cohereEmbeddingModelOptions\n>;\n","import {\n TooManyEmbeddingValuesForCallError,\n type EmbeddingModelV4,\n} from '@ai-sdk/provider';\nimport {\n resolve,\n type Resolvable,\n combineHeaders,\n createJsonResponseHandler,\n parseProviderOptions,\n postJsonToApi,\n serializeModelOptions,\n WORKFLOW_SERIALIZE,\n WORKFLOW_DESERIALIZE,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport {\n cohereEmbeddingModelOptions,\n type CohereEmbeddingModelId,\n type CohereEmbeddingModelOptions,\n} from './cohere-embedding-model-options';\nimport { cohereFailedResponseHandler } from './cohere-error';\nimport {\n cohereEmbeddingModelLimits,\n getCohereEmbeddingModelEntry,\n} from './cohere-model-catalog';\n\ntype CohereEmbeddingConfig = {\n provider: string;\n baseURL: string;\n headers?: Resolvable<Record<string, string | undefined>>;\n fetch?: FetchFunction;\n};\n\nexport class CohereEmbeddingModel implements EmbeddingModelV4 {\n readonly specificationVersion = 'v4';\n readonly modelId: CohereEmbeddingModelId;\n\n readonly maxEmbeddingsPerCall: number;\n readonly supportsParallelCalls: boolean;\n\n private readonly config: CohereEmbeddingConfig;\n\n static [WORKFLOW_SERIALIZE](model: CohereEmbeddingModel) {\n return serializeModelOptions({\n modelId: model.modelId,\n config: model.config,\n });\n }\n\n static [WORKFLOW_DESERIALIZE](options: {\n modelId: CohereEmbeddingModelId;\n config: CohereEmbeddingConfig;\n }) {\n return new CohereEmbeddingModel(options.modelId, options.config);\n }\n\n constructor(modelId: CohereEmbeddingModelId, config: CohereEmbeddingConfig) {\n this.modelId = modelId;\n const limits =\n getCohereEmbeddingModelEntry(modelId).capabilities.embedding ??\n cohereEmbeddingModelLimits;\n this.maxEmbeddingsPerCall = limits.maxEmbeddingsPerCall;\n this.supportsParallelCalls = limits.supportsParallelCalls;\n this.config = config;\n }\n\n get provider(): string {\n return this.config.provider;\n }\n\n async doEmbed({\n values,\n dimensions,\n headers,\n abortSignal,\n providerOptions,\n }: Parameters<EmbeddingModelV4['doEmbed']>[0]): Promise<\n Awaited<ReturnType<EmbeddingModelV4['doEmbed']>>\n > {\n const embeddingOptions = await parseProviderOptions({\n provider: 'cohere',\n providerOptions,\n schema: cohereEmbeddingModelOptions,\n });\n const defaults = getCohereEmbeddingModelEntry(this.modelId).requestConfig\n .embedding;\n const embeddingType =\n embeddingOptions?.embeddingType ?? defaults.embeddingType;\n\n if (values.length > this.maxEmbeddingsPerCall) {\n throw new TooManyEmbeddingValuesForCallError({\n provider: this.provider,\n modelId: this.modelId,\n maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,\n values,\n });\n }\n\n const {\n responseHeaders,\n value: response,\n rawValue,\n } = await postJsonToApi({\n url: `${this.config.baseURL}/embed`,\n headers: combineHeaders(await resolve(this.config.headers), headers),\n body: {\n model: this.modelId,\n embedding_types: [embeddingType],\n texts: values,\n input_type: embeddingOptions?.inputType ?? defaults.inputType,\n truncate: embeddingOptions?.truncate,\n output_dimension: embeddingOptions?.outputDimension ?? dimensions,\n },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n cohereTextEmbeddingResponseSchema(embeddingType),\n ),\n abortSignal,\n fetch: this.config.fetch,\n });\n\n return {\n warnings: [],\n embeddings: response.embeddings[embeddingType],\n usage: { tokens: response.meta.billed_units.input_tokens },\n response: { headers: responseHeaders, body: rawValue },\n };\n }\n}\n\n// minimal version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nconst cohereTextEmbeddingResponseSchema = (\n embeddingType: NonNullable<CohereEmbeddingModelOptions['embeddingType']>,\n) =>\n z.object({\n embeddings: z.object({\n [embeddingType]: z.array(z.array(z.number())),\n }),\n meta: z.object({\n billed_units: z.object({\n input_tokens: z.number(),\n }),\n }),\n });\n","import { lazySchema, zodSchema } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// https://docs.cohere.com/v2/reference/rerank\nexport type CohereRerankingInput = {\n model: string;\n query: string;\n documents: string[];\n top_n: number | undefined;\n max_tokens_per_doc: number | undefined;\n priority: number | undefined;\n};\n\nexport const cohereRerankingResponseSchema = lazySchema(() =>\n zodSchema(\n z.object({\n id: z.string().nullish(),\n results: z.array(\n z.object({\n index: z.number(),\n relevance_score: z.number(),\n }),\n ),\n meta: z.any(),\n }),\n ),\n);\n","import {\n lazySchema,\n zodSchema,\n type FlexibleSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// https://docs.cohere.com/docs/rerank\nexport type CohereRerankingModelId =\n | 'rerank-v3.5'\n | 'rerank-english-v3.0'\n | 'rerank-multilingual-v3.0'\n | (string & {});\n\nexport type CohereRerankingModelOptions = {\n /**\n * Long documents will be automatically truncated to the specified number of tokens.\n *\n * @default 4096\n */\n maxTokensPerDoc?: number;\n\n /**\n * The priority of the request.\n *\n * @default 0\n */\n priority?: number;\n};\n\nexport const cohereRerankingModelOptionsSchema: FlexibleSchema<CohereRerankingModelOptions> =\n lazySchema(() =>\n zodSchema(\n z.object({\n maxTokensPerDoc: z.number().optional(),\n priority: z.number().optional(),\n }),\n ),\n );\n","import type { RerankingModelV4, SharedV4Warning } from '@ai-sdk/provider';\nimport {\n resolve,\n type Resolvable,\n combineHeaders,\n createJsonResponseHandler,\n parseProviderOptions,\n postJsonToApi,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { cohereFailedResponseHandler } from '../cohere-error';\nimport {\n cohereRerankingResponseSchema,\n type CohereRerankingInput,\n} from './cohere-reranking-api';\nimport {\n cohereRerankingModelOptionsSchema,\n type CohereRerankingModelId,\n} from './cohere-reranking-model-options';\ntype CohereRerankingConfig = {\n provider: string;\n baseURL: string;\n headers: Resolvable<Record<string, string | undefined>>;\n fetch?: FetchFunction;\n};\n\nexport class CohereRerankingModel implements RerankingModelV4 {\n readonly specificationVersion = 'v4';\n readonly modelId: CohereRerankingModelId;\n\n private readonly config: CohereRerankingConfig;\n\n constructor(modelId: CohereRerankingModelId, config: CohereRerankingConfig) {\n this.modelId = modelId;\n this.config = config;\n }\n\n get provider(): string {\n return this.config.provider;\n }\n\n // current implementation is based on v2 of the API: https://docs.cohere.com/v2/reference/rerank\n async doRerank({\n documents,\n headers,\n query,\n topN,\n abortSignal,\n providerOptions,\n }: Parameters<RerankingModelV4['doRerank']>[0]): Promise<\n Awaited<ReturnType<RerankingModelV4['doRerank']>>\n > {\n const rerankingOptions = await parseProviderOptions({\n provider: 'cohere',\n providerOptions,\n schema: cohereRerankingModelOptionsSchema,\n });\n\n const warnings: SharedV4Warning[] = [];\n\n if (documents.type === 'object') {\n warnings.push({\n type: 'compatibility',\n feature: 'object documents',\n details: 'Object documents are converted to strings.',\n });\n }\n\n const {\n responseHeaders,\n value: response,\n rawValue,\n } = await postJsonToApi({\n url: `${this.config.baseURL}/rerank`,\n headers: combineHeaders(await resolve(this.config.headers), headers),\n body: {\n model: this.modelId,\n query,\n documents:\n documents.type === 'text'\n ? documents.values\n : documents.values.map(value => JSON.stringify(value)),\n top_n: topN,\n max_tokens_per_doc: rerankingOptions?.maxTokensPerDoc,\n priority: rerankingOptions?.priority,\n } satisfies CohereRerankingInput,\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n cohereRerankingResponseSchema,\n ),\n abortSignal,\n fetch: this.config.fetch,\n });\n\n return {\n ranking: response.results.map(result => ({\n index: result.index,\n relevanceScore: result.relevance_score,\n })),\n warnings,\n response: {\n id: response.id ?? undefined,\n headers: responseHeaders,\n body: rawValue,\n },\n };\n }\n}\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import {\n NoSuchModelError,\n type EmbeddingModelV4,\n type LanguageModelV4,\n type RerankingModelV4,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n resolveWith,\n type Resolvable,\n generateId,\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { CohereChatLanguageModel } from './cohere-chat-language-model';\nimport type { CohereChatModelId } from './cohere-chat-language-model-options';\nimport { CohereEmbeddingModel } from './cohere-embedding-model';\nimport type { CohereRerankingModelId } from './reranking/cohere-reranking-model-options';\nimport { CohereRerankingModel } from './reranking/cohere-reranking-model';\nimport type { CohereEmbeddingModelId } from './cohere-embedding-model-options';\nimport { VERSION } from './version';\n\nexport interface CohereProvider extends ProviderV4 {\n (modelId: CohereChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation.\n */\n languageModel(modelId: CohereChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text embeddings.\n */\n embedding(modelId: CohereEmbeddingModelId): EmbeddingModelV4;\n\n /**\n * Creates a model for text embeddings.\n */\n embeddingModel(modelId: CohereEmbeddingModelId): EmbeddingModelV4;\n\n /**\n * @deprecated Use `embedding` instead.\n */\n textEmbedding(modelId: CohereEmbeddingModelId): EmbeddingModelV4;\n\n /**\n * @deprecated Use `embeddingModel` instead.\n */\n textEmbeddingModel(modelId: CohereEmbeddingModelId): EmbeddingModelV4;\n\n /**\n * Creates a model for reranking.\n */\n reranking(modelId: CohereRerankingModelId): RerankingModelV4;\n\n /**\n * Creates a model for reranking.\n */\n rerankingModel(modelId: CohereRerankingModelId): RerankingModelV4;\n}\n\nexport interface CohereProviderSettings {\n /**\n * Use a different URL prefix for API calls, e.g. to use proxy servers.\n * The default prefix is `https://api.cohere.com/v2`.\n */\n baseURL?: string;\n\n /**\n * API key that is being send using the `Authorization` header.\n * It defaults to the `COHERE_API_KEY` environment variable.\n */\n apiKey?: Resolvable<string>;\n\n /**\n * Custom headers to include in the requests.\n */\n headers?: Record<string, string>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\n * Optional function to generate a unique ID for each request.\n */\n generateId?: () => string;\n}\n\n/**\n * Create a Cohere AI provider instance.\n */\nexport function createCohere(\n options: CohereProviderSettings = {},\n): CohereProvider {\n const baseURL =\n withoutTrailingSlash(options.baseURL) ?? 'https://api.cohere.com/v2';\n\n const getHeaders = () =>\n resolveWith(options.apiKey, apiKey =>\n withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey,\n environmentVariableName: 'COHERE_API_KEY',\n description: 'Cohere',\n })}`,\n ...options.headers,\n },\n `ai-sdk-cohere/${VERSION}`,\n ),\n );\n\n const createChatModel = (modelId: CohereChatModelId) =>\n new CohereChatLanguageModel(modelId, {\n provider: 'cohere.chat',\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n generateId: options.generateId ?? generateId,\n });\n\n const createEmbeddingModel = (modelId: CohereEmbeddingModelId) =>\n new CohereEmbeddingModel(modelId, {\n provider: 'cohere.textEmbedding',\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n });\n\n const createRerankingModel = (modelId: CohereRerankingModelId) =>\n new CohereRerankingModel(modelId, {\n provider: 'cohere.reranking',\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n });\n\n const provider = function (modelId: CohereChatModelId) {\n if (new.target) {\n throw new Error(\n 'The Cohere model function cannot be called with the new keyword.',\n );\n }\n\n return createChatModel(modelId);\n };\n\n provider.specificationVersion = 'v4' as const;\n provider.languageModel = createChatModel;\n provider.embedding = createEmbeddingModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbedding = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.reranking = createRerankingModel;\n provider.rerankingModel = createRerankingModel;\n\n provider.imageModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'imageModel' });\n };\n\n return provider;\n}\n\n/**\n * Default Cohere provider instance.\n */\nexport const cohere = createCohere();\n"],"mappings":";;;;AAwBA,MAAa,iCAAiC,iBAC5C,UACE,EAAE,OAAO;;;;;;;;;AASP,UAAU,EACP,OAAO;CACN,MAAM,EAAE,KAAK,CAAC,WAAW,UAAU,CAAC,CAAC,CAAC,SAAS;CAC/C,aAAa,EAAE,OAAO,CAAC,CAAC,SAAS;AACnC,CAAC,CAAC,CACD,SAAS,EACd,CAAC,CACH,CACF;AAMA,MAAa,iCAAiC,iBAC5C,UACE,EAAE,OAAO;;;;;;AAMP,QAAQ,EAAE,KAAK;CAAC;CAAQ;CAAO;AAAM,CAAC,CAAC,CAAC,SAAS,EACnD,CAAC,CACH,CACF;;;ACpDA,MAAM,wBAAwB,iBAC5B,UACE,EAAE,OAAO,EACP,SAAS,EAAE,OAAO,EACpB,CAAC,CACH,CACF;AAIA,MAAa,8BAA8B,+BAA+B;CACxE,aAAa;CACb,iBAAgB,SAAQ,KAAK;AAC/B,CAAC;;;ACVD,MAAa,wBAAwB;CACnC,UAAU,EACR,UAAU,EACR,aAAa,wDACf,EACF;CAIA,WAAW;EACT,eAAe,EAAE,aAAa,wCAAwC;EACtE,WAAW,EAAE,aAAa,wCAAwC;EAClE,UAAU,EACR,aAAa,oDACf;EACA,iBAAiB,EAAE,aAAa,+BAA+B;CACjE;CAIA,WAAW;EACT,iBAAiB,EAAE,aAAa,iCAAiC;EACjE,UAAU,EAAE,aAAa,+BAA+B;CAC1D;AAIF;AA0EA,MAAM,WAAW;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A;IACnB,SAAS;IACT,MAAM;GACR;EACF;CACF;AACF;;;ACzGA,MAAa,UAAA;;;;;;AC8Fb,SAAgB,aACd,UAAkC,CAAC,GACnB;CAChB,MAAM,UACJ,qBAAqB,QAAQ,OAAO,KAAK;CAE3C,MAAM,mBACJ,YAAY,QAAQ,SAAQ,WAC1B,oBACE;EACE,eAAe,UAAU,WAAW;GAClC;GACA,yBAAyB;GACzB,aAAa;EACf,CAAC;EACD,GAAG,QAAQ;CACb,GACA,iBAAiB,SACnB,CACF;CAEF,MAAM,mBAAmB,YACvB,IAAI,wBAAwB,SAAS;EACnC,UAAU;EACV;EACA,SAAS;EACT,OAAO,QAAQ;EACf,YAAY,QAAQ,cAAc;CACpC,CAAC;CAEH,MAAM,wBAAwB,YAC5B,IAAI,qBAAqB,SAAS;EAChC,UAAU;EACV;EACA,SAAS;EACT,OAAO,QAAQ;CACjB,CAAC;CAEH,MAAM,wBAAwB,YAC5B,IAAI,qBAAqB,SAAS;EAChC,UAAU;EACV;EACA,SAAS;EACT,OAAO,QAAQ;CACjB,CAAC;CAEH,MAAM,WAAW,SAAU,SAA4B;EACrD,IAAI,YACF,MAAM,IAAI,MACR,kEACF;EAGF,OAAO,gBAAgB,OAAO;CAChC;CAEA,SAAS,uBAAuB;CAChC,SAAS,gBAAgB;CACzB,SAAS,YAAY;CACrB,SAAS,iBAAiB;CAC1B,SAAS,gBAAgB;CACzB,SAAS,qBAAqB;CAC9B,SAAS,YAAY;CACrB,SAAS,iBAAiB;CAE1B,SAAS,cAAc,YAAoB;EACzC,MAAM,IAAI,iBAAiB;GAAE;GAAS,WAAW;EAAa,CAAC;CACjE;CAEA,OAAO;AACT;;;;AAKA,MAAa,SAAS,aAAa"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["_exhaustiveCheck","_exhaustiveCheck"],"sources":["../src/cohere-chat-language-model-options.ts","../src/cohere-citations.ts","../src/cohere-error.ts","../src/cohere-model-catalog.ts","../src/cohere-prepare-tools.ts","../src/convert-cohere-usage.ts","../src/convert-to-cohere-chat-prompt.ts","../src/map-cohere-finish-reason.ts","../src/cohere-chat-language-model.ts","../src/cohere-embedding-model-options.ts","../src/cohere-embedding-model.ts","../src/reranking/cohere-reranking-api.ts","../src/reranking/cohere-reranking-model-options.ts","../src/reranking/cohere-reranking-model.ts","../src/version.ts","../src/cohere-provider.ts"],"sourcesContent":["import {\n lazySchema,\n zodSchema,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// https://docs.cohere.com/docs/models\nexport type CohereChatModelId =\n | 'command-a-03-2025'\n | 'command-a-reasoning-08-2025'\n | 'command-a-vision-07-2025'\n | 'command-r7b-12-2024'\n | 'command-r-plus-04-2024'\n | 'command-r-plus'\n | 'command-r-08-2024'\n | 'command-r-03-2024'\n | 'command-r'\n | 'command'\n | 'command-nightly'\n | 'command-light'\n | 'command-light-nightly'\n | (string & {});\n\nexport const cohereLanguageModelChatOptions = lazySchema(() =>\n zodSchema(\n z.object({\n /**\n * Configuration for reasoning features (optional)\n *\n * Can be set to an object with the two properties `type` and `tokenBudget`. `type` can be set to `'enabled'` or `'disabled'` (defaults to `'enabled'`).\n * `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\n *\n * @see https://docs.cohere.com/reference/chat#request.body.thinking\n */\n thinking: z\n .object({\n type: z.enum(['enabled', 'disabled']).optional(),\n tokenBudget: z.number().optional(),\n })\n .optional(),\n }),\n ),\n);\n\nexport type CohereLanguageModelChatOptions = InferSchema<\n typeof cohereLanguageModelChatOptions\n>;\n\nexport const cohereImagePartProviderOptions = lazySchema(() =>\n zodSchema(\n z.object({\n /**\n * Image fidelity level passed through as `image_url.detail` on the Cohere chat API.\n *\n * @see https://docs.cohere.com/docs/image-inputs\n */\n detail: z.enum(['auto', 'low', 'high']).optional(),\n }),\n ),\n);\n\nexport type CohereImagePartProviderOptions = InferSchema<\n typeof cohereImagePartProviderOptions\n>;\n","import type { JSONArray, LanguageModelV4Source } from '@ai-sdk/provider';\nimport { z } from 'zod/v4';\n\n/**\n * Citation payload Cohere returns for text content, in non-streaming responses\n * and in `citation-start` stream events.\n *\n * All fields are optional in the API specification, and a source can reference\n * either a document or tool output, so partial citations are validated instead\n * of discarding the whole response.\n */\nexport const cohereCitationSchema = z.object({\n start: z.number().nullish(),\n end: z.number().nullish(),\n text: z.string().nullish(),\n sources: z\n .array(\n z.object({\n type: z.string().nullish(),\n id: z.string().nullish(),\n // Documents are arbitrary objects; only the fields the provider maps\n // are typed, everything else is passed through as provider metadata.\n document: z\n .looseObject({\n id: z.string().nullish(),\n text: z.string().nullish(),\n title: z.string().nullish(),\n })\n .nullish(),\n tool_output: z.looseObject({}).nullish(),\n }),\n )\n .nullish(),\n type: z.string().nullish(),\n});\n\nexport type CohereCitation = z.infer<typeof cohereCitationSchema>;\n\n/**\n * Maps a Cohere citation to a document source.\n *\n * The first source with a document provides the title; all sources are kept in\n * `providerMetadata`. Citations that only reference tool output have no\n * document to point at and return `undefined` (their data stays in the response\n * body).\n */\nexport function mapCohereCitationToSource(\n citation: CohereCitation,\n generateId: () => string,\n): LanguageModelV4Source | undefined {\n const document = citation.sources?.find(\n source => source.document != null,\n )?.document;\n\n if (document == null) {\n return undefined;\n }\n\n return {\n type: 'source',\n sourceType: 'document',\n id: generateId(),\n mediaType: 'text/plain',\n title: document.title || 'Document',\n providerMetadata: {\n cohere: {\n ...(citation.start != null && { start: citation.start }),\n ...(citation.end != null && { end: citation.end }),\n ...(citation.text != null && { text: citation.text }),\n ...(citation.sources != null && {\n sources: citation.sources as JSONArray,\n }),\n ...(citation.type != null && { citationType: citation.type }),\n },\n },\n };\n}\n","import {\n lazySchema,\n zodSchema,\n type InferSchema,\n createJsonErrorResponseHandler,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nconst cohereErrorDataSchema = lazySchema(() =>\n zodSchema(\n z.object({\n message: z.string(),\n }),\n ),\n);\n\nexport type CohereErrorData = InferSchema<typeof cohereErrorDataSchema>;\n\nexport const cohereFailedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: cohereErrorDataSchema,\n errorToMessage: data => data.message,\n});\n","import type {\n ModelCapabilities,\n ModelCapability,\n ModelEntry,\n ProviderOptionDefinition,\n ProviderOptionDefinitions,\n} from '@ai-sdk/provider';\nimport type { CohereLanguageModelChatOptions } from './cohere-chat-language-model-options';\nimport type { CohereEmbeddingModelOptions } from './cohere-embedding-model-options';\nimport type { CohereRerankingModelOptions } from './reranking/cohere-reranking-model-options';\n\nexport const cohereProviderOptions = {\n language: {\n thinking: {\n description: 'Enable or disable reasoning and set its token budget.',\n },\n } satisfies Record<\n keyof CohereLanguageModelChatOptions,\n ProviderOptionDefinition\n >,\n embedding: {\n embeddingType: { description: 'Embedding format returned by the API.' },\n inputType: { description: 'Intended use of the input embeddings.' },\n truncate: {\n description: 'How to truncate inputs exceeding the token limit.',\n },\n outputDimension: { description: 'Output embedding dimensions.' },\n } satisfies Record<\n keyof CohereEmbeddingModelOptions,\n ProviderOptionDefinition\n >,\n reranking: {\n maxTokensPerDoc: { description: 'Token limit for each document.' },\n priority: { description: 'Request processing priority.' },\n } satisfies Record<\n keyof CohereRerankingModelOptions,\n ProviderOptionDefinition\n >,\n} as const satisfies ProviderOptionDefinitions;\n\ntype LanguageCapabilities = NonNullable<ModelCapabilities['language']> & {\n reasoning: NonNullable<ModelCapabilities['language']>['reasoning'] & {\n maxBudget: number;\n };\n};\n\ntype LanguageRequestConfig = {\n thinkingType: 'enabled';\n reasoningMaxOutputTokens: number;\n};\n\ntype EmbeddingType = NonNullable<CohereEmbeddingModelOptions['embeddingType']>;\n\ntype EmbeddingCapabilities = NonNullable<ModelCapabilities['embedding']> & {\n dimensions: readonly number[];\n embeddingTypes: readonly EmbeddingType[];\n maxEmbeddingsPerCall: number;\n supportsParallelCalls: boolean;\n};\n\ntype EmbeddingRequestConfig = {\n embeddingType: EmbeddingType;\n inputType: NonNullable<CohereEmbeddingModelOptions['inputType']>;\n};\n\nexport type CohereLanguageModelEntry = {\n capabilities: { language: LanguageCapabilities };\n providerOptions: {\n language: Record<keyof CohereLanguageModelChatOptions, ModelCapability>;\n };\n requestConfig: { language: LanguageRequestConfig };\n};\n\ntype CohereEmbeddingModelEntry = {\n // Unknown model IDs do not invent a default dimension.\n capabilities: { embedding?: EmbeddingCapabilities };\n providerOptions: {\n embedding: Record<keyof CohereEmbeddingModelOptions, ModelCapability>;\n };\n requestConfig: { embedding: EmbeddingRequestConfig };\n};\n\ntype CohereRerankingModelEntry = {\n capabilities: { reranking: NonNullable<ModelCapabilities['reranking']> };\n providerOptions: {\n reranking: Record<keyof CohereRerankingModelOptions, ModelCapability>;\n };\n};\n\ntype CohereModelEntry = ModelEntry<{\n language?: LanguageRequestConfig;\n embedding?: EmbeddingRequestConfig;\n}> & {\n capabilities: ModelCapabilities & {\n language?: LanguageCapabilities;\n embedding?: EmbeddingCapabilities;\n };\n providerOptions?: {\n [Section in keyof typeof cohereProviderOptions]?: Record<\n keyof (typeof cohereProviderOptions)[Section],\n ModelCapability\n >;\n };\n};\n\ntype LanguageDefinition = {\n image: boolean;\n objectGeneration: boolean;\n tools: boolean;\n reasoning?: boolean;\n};\n\nconst standard = { image: false, objectGeneration: true, tools: true };\nconst legacy = { image: false, objectGeneration: false, tools: false };\n\n// Preserve the provider page's model set and per-model exceptions.\nconst languageDefinitions: Record<string, LanguageDefinition> = {\n 'command-a-03-2025': standard,\n 'command-a-reasoning-08-2025': { ...standard, reasoning: true },\n 'command-a-vision-07-2025': { ...standard, image: true },\n 'command-r7b-12-2024': standard,\n 'command-r-plus-04-2024': standard,\n 'command-r-plus': standard,\n 'command-r-08-2024': standard,\n 'command-r-03-2024': standard,\n 'command-r': standard,\n command: legacy,\n 'command-nightly': legacy,\n 'command-light': legacy,\n 'command-light-nightly': legacy,\n};\n\nfunction createLanguageModelEntry(\n definition?: LanguageDefinition,\n): CohereLanguageModelEntry {\n const reasoningSupport = definition?.reasoning ?? 'unknown';\n return {\n capabilities: {\n language: {\n inputs: { image: definition?.image ?? 'unknown', audio: false },\n objectGeneration: definition?.objectGeneration ?? 'unknown',\n tools: {\n usage: definition?.tools ?? 'unknown',\n streaming: definition?.tools ?? 'unknown',\n },\n reasoning: { support: reasoningSupport, maxBudget: 32768 },\n sampling: { temperature: 'unknown', topP: 'unknown', logprobs: false },\n },\n },\n providerOptions: {\n language: declareProviderOptions(\n cohereProviderOptions.language,\n definition != null ? true : 'unknown',\n { thinking: reasoningSupport },\n ),\n },\n requestConfig: {\n language: { thinkingType: 'enabled', reasoningMaxOutputTokens: 32768 },\n },\n };\n}\n\n// These SDK limits apply to custom model IDs as well as catalog models.\nexport const cohereEmbeddingModelLimits = {\n maxEmbeddingsPerCall: 96,\n supportsParallelCalls: true,\n} as const;\n\nconst embeddingRequestConfig: EmbeddingRequestConfig = {\n embeddingType: 'float',\n inputType: 'search_query',\n};\n\nconst embeddingTypes: readonly EmbeddingType[] = [\n 'float',\n 'int8',\n 'uint8',\n 'binary',\n 'ubinary',\n];\n\nfunction createEmbeddingModelEntry(\n defaultDimensions: number,\n dimensions: readonly number[],\n formats: readonly EmbeddingType[] = embeddingTypes,\n) {\n const customDimensions = dimensions.length > 1;\n return {\n capabilities: {\n embedding: {\n defaultDimensions,\n customDimensions,\n dimensions,\n embeddingTypes: formats,\n ...cohereEmbeddingModelLimits,\n },\n },\n providerOptions: {\n embedding: declareProviderOptions(cohereProviderOptions.embedding, true, {\n outputDimension: customDimensions,\n embeddingType:\n formats.length === 1\n ? { condition: \"Only embeddingType: 'float' is supported.\" }\n : true,\n }),\n },\n requestConfig: { embedding: embeddingRequestConfig },\n };\n}\n\nfunction createRerankingModelEntry(\n declared: boolean,\n): CohereRerankingModelEntry {\n const support = declared ? true : 'unknown';\n return {\n capabilities: {\n reranking: {\n documents: {\n text: support,\n object: declared\n ? {\n condition:\n 'Objects are converted to JSON strings with a compatibility warning.',\n }\n : 'unknown',\n },\n topN: support,\n },\n },\n providerOptions: {\n reranking: declareProviderOptions(\n cohereProviderOptions.reranking,\n support,\n {},\n ),\n },\n };\n}\n\nexport const cohereModelCatalog: Readonly<Record<string, CohereModelEntry>> = {\n ...Object.fromEntries(\n Object.entries(languageDefinitions).map(([modelId, definition]) => [\n modelId,\n createLanguageModelEntry(definition),\n ]),\n ),\n 'embed-v5.0-pro': createEmbeddingModelEntry(\n 2048,\n [256, 512, 768, 1024, 1536, 2048],\n ),\n 'embed-v5.0-fast': createEmbeddingModelEntry(\n 2048,\n [256, 512, 768, 1024, 1536, 2048],\n ),\n 'embed-v4.0': createEmbeddingModelEntry(1536, [256, 512, 1024, 1536]),\n 'embed-english-v3.0': createEmbeddingModelEntry(1024, [1024]),\n 'embed-multilingual-v3.0': createEmbeddingModelEntry(1024, [1024]),\n 'embed-english-light-v3.0': createEmbeddingModelEntry(384, [384]),\n 'embed-multilingual-light-v3.0': createEmbeddingModelEntry(384, [384]),\n 'embed-english-v2.0': createEmbeddingModelEntry(4096, [4096], ['float']),\n 'embed-english-light-v2.0': createEmbeddingModelEntry(\n 1024,\n [1024],\n ['float'],\n ),\n 'embed-multilingual-v2.0': createEmbeddingModelEntry(768, [768], ['float']),\n 'rerank-v4.0-pro': createRerankingModelEntry(true),\n 'rerank-v4.0-fast': createRerankingModelEntry(true),\n 'rerank-v3.5': createRerankingModelEntry(true),\n 'rerank-english-v3.0': createRerankingModelEntry(true),\n 'rerank-multilingual-v3.0': createRerankingModelEntry(true),\n};\n\nfunction findModelEntry(modelId: string) {\n return Object.prototype.hasOwnProperty.call(cohereModelCatalog, modelId)\n ? cohereModelCatalog[modelId]\n : undefined;\n}\n\nexport function getCohereLanguageModelEntry(\n modelId: string,\n): CohereLanguageModelEntry {\n const entry = findModelEntry(modelId);\n return entry?.capabilities.language != null &&\n entry.providerOptions?.language != null &&\n entry.requestConfig?.language != null\n ? {\n capabilities: { language: entry.capabilities.language },\n providerOptions: { language: entry.providerOptions.language },\n requestConfig: { language: entry.requestConfig.language },\n }\n : createLanguageModelEntry();\n}\n\nexport function getCohereEmbeddingModelEntry(\n modelId: string,\n): CohereEmbeddingModelEntry {\n const entry = findModelEntry(modelId);\n return entry?.capabilities.embedding != null &&\n entry.providerOptions?.embedding != null &&\n entry.requestConfig?.embedding != null\n ? {\n capabilities: { embedding: entry.capabilities.embedding },\n providerOptions: { embedding: entry.providerOptions.embedding },\n requestConfig: { embedding: entry.requestConfig.embedding },\n }\n : {\n capabilities: {},\n providerOptions: {\n embedding: declareProviderOptions(\n cohereProviderOptions.embedding,\n 'unknown',\n {},\n ),\n },\n requestConfig: { embedding: embeddingRequestConfig },\n };\n}\n\nexport function getCohereRerankingModelEntry(\n modelId: string,\n): CohereRerankingModelEntry {\n const entry = findModelEntry(modelId);\n return entry?.capabilities.reranking != null &&\n entry.providerOptions?.reranking != null\n ? {\n capabilities: { reranking: entry.capabilities.reranking },\n providerOptions: { reranking: entry.providerOptions.reranking },\n }\n : createRerankingModelEntry(false);\n}\n\nfunction declareProviderOptions<Option extends string>(\n definitions: Readonly<Record<Option, ProviderOptionDefinition>>,\n support: ModelCapability,\n exceptions: Partial<Record<Option, ModelCapability>>,\n): Record<Option, ModelCapability> {\n return Object.fromEntries(\n (Object.keys(definitions) as Option[]).map(option => [\n option,\n exceptions[option] ?? support,\n ]),\n ) as Record<Option, ModelCapability>;\n}\n","import {\n UnsupportedFunctionalityError,\n type LanguageModelV4CallOptions,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nimport type { CohereToolChoice } from './cohere-chat-prompt';\n\nexport function prepareTools({\n tools,\n toolChoice,\n}: {\n tools: LanguageModelV4CallOptions['tools'];\n toolChoice?: LanguageModelV4CallOptions['toolChoice'];\n}): {\n tools:\n | Array<{\n type: 'function';\n function: {\n name: string | undefined;\n description: string | undefined;\n parameters: unknown;\n };\n }>\n | undefined;\n toolChoice: CohereToolChoice;\n toolWarnings: SharedV4Warning[];\n} {\n // when the tools array is empty, change it to undefined to prevent errors:\n tools = tools?.length ? tools : undefined;\n\n const toolWarnings: SharedV4Warning[] = [];\n\n if (tools == null) {\n return { tools: undefined, toolChoice: undefined, toolWarnings };\n }\n\n const cohereTools: Array<{\n type: 'function';\n function: {\n name: string;\n description: string | undefined;\n parameters: unknown;\n };\n }> = [];\n\n for (const tool of tools) {\n if (tool.type === 'provider') {\n toolWarnings.push({\n type: 'unsupported',\n feature: `provider-defined tool ${tool.id}`,\n });\n } else {\n cohereTools.push({\n type: 'function',\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n });\n }\n }\n\n if (toolChoice == null) {\n return { tools: cohereTools, toolChoice: undefined, toolWarnings };\n }\n\n const type = toolChoice.type;\n\n switch (type) {\n case 'auto':\n return { tools: cohereTools, toolChoice: undefined, toolWarnings };\n\n case 'none':\n return { tools: cohereTools, toolChoice: 'NONE', toolWarnings };\n\n case 'required':\n return { tools: cohereTools, toolChoice: 'REQUIRED', toolWarnings };\n\n case 'tool':\n return {\n tools: cohereTools.filter(\n tool => tool.function.name === toolChoice.toolName,\n ),\n toolChoice: 'REQUIRED',\n toolWarnings,\n };\n\n default: {\n const _exhaustiveCheck: never = type;\n throw new UnsupportedFunctionalityError({\n functionality: `tool choice type: ${_exhaustiveCheck}`,\n });\n }\n }\n}\n","import type { LanguageModelV4Usage } from '@ai-sdk/provider';\nimport { createNullLanguageModelUsage } from '@ai-sdk/provider-utils';\n\nexport type CohereUsageTokens = {\n input_tokens?: number | null;\n output_tokens?: number | null;\n};\n\nexport type CohereUsage = {\n billed_units?: CohereUsageTokens | null;\n tokens?: CohereUsageTokens | null;\n cached_tokens?: number | null;\n};\n\nexport function convertCohereUsage(\n usage: CohereUsage | undefined | null,\n): LanguageModelV4Usage {\n if (usage == null) {\n return createNullLanguageModelUsage();\n }\n\n // `tokens` is the only measure that matches the unified token counts.\n // `billed_units` count billed units rather than tokens, so they are kept in\n // `raw` only and never used as token counts or reduced by cached tokens.\n const inputTokens = usage.tokens?.input_tokens ?? undefined;\n const outputTokens = usage.tokens?.output_tokens ?? undefined;\n const cacheReadTokens = usage.cached_tokens ?? undefined;\n\n return {\n inputTokens: {\n total: inputTokens,\n noCache:\n inputTokens != null && cacheReadTokens != null\n ? inputTokens - cacheReadTokens\n : inputTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: outputTokens,\n text: outputTokens,\n reasoning: undefined,\n },\n raw: usage,\n };\n}\n","import {\n UnsupportedFunctionalityError,\n type LanguageModelV4FilePart,\n type LanguageModelV4Prompt,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nimport {\n secureJsonParse,\n stringifyWithBigIntAndCycles,\n convertBase64ToUint8Array,\n convertToBase64,\n getTopLevelMediaType,\n parseProviderOptions,\n resolveFullMediaType,\n} from '@ai-sdk/provider-utils';\nimport { cohereImagePartProviderOptions } from './cohere-chat-language-model-options';\nimport type {\n CohereAssistantMessage,\n CohereChatPrompt,\n CohereUserMessageContent,\n} from './cohere-chat-prompt';\n\nfunction serializeCohereToolCallArguments(input: unknown): string {\n if (typeof input === 'string') {\n try {\n secureJsonParse(input);\n return input;\n } catch {\n return JSON.stringify(input);\n }\n }\n return stringifyWithBigIntAndCycles(input);\n}\n\nexport async function convertToCohereChatPrompt(\n prompt: LanguageModelV4Prompt,\n): Promise<{\n messages: CohereChatPrompt;\n documents: Array<{\n data: { text: string; title?: string };\n }>;\n warnings: SharedV4Warning[];\n}> {\n const messages: CohereChatPrompt = [];\n const documents: Array<{ data: { text: string; title?: string } }> = [];\n const warnings: SharedV4Warning[] = [];\n\n for (const { role, content } of prompt) {\n switch (role) {\n case 'system': {\n messages.push({ role: 'system', content });\n break;\n }\n\n case 'user': {\n const userContentParts: Array<CohereUserMessageContent> = [];\n let hasImage = false;\n\n for (const part of content) {\n switch (part.type) {\n case 'text': {\n if (part.text.length > 0) {\n userContentParts.push({ type: 'text', text: part.text });\n }\n break;\n }\n case 'file': {\n if (getTopLevelMediaType(part.mediaType) === 'image') {\n hasImage = true;\n const url = buildImageUrl({ part });\n const cohereOptions =\n (await parseProviderOptions({\n provider: 'cohere',\n providerOptions: part.providerOptions,\n schema: cohereImagePartProviderOptions,\n })) ?? {};\n\n userContentParts.push({\n type: 'image_url',\n image_url: {\n url,\n ...(cohereOptions.detail\n ? { detail: cohereOptions.detail }\n : {}),\n },\n });\n break;\n }\n\n let textContent: string;\n switch (part.data.type) {\n case 'reference': {\n throw new UnsupportedFunctionalityError({\n functionality: 'file parts with provider references',\n });\n }\n case 'url': {\n throw new UnsupportedFunctionalityError({\n functionality: 'File URL data',\n message:\n 'URLs should be downloaded by the AI SDK and not reach this point. This indicates a configuration issue.',\n });\n }\n case 'text': {\n textContent = part.data.text;\n break;\n }\n case 'data': {\n textContent = new TextDecoder().decode(\n typeof part.data.data === 'string'\n ? convertBase64ToUint8Array(part.data.data)\n : part.data.data,\n );\n break;\n }\n }\n\n documents.push({\n data: {\n text: textContent,\n title: part.filename,\n },\n });\n break;\n }\n }\n }\n\n if (hasImage) {\n messages.push({ role: 'user', content: userContentParts });\n } else {\n messages.push({\n role: 'user',\n content: userContentParts\n .map(p => (p.type === 'text' ? p.text : ''))\n .join(''),\n });\n }\n break;\n }\n\n case 'assistant': {\n let text = '';\n const toolCalls: CohereAssistantMessage['tool_calls'] = [];\n\n for (const part of content) {\n switch (part.type) {\n case 'text': {\n text += part.text;\n break;\n }\n case 'tool-call': {\n toolCalls.push({\n id: part.toolCallId,\n type: 'function' as const,\n function: {\n name: part.toolName,\n arguments: serializeCohereToolCallArguments(part.input),\n },\n });\n break;\n }\n }\n }\n\n messages.push({\n role: 'assistant',\n content: toolCalls.length > 0 ? undefined : text,\n tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\n tool_plan: undefined,\n });\n\n break;\n }\n case 'tool': {\n messages.push(\n ...content\n .filter(toolResult => toolResult.type !== 'tool-approval-response')\n .map(toolResult => {\n const output = toolResult.output;\n\n let contentValue: string;\n switch (output.type) {\n case 'text':\n case 'error-text':\n contentValue = output.value;\n break;\n case 'execution-denied':\n contentValue = output.reason ?? 'Tool call execution denied.';\n break;\n case 'content':\n case 'json':\n case 'error-json':\n contentValue = stringifyWithBigIntAndCycles(output.value);\n break;\n }\n\n return {\n role: 'tool' as const,\n content: contentValue,\n tool_call_id: toolResult.toolCallId,\n };\n }),\n );\n\n break;\n }\n default: {\n const _exhaustiveCheck: never = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n\n return { messages, documents, warnings };\n}\n\nfunction buildImageUrl({ part }: { part: LanguageModelV4FilePart }): string {\n switch (part.data.type) {\n case 'url': {\n return part.data.url.toString();\n }\n case 'data': {\n return `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}`;\n }\n case 'reference': {\n throw new UnsupportedFunctionalityError({\n functionality: 'image file parts with provider references',\n });\n }\n case 'text': {\n throw new UnsupportedFunctionalityError({\n functionality: 'image file parts with text data',\n });\n }\n }\n}\n","import type { LanguageModelV4FinishReason } from '@ai-sdk/provider';\n\nexport function mapCohereFinishReason(\n finishReason: string | null | undefined,\n): LanguageModelV4FinishReason['unified'] {\n switch (finishReason) {\n case 'COMPLETE':\n case 'STOP_SEQUENCE':\n return 'stop';\n\n case 'MAX_TOKENS':\n return 'length';\n\n case 'ERROR':\n return 'error';\n\n case 'TOOL_CALL':\n return 'tool-calls';\n\n default:\n return 'other';\n }\n}\n","import type {\n LanguageModelV4,\n LanguageModelV4CallOptions,\n LanguageModelV4Content,\n LanguageModelV4FinishReason,\n LanguageModelV4GenerateResult,\n LanguageModelV4StreamPart,\n LanguageModelV4StreamResult,\n SharedV4Warning,\n} from '@ai-sdk/provider';\nimport {\n resolve,\n type Resolvable,\n lazySchema,\n zodSchema,\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonResponseHandler,\n isCustomReasoning,\n mapReasoningToProviderBudget,\n parseProviderOptions,\n parseJSON,\n postJsonToApi,\n serializeModelOptions,\n WORKFLOW_SERIALIZE,\n WORKFLOW_DESERIALIZE,\n type InferSchema,\n type FetchFunction,\n type ParseResult,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport {\n cohereLanguageModelChatOptions,\n type CohereChatModelId,\n} from './cohere-chat-language-model-options';\nimport {\n cohereCitationSchema,\n mapCohereCitationToSource,\n} from './cohere-citations';\nimport { cohereFailedResponseHandler } from './cohere-error';\nimport {\n getCohereLanguageModelEntry,\n type CohereLanguageModelEntry,\n} from './cohere-model-catalog';\nimport { prepareTools } from './cohere-prepare-tools';\nimport { convertCohereUsage, type CohereUsage } from './convert-cohere-usage';\nimport { convertToCohereChatPrompt } from './convert-to-cohere-chat-prompt';\nimport { mapCohereFinishReason } from './map-cohere-finish-reason';\n\ntype CohereChatConfig = {\n provider: string;\n baseURL: string;\n headers?: Resolvable<Record<string, string | undefined>>;\n fetch?: FetchFunction;\n generateId: () => string;\n};\n\nexport class CohereChatLanguageModel implements LanguageModelV4 {\n readonly specificationVersion = 'v4';\n\n readonly modelId: CohereChatModelId;\n\n readonly supportedUrls: Record<string, RegExp[]> = {\n 'image/*': [/^https?:\\/\\/.*$/],\n };\n\n private readonly config: CohereChatConfig;\n\n static [WORKFLOW_SERIALIZE](model: CohereChatLanguageModel) {\n return serializeModelOptions({\n modelId: model.modelId,\n config: model.config,\n });\n }\n\n static [WORKFLOW_DESERIALIZE](options: {\n modelId: CohereChatModelId;\n config: CohereChatConfig;\n }) {\n return new CohereChatLanguageModel(options.modelId, options.config);\n }\n\n constructor(modelId: CohereChatModelId, config: CohereChatConfig) {\n this.modelId = modelId;\n this.config = config;\n }\n\n get provider(): string {\n return this.config.provider;\n }\n\n private async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n stopSequences,\n responseFormat,\n seed,\n reasoning,\n tools,\n toolChoice,\n providerOptions,\n }: LanguageModelV4CallOptions) {\n const warnings: SharedV4Warning[] = [];\n\n const cohereOptions =\n (await parseProviderOptions({\n provider: 'cohere',\n providerOptions,\n schema: cohereLanguageModelChatOptions,\n })) ?? {};\n\n const {\n messages: chatPrompt,\n documents: cohereDocuments,\n warnings: promptWarnings,\n } = await convertToCohereChatPrompt(prompt);\n\n const {\n tools: cohereTools,\n toolChoice: cohereToolChoice,\n toolWarnings,\n } = prepareTools({ tools, toolChoice });\n\n warnings.push(...toolWarnings, ...promptWarnings);\n\n return {\n args: {\n // model id:\n model: this.modelId,\n\n // standardized settings:\n frequency_penalty: frequencyPenalty,\n presence_penalty: presencePenalty,\n max_tokens: maxOutputTokens,\n temperature,\n p: topP,\n k: topK,\n seed,\n stop_sequences: stopSequences,\n\n // response format:\n response_format:\n responseFormat?.type === 'json'\n ? { type: 'json_object', json_schema: responseFormat.schema }\n : undefined,\n\n // messages:\n messages: chatPrompt,\n\n // tools:\n tools: cohereTools,\n tool_choice: cohereToolChoice,\n\n // documents for RAG:\n ...(cohereDocuments.length > 0 && { documents: cohereDocuments }),\n\n // reasoning:\n ...resolveCohereThinking({\n modelEntry: getCohereLanguageModelEntry(this.modelId),\n reasoning,\n cohereOptions,\n warnings,\n }),\n },\n warnings,\n };\n }\n\n async doGenerate(\n options: LanguageModelV4CallOptions,\n ): Promise<LanguageModelV4GenerateResult> {\n const { args, warnings } = await this.getArgs(options);\n\n const {\n responseHeaders,\n value: response,\n rawValue: rawResponse,\n } = await postJsonToApi({\n url: `${this.config.baseURL}/chat`,\n headers: combineHeaders(\n await resolve(this.config.headers),\n options.headers,\n ),\n body: args,\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n cohereChatResponseSchema,\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n const content: Array<LanguageModelV4Content> = [];\n\n for (const item of response.message.content ?? []) {\n if (item.type === 'text' && item.text.length > 0) {\n content.push({ type: 'text', text: item.text });\n continue;\n }\n\n if (item.type === 'thinking' && item.thinking.length > 0) {\n content.push({ type: 'reasoning', text: item.thinking });\n continue;\n }\n }\n\n // citations:\n for (const citation of response.message.citations ?? []) {\n // Tool-sourced citations (e.g. citations of tool results in a follow-up\n // step) have no document to point at, so they are not emitted as sources.\n const source = mapCohereCitationToSource(citation, () =>\n this.config.generateId(),\n );\n\n if (source != null) {\n content.push(source);\n }\n }\n\n // tool calls:\n for (const toolCall of response.message.tool_calls ?? []) {\n content.push({\n type: 'tool-call' as const,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n // Cohere sometimes returns `null` for tool call arguments for tools\n // defined as having no arguments.\n input: toolCall.function.arguments.replace(/^null$/, '{}'),\n });\n }\n\n return {\n content,\n finishReason: {\n unified: mapCohereFinishReason(response.finish_reason),\n raw: response.finish_reason ?? undefined,\n },\n usage: convertCohereUsage(response.usage),\n request: { body: args },\n response: {\n // TODO timestamp, model id\n // Cohere v2 returns `id`; `generation_id` is the v1 field, kept only\n // for compatibility with proxies/mocks that still return it.\n id: response.id ?? response.generation_id ?? undefined,\n headers: responseHeaders,\n body: rawResponse,\n },\n warnings,\n };\n }\n\n async doStream(\n options: LanguageModelV4CallOptions,\n ): Promise<LanguageModelV4StreamResult> {\n const { args, warnings } = await this.getArgs(options);\n\n const { responseHeaders, value: response } = await postJsonToApi({\n url: `${this.config.baseURL}/chat`,\n headers: combineHeaders(\n await resolve(this.config.headers),\n options.headers,\n ),\n body: { ...args, stream: true },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n cohereChatChunkSchema,\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n // A clean end without the provider's completion signal is interrupted.\n let finishReason: LanguageModelV4FinishReason = {\n unified: 'interrupted',\n raw: undefined,\n };\n let usage: CohereUsage | undefined = undefined;\n\n let pendingToolCall: {\n id: string;\n name: string;\n arguments: string;\n hasFinished: boolean;\n } | null = null;\n\n let isActiveReasoning = false;\n\n const generateId = this.config.generateId;\n\n return {\n stream: response.pipeThrough(\n new TransformStream<\n ParseResult<InferSchema<typeof cohereChatChunkSchema>>,\n LanguageModelV4StreamPart\n >({\n start(controller) {\n controller.enqueue({ type: 'stream-start', warnings });\n },\n\n async transform(chunk, controller) {\n if (options.includeRawChunks) {\n controller.enqueue({ type: 'raw', rawValue: chunk.rawValue });\n }\n\n // handle failed chunk parsing / validation:\n if (!chunk.success) {\n finishReason = { unified: 'error', raw: undefined };\n controller.enqueue({ type: 'error', error: chunk.error });\n return;\n }\n\n const value = chunk.value;\n const type = value.type;\n\n switch (type) {\n case 'content-start': {\n if (value.delta.message.content.type === 'thinking') {\n controller.enqueue({\n type: 'reasoning-start',\n id: String(value.index),\n });\n isActiveReasoning = true;\n return;\n }\n\n controller.enqueue({\n type: 'text-start',\n id: String(value.index),\n });\n return;\n }\n\n case 'content-delta': {\n if ('thinking' in value.delta.message.content) {\n controller.enqueue({\n type: 'reasoning-delta',\n id: String(value.index),\n delta: value.delta.message.content.thinking,\n });\n return;\n }\n\n controller.enqueue({\n type: 'text-delta',\n id: String(value.index),\n delta: value.delta.message.content.text,\n });\n return;\n }\n\n case 'content-end': {\n if (isActiveReasoning) {\n controller.enqueue({\n type: 'reasoning-end',\n id: String(value.index),\n });\n isActiveReasoning = false;\n return;\n }\n\n controller.enqueue({\n type: 'text-end',\n id: String(value.index),\n });\n\n return;\n }\n\n case 'citation-start': {\n const citations = value.delta?.message?.citations;\n if (citations == null) {\n return;\n }\n\n for (const citation of Array.isArray(citations)\n ? citations\n : [citations]) {\n // Tool-only citations have no document, so they are not\n // emitted as sources (matching doGenerate).\n const source = mapCohereCitationToSource(\n citation,\n generateId,\n );\n\n if (source != null) {\n controller.enqueue(source);\n }\n }\n return;\n }\n\n case 'tool-call-start': {\n const toolId = value.delta.message.tool_calls.id;\n const toolName = value.delta.message.tool_calls.function.name;\n const initialArgs =\n value.delta.message.tool_calls.function.arguments;\n\n pendingToolCall = {\n id: toolId,\n name: toolName,\n arguments: initialArgs,\n hasFinished: false,\n };\n\n controller.enqueue({\n type: 'tool-input-start',\n id: toolId,\n toolName,\n });\n\n if (initialArgs.length > 0) {\n controller.enqueue({\n type: 'tool-input-delta',\n id: toolId,\n delta: initialArgs,\n });\n }\n return;\n }\n\n case 'tool-call-delta': {\n if (pendingToolCall && !pendingToolCall.hasFinished) {\n const argsDelta =\n value.delta.message.tool_calls.function.arguments;\n pendingToolCall.arguments += argsDelta;\n\n controller.enqueue({\n type: 'tool-input-delta',\n id: pendingToolCall.id,\n delta: argsDelta,\n });\n }\n return;\n }\n\n case 'tool-call-end': {\n if (pendingToolCall && !pendingToolCall.hasFinished) {\n controller.enqueue({\n type: 'tool-input-end',\n id: pendingToolCall.id,\n });\n\n controller.enqueue({\n type: 'tool-call',\n toolCallId: pendingToolCall.id,\n toolName: pendingToolCall.name,\n input: JSON.stringify(\n (await parseJSON({\n text: pendingToolCall.arguments?.trim() || '{}',\n })) ?? {},\n ),\n });\n\n pendingToolCall.hasFinished = true;\n pendingToolCall = null;\n }\n return;\n }\n\n case 'message-start': {\n controller.enqueue({\n type: 'response-metadata',\n id: value.id ?? undefined,\n });\n return;\n }\n\n case 'message-end': {\n finishReason = {\n unified: mapCohereFinishReason(value.delta.finish_reason),\n raw: value.delta.finish_reason,\n };\n usage = value.delta.usage;\n return;\n }\n\n default: {\n }\n }\n },\n\n flush(controller) {\n controller.enqueue({\n type: 'finish',\n finishReason,\n usage: convertCohereUsage(usage),\n });\n },\n }),\n ),\n request: { body: { ...args, stream: true } },\n response: { headers: responseHeaders },\n };\n }\n}\n\nfunction resolveCohereThinking({\n modelEntry,\n reasoning,\n cohereOptions,\n warnings,\n}: {\n modelEntry: CohereLanguageModelEntry;\n reasoning: LanguageModelV4CallOptions['reasoning'];\n cohereOptions: InferSchema<typeof cohereLanguageModelChatOptions>;\n warnings: SharedV4Warning[];\n}): { thinking?: { type: string; token_budget?: number } } {\n const {\n capabilities: { language: capabilities },\n requestConfig: { language: defaults },\n } = modelEntry;\n if (cohereOptions.thinking) {\n return {\n thinking: {\n type: cohereOptions.thinking.type ?? defaults.thinkingType,\n token_budget: cohereOptions.thinking.tokenBudget,\n },\n };\n }\n\n if (!isCustomReasoning(reasoning)) {\n return {};\n }\n\n if (reasoning === 'none') {\n return { thinking: { type: 'disabled' } };\n }\n\n const tokenBudget = mapReasoningToProviderBudget({\n reasoning,\n maxOutputTokens: defaults.reasoningMaxOutputTokens,\n maxReasoningBudget: capabilities.reasoning.maxBudget,\n warnings,\n });\n\n return { thinking: { type: 'enabled', token_budget: tokenBudget } };\n}\n\n// Loose, nested objects included: the parsed value is returned as `usage.raw`.\n// All fields are optional in the API specification, so every field is nullish.\nconst cohereUsageSchema = () =>\n z.looseObject({\n billed_units: z\n .looseObject({\n input_tokens: z.number().nullish(),\n output_tokens: z.number().nullish(),\n })\n .nullish(),\n tokens: z\n .looseObject({\n input_tokens: z.number().nullish(),\n output_tokens: z.number().nullish(),\n })\n .nullish(),\n cached_tokens: z.number().nullish(),\n });\n\nconst cohereChatResponseSchema = lazySchema(() =>\n zodSchema(\n z.object({\n id: z.string().nullish(),\n generation_id: z.string().nullish(),\n message: z.object({\n role: z.string(),\n content: z\n .array(\n z.union([\n z.object({\n type: z.literal('text'),\n text: z.string(),\n }),\n z.object({\n type: z.literal('thinking'),\n thinking: z.string(),\n }),\n ]),\n )\n .nullish(),\n tool_plan: z.string().nullish(),\n tool_calls: z\n .array(\n z.object({\n id: z.string(),\n type: z.literal('function'),\n function: z.object({\n name: z.string(),\n arguments: z.string(),\n }),\n }),\n )\n .nullish(),\n citations: z.array(cohereCitationSchema).nullish(),\n }),\n finish_reason: z.string(),\n usage: cohereUsageSchema().nullish(),\n }),\n ),\n);\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nconst cohereChatChunkSchema = lazySchema(() =>\n zodSchema(\n z.discriminatedUnion('type', [\n // `citation-start` events can arrive without citations, and a single\n // citation may be sent instead of an array.\n z.object({\n type: z.literal('citation-start'),\n index: z.number().nullish(),\n delta: z\n .object({\n message: z\n .object({\n citations: z\n .union([cohereCitationSchema, z.array(cohereCitationSchema)])\n .nullish(),\n })\n .nullish(),\n })\n .nullish(),\n }),\n z.object({\n type: z.literal('citation-end'),\n }),\n z.object({\n type: z.literal('content-start'),\n index: z.number(),\n delta: z.object({\n message: z.object({\n content: z.union([\n z.object({\n type: z.literal('text'),\n text: z.string(),\n }),\n z.object({\n type: z.literal('thinking'),\n thinking: z.string(),\n }),\n ]),\n }),\n }),\n }),\n z.object({\n type: z.literal('content-delta'),\n index: z.number(),\n delta: z.object({\n message: z.object({\n content: z.union([\n z.object({\n text: z.string(),\n }),\n z.object({\n thinking: z.string(),\n }),\n ]),\n }),\n }),\n }),\n z.object({\n type: z.literal('content-end'),\n index: z.number(),\n }),\n z.object({\n type: z.literal('message-start'),\n id: z.string().nullish(),\n }),\n z.object({\n type: z.literal('message-end'),\n delta: z.object({\n finish_reason: z.string(),\n usage: cohereUsageSchema(),\n }),\n }),\n // https://docs.cohere.com/v2/docs/streaming#tool-use-stream-events-for-tool-calling\n z.object({\n type: z.literal('tool-plan-delta'),\n delta: z.object({\n message: z.object({\n tool_plan: z.string(),\n }),\n }),\n }),\n z.object({\n type: z.literal('tool-call-start'),\n delta: z.object({\n message: z.object({\n tool_calls: z.object({\n id: z.string(),\n type: z.literal('function'),\n function: z.object({\n name: z.string(),\n arguments: z.string(),\n }),\n }),\n }),\n }),\n }),\n // A single tool call's `arguments` stream in chunks and must be accumulated\n // in a string and so the full tool object info can only be parsed once we see\n // `tool-call-end`.\n z.object({\n type: z.literal('tool-call-delta'),\n delta: z.object({\n message: z.object({\n tool_calls: z.object({\n function: z.object({\n arguments: z.string(),\n }),\n }),\n }),\n }),\n }),\n z.object({\n type: z.literal('tool-call-end'),\n }),\n ]),\n ),\n);\n","import {\n lazySchema,\n zodSchema,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport type CohereEmbeddingModelId =\n | 'embed-english-v3.0'\n | 'embed-multilingual-v3.0'\n | 'embed-english-light-v3.0'\n | 'embed-multilingual-light-v3.0'\n | 'embed-english-v2.0'\n | 'embed-english-light-v2.0'\n | 'embed-multilingual-v2.0'\n | (string & {});\n\nexport const cohereEmbeddingModelOptions = lazySchema(() =>\n zodSchema(\n z.object({\n /**\n * The format of the returned embedding. Defaults to `float`.\n * Non-float formats require Embed v3.0 or newer.\n * Binary formats contain packed bytes, not individual vector dimensions.\n */\n embeddingType: z\n .enum(['float', 'int8', 'uint8', 'binary', 'ubinary'])\n .optional(),\n\n /**\n * Specifies the type of input passed to the model. Default is `search_query`.\n *\n * - \"search_document\": Used for embeddings stored in a vector database for search use-cases.\n * - \"search_query\": Used for embeddings of search queries run against a vector DB to find relevant documents.\n * - \"classification\": Used for embeddings passed through a text classifier.\n * - \"clustering\": Used for embeddings run through a clustering algorithm.\n */\n inputType: z\n .enum([\n 'search_document',\n 'search_query',\n 'classification',\n 'clustering',\n ])\n .optional(),\n\n /**\n * Specifies how the API will handle inputs longer than the maximum token length.\n * Default is `END`.\n *\n * - \"NONE\": If selected, when the input exceeds the maximum input token length will return an error.\n * - \"START\": Will discard the start of the input until the remaining input is exactly the maximum input token length for the model.\n * - \"END\": Will discard the end of the input until the remaining input is exactly the maximum input token length for the model.\n */\n truncate: z.enum(['NONE', 'START', 'END']).optional(),\n\n /**\n * The number of dimensions of the output embedding.\n * Only available for `embed-v4.0` and newer models.\n *\n * Embed v4.0 supports `256`, `512`, `1024`, and `1536` (default).\n * Embed v5.0 Pro and Fast also support `768` and `2048` (default).\n */\n outputDimension: z\n .union([\n z.literal(256),\n z.literal(512),\n z.literal(768),\n z.literal(1024),\n z.literal(1536),\n z.literal(2048),\n ])\n .optional(),\n }),\n ),\n);\n\nexport type CohereEmbeddingModelOptions = InferSchema<\n typeof cohereEmbeddingModelOptions\n>;\n","import {\n TooManyEmbeddingValuesForCallError,\n type EmbeddingModelV4,\n} from '@ai-sdk/provider';\nimport {\n resolve,\n type Resolvable,\n combineHeaders,\n createJsonResponseHandler,\n parseProviderOptions,\n postJsonToApi,\n serializeModelOptions,\n WORKFLOW_SERIALIZE,\n WORKFLOW_DESERIALIZE,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport {\n cohereEmbeddingModelOptions,\n type CohereEmbeddingModelId,\n type CohereEmbeddingModelOptions,\n} from './cohere-embedding-model-options';\nimport { cohereFailedResponseHandler } from './cohere-error';\nimport {\n cohereEmbeddingModelLimits,\n getCohereEmbeddingModelEntry,\n} from './cohere-model-catalog';\n\ntype CohereEmbeddingConfig = {\n provider: string;\n baseURL: string;\n headers?: Resolvable<Record<string, string | undefined>>;\n fetch?: FetchFunction;\n};\n\nexport class CohereEmbeddingModel implements EmbeddingModelV4 {\n readonly specificationVersion = 'v4';\n readonly modelId: CohereEmbeddingModelId;\n\n readonly maxEmbeddingsPerCall: number;\n readonly supportsParallelCalls: boolean;\n\n private readonly config: CohereEmbeddingConfig;\n\n static [WORKFLOW_SERIALIZE](model: CohereEmbeddingModel) {\n return serializeModelOptions({\n modelId: model.modelId,\n config: model.config,\n });\n }\n\n static [WORKFLOW_DESERIALIZE](options: {\n modelId: CohereEmbeddingModelId;\n config: CohereEmbeddingConfig;\n }) {\n return new CohereEmbeddingModel(options.modelId, options.config);\n }\n\n constructor(modelId: CohereEmbeddingModelId, config: CohereEmbeddingConfig) {\n this.modelId = modelId;\n const limits =\n getCohereEmbeddingModelEntry(modelId).capabilities.embedding ??\n cohereEmbeddingModelLimits;\n this.maxEmbeddingsPerCall = limits.maxEmbeddingsPerCall;\n this.supportsParallelCalls = limits.supportsParallelCalls;\n this.config = config;\n }\n\n get provider(): string {\n return this.config.provider;\n }\n\n async doEmbed({\n values,\n dimensions,\n headers,\n abortSignal,\n providerOptions,\n }: Parameters<EmbeddingModelV4['doEmbed']>[0]): Promise<\n Awaited<ReturnType<EmbeddingModelV4['doEmbed']>>\n > {\n const embeddingOptions = await parseProviderOptions({\n provider: 'cohere',\n providerOptions,\n schema: cohereEmbeddingModelOptions,\n });\n const defaults = getCohereEmbeddingModelEntry(this.modelId).requestConfig\n .embedding;\n const embeddingType =\n embeddingOptions?.embeddingType ?? defaults.embeddingType;\n\n if (values.length > this.maxEmbeddingsPerCall) {\n throw new TooManyEmbeddingValuesForCallError({\n provider: this.provider,\n modelId: this.modelId,\n maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,\n values,\n });\n }\n\n const {\n responseHeaders,\n value: response,\n rawValue,\n } = await postJsonToApi({\n url: `${this.config.baseURL}/embed`,\n headers: combineHeaders(await resolve(this.config.headers), headers),\n body: {\n model: this.modelId,\n embedding_types: [embeddingType],\n texts: values,\n input_type: embeddingOptions?.inputType ?? defaults.inputType,\n truncate: embeddingOptions?.truncate,\n output_dimension: embeddingOptions?.outputDimension ?? dimensions,\n },\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n cohereTextEmbeddingResponseSchema(embeddingType),\n ),\n abortSignal,\n fetch: this.config.fetch,\n });\n\n return {\n warnings: [],\n embeddings: response.embeddings[embeddingType],\n usage: { tokens: response.meta.billed_units.input_tokens },\n response: { headers: responseHeaders, body: rawValue },\n };\n }\n}\n\n// minimal version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nconst cohereTextEmbeddingResponseSchema = (\n embeddingType: NonNullable<CohereEmbeddingModelOptions['embeddingType']>,\n) =>\n z.object({\n embeddings: z.object({\n [embeddingType]: z.array(z.array(z.number())),\n }),\n meta: z.object({\n billed_units: z.object({\n input_tokens: z.number(),\n }),\n }),\n });\n","import { lazySchema, zodSchema } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// https://docs.cohere.com/v2/reference/rerank\nexport type CohereRerankingInput = {\n model: string;\n query: string;\n documents: string[];\n top_n: number | undefined;\n max_tokens_per_doc: number | undefined;\n priority: number | undefined;\n};\n\nexport const cohereRerankingResponseSchema = lazySchema(() =>\n zodSchema(\n z.object({\n id: z.string().nullish(),\n results: z.array(\n z.object({\n index: z.number(),\n relevance_score: z.number(),\n }),\n ),\n }),\n ),\n);\n","import {\n lazySchema,\n zodSchema,\n type FlexibleSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// https://docs.cohere.com/docs/rerank\nexport type CohereRerankingModelId =\n | 'rerank-v3.5'\n | 'rerank-english-v3.0'\n | 'rerank-multilingual-v3.0'\n | (string & {});\n\nexport type CohereRerankingModelOptions = {\n /**\n * Long documents will be automatically truncated to the specified number of tokens.\n *\n * @default 4096\n */\n maxTokensPerDoc?: number;\n\n /**\n * The priority of the request.\n *\n * @default 0\n */\n priority?: number;\n};\n\nexport const cohereRerankingModelOptionsSchema: FlexibleSchema<CohereRerankingModelOptions> =\n lazySchema(() =>\n zodSchema(\n z.object({\n maxTokensPerDoc: z.number().optional(),\n priority: z.number().optional(),\n }),\n ),\n );\n","import type { RerankingModelV4, SharedV4Warning } from '@ai-sdk/provider';\nimport {\n resolve,\n type Resolvable,\n combineHeaders,\n createJsonResponseHandler,\n parseProviderOptions,\n postJsonToApi,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { cohereFailedResponseHandler } from '../cohere-error';\nimport {\n cohereRerankingResponseSchema,\n type CohereRerankingInput,\n} from './cohere-reranking-api';\nimport {\n cohereRerankingModelOptionsSchema,\n type CohereRerankingModelId,\n} from './cohere-reranking-model-options';\ntype CohereRerankingConfig = {\n provider: string;\n baseURL: string;\n headers: Resolvable<Record<string, string | undefined>>;\n fetch?: FetchFunction;\n};\n\nexport class CohereRerankingModel implements RerankingModelV4 {\n readonly specificationVersion = 'v4';\n readonly modelId: CohereRerankingModelId;\n\n private readonly config: CohereRerankingConfig;\n\n constructor(modelId: CohereRerankingModelId, config: CohereRerankingConfig) {\n this.modelId = modelId;\n this.config = config;\n }\n\n get provider(): string {\n return this.config.provider;\n }\n\n // current implementation is based on v2 of the API: https://docs.cohere.com/v2/reference/rerank\n async doRerank({\n documents,\n headers,\n query,\n topN,\n abortSignal,\n providerOptions,\n }: Parameters<RerankingModelV4['doRerank']>[0]): Promise<\n Awaited<ReturnType<RerankingModelV4['doRerank']>>\n > {\n const rerankingOptions = await parseProviderOptions({\n provider: 'cohere',\n providerOptions,\n schema: cohereRerankingModelOptionsSchema,\n });\n\n const warnings: SharedV4Warning[] = [];\n\n if (documents.type === 'object') {\n warnings.push({\n type: 'compatibility',\n feature: 'object documents',\n details: 'Object documents are converted to strings.',\n });\n }\n\n const {\n responseHeaders,\n value: response,\n rawValue,\n } = await postJsonToApi({\n url: `${this.config.baseURL}/rerank`,\n headers: combineHeaders(await resolve(this.config.headers), headers),\n body: {\n model: this.modelId,\n query,\n documents:\n documents.type === 'text'\n ? documents.values\n : documents.values.map(value => JSON.stringify(value)),\n top_n: topN,\n max_tokens_per_doc: rerankingOptions?.maxTokensPerDoc,\n priority: rerankingOptions?.priority,\n } satisfies CohereRerankingInput,\n failedResponseHandler: cohereFailedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n cohereRerankingResponseSchema,\n ),\n abortSignal,\n fetch: this.config.fetch,\n });\n\n return {\n ranking: response.results.map(result => ({\n index: result.index,\n relevanceScore: result.relevance_score,\n })),\n warnings,\n response: {\n id: response.id ?? undefined,\n headers: responseHeaders,\n body: rawValue,\n },\n };\n }\n}\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import {\n NoSuchModelError,\n type EmbeddingModelV4,\n type LanguageModelV4,\n type RerankingModelV4,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n resolveWith,\n type Resolvable,\n generateId,\n loadApiKey,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { CohereChatLanguageModel } from './cohere-chat-language-model';\nimport type { CohereChatModelId } from './cohere-chat-language-model-options';\nimport { CohereEmbeddingModel } from './cohere-embedding-model';\nimport type { CohereRerankingModelId } from './reranking/cohere-reranking-model-options';\nimport { CohereRerankingModel } from './reranking/cohere-reranking-model';\nimport type { CohereEmbeddingModelId } from './cohere-embedding-model-options';\nimport { VERSION } from './version';\n\nexport interface CohereProvider extends ProviderV4 {\n (modelId: CohereChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation.\n */\n languageModel(modelId: CohereChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text embeddings.\n */\n embedding(modelId: CohereEmbeddingModelId): EmbeddingModelV4;\n\n /**\n * Creates a model for text embeddings.\n */\n embeddingModel(modelId: CohereEmbeddingModelId): EmbeddingModelV4;\n\n /**\n * @deprecated Use `embedding` instead.\n */\n textEmbedding(modelId: CohereEmbeddingModelId): EmbeddingModelV4;\n\n /**\n * @deprecated Use `embeddingModel` instead.\n */\n textEmbeddingModel(modelId: CohereEmbeddingModelId): EmbeddingModelV4;\n\n /**\n * Creates a model for reranking.\n */\n reranking(modelId: CohereRerankingModelId): RerankingModelV4;\n\n /**\n * Creates a model for reranking.\n */\n rerankingModel(modelId: CohereRerankingModelId): RerankingModelV4;\n}\n\nexport interface CohereProviderSettings {\n /**\n * Use a different URL prefix for API calls, e.g. to use proxy servers.\n * The default prefix is `https://api.cohere.com/v2`.\n */\n baseURL?: string;\n\n /**\n * API key that is being send using the `Authorization` header.\n * It defaults to the `COHERE_API_KEY` environment variable.\n */\n apiKey?: Resolvable<string>;\n\n /**\n * Custom headers to include in the requests.\n */\n headers?: Record<string, string>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\n * Optional function to generate a unique ID for each request.\n */\n generateId?: () => string;\n}\n\n/**\n * Create a Cohere AI provider instance.\n */\nexport function createCohere(\n options: CohereProviderSettings = {},\n): CohereProvider {\n const baseURL =\n withoutTrailingSlash(options.baseURL) ?? 'https://api.cohere.com/v2';\n\n const getHeaders = () =>\n resolveWith(options.apiKey, apiKey =>\n withUserAgentSuffix(\n {\n Authorization: `Bearer ${loadApiKey({\n apiKey,\n environmentVariableName: 'COHERE_API_KEY',\n description: 'Cohere',\n })}`,\n ...options.headers,\n },\n `ai-sdk-cohere/${VERSION}`,\n ),\n );\n\n const createChatModel = (modelId: CohereChatModelId) =>\n new CohereChatLanguageModel(modelId, {\n provider: 'cohere.chat',\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n generateId: options.generateId ?? generateId,\n });\n\n const createEmbeddingModel = (modelId: CohereEmbeddingModelId) =>\n new CohereEmbeddingModel(modelId, {\n provider: 'cohere.textEmbedding',\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n });\n\n const createRerankingModel = (modelId: CohereRerankingModelId) =>\n new CohereRerankingModel(modelId, {\n provider: 'cohere.reranking',\n baseURL,\n headers: getHeaders,\n fetch: options.fetch,\n });\n\n const provider = function (modelId: CohereChatModelId) {\n if (new.target) {\n throw new Error(\n 'The Cohere model function cannot be called with the new keyword.',\n );\n }\n\n return createChatModel(modelId);\n };\n\n provider.specificationVersion = 'v4' as const;\n provider.languageModel = createChatModel;\n provider.embedding = createEmbeddingModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbedding = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.reranking = createRerankingModel;\n provider.rerankingModel = createRerankingModel;\n\n provider.imageModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'imageModel' });\n };\n\n return provider;\n}\n\n/**\n * Default Cohere provider instance.\n */\nexport const cohere = createCohere();\n"],"mappings":";;;;AAwBA,MAAa,iCAAiC,iBAC5C,UACE,EAAE,OAAO;;;;;;;;;AASP,UAAU,EACP,OAAO;CACN,MAAM,EAAE,KAAK,CAAC,WAAW,UAAU,CAAC,CAAC,CAAC,SAAS;CAC/C,aAAa,EAAE,OAAO,CAAC,CAAC,SAAS;AACnC,CAAC,CAAC,CACD,SAAS,EACd,CAAC,CACH,CACF;AAMA,MAAa,iCAAiC,iBA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AEH,MAAM,wBAAwB,YAC5B,IAAI,qBAAqB,SAAS;EAChC,UAAU;EACV;EACA,SAAS;EACT,OAAO,QAAQ;CACjB,CAAC;CAEH,MAAM,WAAW,SAAU,SAA4B;EACrD,IAAI,YACF,MAAM,IAAI,MACR,kEACF;EAGF,OAAO,gBAAgB,OAAO;CAChC;CAEA,SAAS,uBAAuB;CAChC,SAAS,gBAAgB;CACzB,SAAS,YAAY;CACrB,SAAS,iBAAiB;CAC1B,SAAS,gBAAgB;CACzB,SAAS,qBAAqB;CAC9B,SAAS,YAAY;CACrB,SAAS,iBAAiB;CAE1B,SAAS,cAAc,YAAoB;EACzC,MAAM,IAAI,iBAAiB;GAAE;GAAS,WAAW;EAAa,CAAC;CACjE;CAEA,OAAO;AACT;;;;AAKA,MAAa,SAAS,aAAa"}
|
package/docs/25-cohere.mdx
CHANGED
|
@@ -252,6 +252,75 @@ async function main() {
|
|
|
252
252
|
main().catch(console.error);
|
|
253
253
|
```
|
|
254
254
|
|
|
255
|
+
#### Sources
|
|
256
|
+
|
|
257
|
+
You can ground a Cohere response in documents by adding text files to the prompt
|
|
258
|
+
as file parts. When the model cites one of these documents, the provider returns
|
|
259
|
+
the cited text span as a source.
|
|
260
|
+
|
|
261
|
+
With `generateText`, cited documents are available in `result.sources`:
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
import { cohere } from '@ai-sdk/cohere';
|
|
265
|
+
import { generateText } from 'ai';
|
|
266
|
+
import { readFileSync } from 'node:fs';
|
|
267
|
+
|
|
268
|
+
const model = cohere('command-a-03-2025');
|
|
269
|
+
|
|
270
|
+
const { text, sources } = await generateText({
|
|
271
|
+
model,
|
|
272
|
+
messages: [
|
|
273
|
+
{
|
|
274
|
+
role: 'user',
|
|
275
|
+
content: [
|
|
276
|
+
{ type: 'text', text: 'What is the capital of Zephyria?' },
|
|
277
|
+
{
|
|
278
|
+
type: 'file',
|
|
279
|
+
mediaType: 'text/plain',
|
|
280
|
+
filename: 'zephyria.txt',
|
|
281
|
+
data: readFileSync('./data/zephyria.txt'),
|
|
282
|
+
},
|
|
283
|
+
],
|
|
284
|
+
},
|
|
285
|
+
],
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
console.log(sources);
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
With `streamText`, the same citations are emitted as `source` stream parts:
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
import { streamText } from 'ai';
|
|
295
|
+
|
|
296
|
+
const result = streamText({
|
|
297
|
+
model,
|
|
298
|
+
messages: [
|
|
299
|
+
// same messages as above
|
|
300
|
+
],
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
for await (const part of result.fullStream) {
|
|
304
|
+
if (part.type === 'source') {
|
|
305
|
+
console.log(part.sourceType); // 'document'
|
|
306
|
+
console.log(part.title);
|
|
307
|
+
console.log(part.providerMetadata?.cohere);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
Each source has `sourceType: 'document'`, the document title (`'Document'` when
|
|
313
|
+
Cohere does not return one), and citation details in `providerMetadata.cohere`:
|
|
314
|
+
|
|
315
|
+
- `start` / `end` _number_ - character offsets of the cited text in the response.
|
|
316
|
+
- `text` _string_ - the cited text.
|
|
317
|
+
- `sources` _array_ - the raw Cohere sources, including each document's `id`, `text`, and `title`.
|
|
318
|
+
- `citationType` _string_ - the Cohere citation type, e.g. `'TEXT_CONTENT'`.
|
|
319
|
+
|
|
320
|
+
Keys that Cohere omits are absent from `providerMetadata.cohere`. Citations that
|
|
321
|
+
only reference tool output have no document to cite and are not emitted as
|
|
322
|
+
sources.
|
|
323
|
+
|
|
255
324
|
## Embedding Models
|
|
256
325
|
|
|
257
326
|
You can create models that call the [Cohere embed API](https://docs.cohere.com/v2/reference/embed)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-sdk/cohere",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.78",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -29,8 +29,8 @@
|
|
|
29
29
|
}
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@ai-sdk/provider": "4.0.
|
|
33
|
-
"@ai-sdk/provider-utils": "5.0.
|
|
32
|
+
"@ai-sdk/provider": "4.0.37",
|
|
33
|
+
"@ai-sdk/provider-utils": "5.0.76"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@ai-sdk/test-server": "2.0.4",
|
|
@@ -33,6 +33,10 @@ 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';
|
|
37
41
|
import {
|
|
38
42
|
getCohereLanguageModelEntry,
|
|
@@ -207,22 +211,15 @@ export class CohereChatLanguageModel implements LanguageModelV4 {
|
|
|
207
211
|
|
|
208
212
|
// citations:
|
|
209
213
|
for (const citation of response.message.citations ?? []) {
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
end: citation.end,
|
|
220
|
-
text: citation.text,
|
|
221
|
-
sources: citation.sources,
|
|
222
|
-
...(citation.type && { citationType: citation.type }),
|
|
223
|
-
},
|
|
224
|
-
},
|
|
225
|
-
});
|
|
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
|
+
}
|
|
226
223
|
}
|
|
227
224
|
|
|
228
225
|
// tool calls:
|
|
@@ -247,7 +244,9 @@ export class CohereChatLanguageModel implements LanguageModelV4 {
|
|
|
247
244
|
request: { body: args },
|
|
248
245
|
response: {
|
|
249
246
|
// TODO timestamp, model id
|
|
250
|
-
id
|
|
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,
|
|
251
250
|
headers: responseHeaders,
|
|
252
251
|
body: rawResponse,
|
|
253
252
|
},
|
|
@@ -291,6 +290,8 @@ export class CohereChatLanguageModel implements LanguageModelV4 {
|
|
|
291
290
|
|
|
292
291
|
let isActiveReasoning = false;
|
|
293
292
|
|
|
293
|
+
const generateId = this.config.generateId;
|
|
294
|
+
|
|
294
295
|
return {
|
|
295
296
|
stream: response.pipeThrough(
|
|
296
297
|
new TransformStream<
|
|
@@ -370,6 +371,29 @@ export class CohereChatLanguageModel implements LanguageModelV4 {
|
|
|
370
371
|
return;
|
|
371
372
|
}
|
|
372
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
|
+
|
|
373
397
|
case 'tool-call-start': {
|
|
374
398
|
const toolId = value.delta.message.tool_calls.id;
|
|
375
399
|
const toolName = value.delta.message.tool_calls.function.name;
|
|
@@ -518,24 +542,28 @@ function resolveCohereThinking({
|
|
|
518
542
|
}
|
|
519
543
|
|
|
520
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.
|
|
521
546
|
const cohereUsageSchema = () =>
|
|
522
547
|
z.looseObject({
|
|
523
548
|
billed_units: z
|
|
524
549
|
.looseObject({
|
|
525
|
-
input_tokens: z.number(),
|
|
526
|
-
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(),
|
|
527
558
|
})
|
|
528
559
|
.nullish(),
|
|
529
|
-
tokens: z.looseObject({
|
|
530
|
-
input_tokens: z.number(),
|
|
531
|
-
output_tokens: z.number(),
|
|
532
|
-
}),
|
|
533
560
|
cached_tokens: z.number().nullish(),
|
|
534
561
|
});
|
|
535
562
|
|
|
536
563
|
const cohereChatResponseSchema = lazySchema(() =>
|
|
537
564
|
zodSchema(
|
|
538
565
|
z.object({
|
|
566
|
+
id: z.string().nullish(),
|
|
539
567
|
generation_id: z.string().nullish(),
|
|
540
568
|
message: z.object({
|
|
541
569
|
role: z.string(),
|
|
@@ -566,30 +594,10 @@ const cohereChatResponseSchema = lazySchema(() =>
|
|
|
566
594
|
}),
|
|
567
595
|
)
|
|
568
596
|
.nullish(),
|
|
569
|
-
citations: z
|
|
570
|
-
.array(
|
|
571
|
-
z.object({
|
|
572
|
-
start: z.number(),
|
|
573
|
-
end: z.number(),
|
|
574
|
-
text: z.string(),
|
|
575
|
-
sources: z.array(
|
|
576
|
-
z.object({
|
|
577
|
-
type: z.string().optional(),
|
|
578
|
-
id: z.string().optional(),
|
|
579
|
-
document: z.object({
|
|
580
|
-
id: z.string().optional(),
|
|
581
|
-
text: z.string(),
|
|
582
|
-
title: z.string(),
|
|
583
|
-
}),
|
|
584
|
-
}),
|
|
585
|
-
),
|
|
586
|
-
type: z.string().optional(),
|
|
587
|
-
}),
|
|
588
|
-
)
|
|
589
|
-
.nullish(),
|
|
597
|
+
citations: z.array(cohereCitationSchema).nullish(),
|
|
590
598
|
}),
|
|
591
599
|
finish_reason: z.string(),
|
|
592
|
-
usage: cohereUsageSchema(),
|
|
600
|
+
usage: cohereUsageSchema().nullish(),
|
|
593
601
|
}),
|
|
594
602
|
),
|
|
595
603
|
);
|
|
@@ -599,8 +607,22 @@ const cohereChatResponseSchema = lazySchema(() =>
|
|
|
599
607
|
const cohereChatChunkSchema = lazySchema(() =>
|
|
600
608
|
zodSchema(
|
|
601
609
|
z.discriminatedUnion('type', [
|
|
610
|
+
// `citation-start` events can arrive without citations, and a single
|
|
611
|
+
// citation may be sent instead of an array.
|
|
602
612
|
z.object({
|
|
603
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(),
|
|
604
626
|
}),
|
|
605
627
|
z.object({
|
|
606
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
|
+
}
|
|
@@ -2,13 +2,13 @@ import type { LanguageModelV4Usage } from '@ai-sdk/provider';
|
|
|
2
2
|
import { createNullLanguageModelUsage } from '@ai-sdk/provider-utils';
|
|
3
3
|
|
|
4
4
|
export type CohereUsageTokens = {
|
|
5
|
-
input_tokens
|
|
6
|
-
output_tokens
|
|
5
|
+
input_tokens?: number | null;
|
|
6
|
+
output_tokens?: number | null;
|
|
7
7
|
};
|
|
8
8
|
|
|
9
9
|
export type CohereUsage = {
|
|
10
10
|
billed_units?: CohereUsageTokens | null;
|
|
11
|
-
tokens
|
|
11
|
+
tokens?: CohereUsageTokens | null;
|
|
12
12
|
cached_tokens?: number | null;
|
|
13
13
|
};
|
|
14
14
|
|
|
@@ -19,16 +19,20 @@ export function convertCohereUsage(
|
|
|
19
19
|
return createNullLanguageModelUsage();
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
22
|
+
// `tokens` is the only measure that matches the unified token counts.
|
|
23
|
+
// `billed_units` count billed units rather than tokens, so they are kept in
|
|
24
|
+
// `raw` only and never used as token counts or reduced by cached tokens.
|
|
25
|
+
const inputTokens = usage.tokens?.input_tokens ?? undefined;
|
|
26
|
+
const outputTokens = usage.tokens?.output_tokens ?? undefined;
|
|
25
27
|
const cacheReadTokens = usage.cached_tokens ?? undefined;
|
|
26
28
|
|
|
27
29
|
return {
|
|
28
30
|
inputTokens: {
|
|
29
31
|
total: inputTokens,
|
|
30
32
|
noCache:
|
|
31
|
-
|
|
33
|
+
inputTokens != null && cacheReadTokens != null
|
|
34
|
+
? inputTokens - cacheReadTokens
|
|
35
|
+
: inputTokens,
|
|
32
36
|
cacheRead: cacheReadTokens,
|
|
33
37
|
cacheWrite: undefined,
|
|
34
38
|
},
|