Open History to see the last commit
1import { BaseEmbeddingAdapter } from '@tanstack/ai/adapters'
2import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
3import { arrayBufferToBase64, generateId } from '@tanstack/ai-utils'
4import {
5 isFileSource,
6 resolveEmbeddingInput,
7 unsupportedFileSourceError,
8} from '@tanstack/ai'
9import { getCohereApiKeyFromEnv, resolveCohereTransport } from '../utils/client'
10import type {
11 EmbeddingOptions,
12 EmbeddingResult,
13 ImagePart,
14 TokenUsage,
15} from '@tanstack/ai'
16import type {
17 CohereEmbeddingModel,
18 CohereEmbeddingModelInputModalitiesByName,
19 CohereEmbeddingModelProviderOptionsByName,
20} from '../model-meta'
21import type { CohereEmbeddingProviderOptions } from '../embedding/embedding-provider-options'
22import type { CohereClientConfig } from '../utils/client'
23
24/**
25 * Configuration for Cohere embedding adapter.
26 */
27export interface CohereEmbeddingConfig extends CohereClientConfig {}
28
29const DEFAULT_TIMEOUT_MS = 30_000
30
31/**
32 * Returns true when `url` is malformed, non-http(s), or targets a private /
33 * loopback / link-local host. Used to block SSRF via `allowUrlFetch`.
34 */
35function isPrivateOrInternalUrl(url: string): boolean {
36 let parsed: URL
37 try {
38 parsed = new URL(url)
39 } catch {
40 return true
41 }
42 if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
43 return true
44 }
45 const host = parsed.hostname.toLowerCase()
46 if (
47 host === 'localhost' ||
48 host.endsWith('.localhost') ||
49 host === '::1' ||
50 host === '[::1]' ||
51 host.startsWith('127.') ||
52 host.startsWith('10.') ||
53 host.startsWith('192.168.') ||
54 host.startsWith('169.254.') ||
55 /^172\.(1[6-9]|2\d|3[01])\./.test(host)
56 ) {
57 return true
58 }
59 return false
60}
61
62async function fetchWithTimeout(
63 url: string,
64 init: RequestInit | undefined,
65 timeoutMs: number,
66): Promise<Response> {
67 const controller = new AbortController()
68 const timeoutId = setTimeout(() => controller.abort(), timeoutMs)
69 try {
70 return await fetch(url, { ...init, signal: controller.signal })
71 } finally {
72 clearTimeout(timeoutId)
73 }
74}
75
76/** One content part of a Cohere v2/embed fused input. */
77type CohereEmbedContentPart =
78 | { type: 'text'; text: string }
79 | { type: 'image_url'; image_url: { url: string } }
80
81/** Wire shape of the Cohere v2/embed request body. */
82interface CohereEmbedRequestBody {
83 model: string
84 inputs: Array<{ content: Array<CohereEmbedContentPart> }>
85 input_type: CohereEmbeddingProviderOptions['inputType']
86 embedding_types: ['float']
87 truncate?: 'NONE' | 'START' | 'END'
88 output_dimension?: number
89}
90
91/** Wire shape of the Cohere v2/embed response (fields the adapter reads). */
92interface CohereEmbedResponse {
93 id?: string
94 embeddings?: {
95 float?: Array<Array<number>>
96 }
97 meta?: {
98 billed_units?: {
99 input_tokens?: number
100 images?: number
101 }
102 }
103}
104
105/**
106 * Cohere Embedding Adapter
107 *
108 * Tree-shakeable adapter for Cohere multimodal embeddings (embed-v4.0),
109 * implemented with plain `fetch` against the v2/embed endpoint — no Cohere
110 * SDK dependency.
111 *
112 * Features:
113 * - Batch embedding (one request for the whole input array)
114 * - Multimodal inputs: text, images, and fused text+image items (one vector
115 * per input item)
116 * - Matryoshka dimension reduction via the top-level `dimensions` option
117 * (mapped to Cohere's `output_dimension`)
118 */
119export class CohereEmbeddingAdapter<
120 TModel extends CohereEmbeddingModel,
121> extends BaseEmbeddingAdapter<
122 TModel,
123 CohereEmbeddingProviderOptions,
124 CohereEmbeddingModelProviderOptionsByName,
125 CohereEmbeddingModelInputModalitiesByName
126> {
127 readonly name = 'cohere' as const
128
129 protected clientConfig: CohereEmbeddingConfig
130
131 constructor(config: CohereEmbeddingConfig, model: TModel) {
132 super(model, {})
133 this.clientConfig = config
134 }
135
136 async createEmbeddings(
137 options: EmbeddingOptions<CohereEmbeddingProviderOptions>,
138 ): Promise<EmbeddingResult> {
139 const { model, logger, modelOptions } = options
140
141 try {
142 // The provider options type makes `modelOptions` required at the
143 // embed() call site; this guard covers untyped/dynamic callers.
144 const inputType: CohereEmbeddingProviderOptions['inputType'] | undefined =
145 modelOptions?.inputType
146 if (!inputType) {
147 throw new Error(
148 `Cohere embeddings require modelOptions.inputType ('search_document' | 'search_query' | 'classification' | 'clustering').`,
149 )
150 }
151
152 const resolved = resolveEmbeddingInput(options.input)
153 const inputs = await Promise.all(
154 resolved.map(async (item) => {
155 const content: Array<CohereEmbedContentPart> = item.texts.map(
156 (text) => ({ type: 'text', text }),
157 )
158 for (const image of item.images) {
159 content.push({
160 type: 'image_url',
161 image_url: { url: await this.resolveImageUrl(image) },
162 })
163 }
164 return { content }
165 }),
166 )
167
168 // embedding_types is pinned to ['float'] (overriding any disagreeing
169 // modelOptions.embeddingTypes) so vectors are always number[].
170 const body: CohereEmbedRequestBody = {
171 model,
172 inputs,
173 input_type: inputType,
174 embedding_types: ['float'],
175 }
176 const truncate = modelOptions?.truncate
177 if (truncate !== undefined) {
178 body.truncate = truncate
179 }
180 if (options.dimensions !== undefined) {
181 body.output_dimension = options.dimensions
182 }
183
184 logger.request(
185 `activity=embed provider=${this.name} model=${model} inputs=${inputs.length}`,
186 { provider: this.name, model },
187 )
188
189 const timeoutMs = this.clientConfig.timeout ?? DEFAULT_TIMEOUT_MS
190 const transport = resolveCohereTransport(this.clientConfig)
191 const response = await fetchWithTimeout(
192 `${transport.baseUrl}/v2/embed`,
193 {
194 method: 'POST',
195 headers: {
196 Authorization: `Bearer ${this.clientConfig.apiKey}`,
197 'Content-Type': 'application/json',
198 ...transport.headers,
199 },
200 body: JSON.stringify(body),
201 },
202 timeoutMs,
203 )
204
205 if (!response.ok) {
206 const bodyText = await response.text()
207 let message = bodyText
208 try {
209 const parsed: unknown = JSON.parse(bodyText)
210 if (
211 typeof parsed === 'object' &&
212 parsed !== null &&
213 'message' in parsed &&
214 typeof parsed.message === 'string'
215 ) {
216 message = parsed.message
217 }
218 } catch {
219 // Not JSON — fall back to the raw body text.
220 }
221 throw new Error(`Cohere embed failed (${response.status}): ${message}`)
222 }
223
224 const data = (await response.json()) as CohereEmbedResponse
225
226 const vectors = data.embeddings?.float
227 if (!vectors) {
228 throw new Error(
229 'Cohere embed response did not include float embeddings',
230 )
231 }
232 if (vectors.length !== inputs.length) {
233 throw new Error(
234 `Cohere embed returned ${vectors.length} embeddings for ${inputs.length} inputs`,
235 )
236 }
237
238 const result: EmbeddingResult = {
239 id: generateId(this.name),
240 model,
241 embeddings: vectors.map((vector, index) => ({ vector, index })),
242 }
243
244 const inputTokens = data.meta?.billed_units?.input_tokens
245 if (inputTokens !== undefined) {
246 const usage: TokenUsage = {
247 promptTokens: inputTokens,
248 completionTokens: 0,
249 totalTokens: inputTokens,
250 }
251 result.usage = usage
252 }
253
254 return result
255 } catch (error: unknown) {
256 logger.errors(`${this.name}.createEmbeddings fatal`, {
257 error: toRunErrorPayload(error, `${this.name}.createEmbeddings failed`),
258 source: `${this.name}.createEmbeddings`,
259 })
260 throw error
261 }
262 }
263
264 /**
265 * Resolves an image part to a URL Cohere accepts. Cohere does not fetch
266 * remote image URLs, so everything is normalized to a `data:` URI unless
267 * the caller already provided one.
268 */
269 protected async resolveImageUrl(image: ImagePart): Promise<string> {
270 const source = image.source
271 if (isFileSource(source)) throw unsupportedFileSourceError(this.name)
272
273 if (source.type === 'data') {
274 return `data:${source.mimeType};base64,${source.value}`
275 }
276
277 if (source.value.startsWith('data:')) {
278 return source.value
279 }
280
281 if (!this.clientConfig.allowUrlFetch) {
282 throw new Error(
283 'Cohere does not fetch remote image URLs; pass base64 data or a data: URI (or enable config.allowUrlFetch to have the adapter download it)',
284 )
285 }
286
287 if (isPrivateOrInternalUrl(source.value)) {
288 throw new Error(
289 `Refusing to fetch internal or private URL for Cohere embedding: ${source.value}`,
290 )
291 }
292
293 const response = await fetchWithTimeout(
294 source.value,
295 undefined,
296 this.clientConfig.timeout ?? DEFAULT_TIMEOUT_MS,
297 )
298 if (!response.ok) {
299 throw new Error(
300 `Failed to fetch image URL for Cohere embedding (${response.status}): ${source.value}`,
301 )
302 }
303 const mimeType =
304 response.headers.get('content-type') ??
305 source.mimeType ??
306 'application/octet-stream'
307 const base64 = arrayBufferToBase64(await response.arrayBuffer())
308 return `data:${mimeType};base64,${base64}`
309 }
310}
311
312/**
313 * Creates a Cohere embedding adapter with explicit API key.
314 * Type resolution happens here at the call site.
315 *
316 * @param model - The model name (e.g., 'embed-v4.0')
317 * @param apiKey - Your Cohere API key
318 * @param config - Optional additional configuration
319 * @returns Configured Cohere embedding adapter instance with resolved types
320 *
321 * @example
322 * ```typescript
323 * const adapter = createCohereEmbedding('embed-v4.0', 'api_key');
324 *
325 * const result = await embed({
326 * adapter,
327 * input: 'a red guitar',
328 * modelOptions: { inputType: 'search_document' }
329 * });
330 * ```
331 */
332export function createCohereEmbedding<TModel extends CohereEmbeddingModel>(
333 model: TModel,
334 apiKey: string,
335 config?: Omit<CohereEmbeddingConfig, 'apiKey'>,
336): CohereEmbeddingAdapter<TModel> {
337 return new CohereEmbeddingAdapter({ apiKey, ...config }, model)
338}
339
340/**
341 * Creates a Cohere embedding adapter using the `COHERE_API_KEY` environment variable.
342 * Type resolution happens here at the call site.
343 *
344 * Looks for `COHERE_API_KEY` in:
345 * - `process.env` (Node.js)
346 * - `window.env` (Browser with injected env)
347 *
348 * @param model - The model name (e.g., 'embed-v4.0')
349 * @param config - Optional configuration (excluding apiKey which is auto-detected)
350 * @returns Configured Cohere embedding adapter instance with resolved types
351 * @throws Error if COHERE_API_KEY is not found in environment
352 *
353 * @example
354 * ```typescript
355 * // Automatically uses COHERE_API_KEY from environment
356 * const adapter = cohereEmbedding('embed-v4.0');
357 *
358 * const result = await embed({
359 * adapter,
360 * input: ['a red guitar', 'a blue drum kit'],
361 * modelOptions: { inputType: 'search_query' },
362 * dimensions: 1024
363 * });
364 *
365 * console.log(result.embeddings[0].vector)
366 * ```
367 */
368export function cohereEmbedding<TModel extends CohereEmbeddingModel>(
369 model: TModel,
370 config?: Omit<CohereEmbeddingConfig, 'apiKey'>,
371): CohereEmbeddingAdapter<TModel> {
372 const apiKey = getCohereApiKeyFromEnv()
373 return createCohereEmbedding(model, apiKey, config)
374}