Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

embedding-adapter.test.ts

455 lines14.3 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
3import {
4 CohereEmbeddingAdapter,
5 cohereEmbedding,
6 createCohereEmbedding,
7} from '../src/adapters/embedding'
8​
9const testLogger = resolveDebugOption(false)
10​
11const EMBED_URL = 'https://api.cohere.com/v2/embed'
12​
13interface CohereEmbedResponseInit {
14 vectors: Array<Array<number>>
15 inputTokens?: number
17​
18function embedResponse({
19 vectors,
20 inputTokens,
21}: CohereEmbedResponseInit): Response {
22 return new Response(
23 JSON.stringify({
24 id: 'cohere-test-id',
25 embeddings: { float: vectors },
26 ...(inputTokens !== undefined
27 ? { meta: { billed_units: { input_tokens: inputTokens } } }
28 : {}),
29 }),
30 { status: 200, headers: { 'content-type': 'application/json' } },
31 )
33​
34const fetchMock = vi.fn()
35vi.stubGlobal('fetch', fetchMock)
36​
37function lastRequestBody(): any {
38 const call = fetchMock.mock.calls.at(-1)
39 if (!call) throw new Error('fetch was not called')
40 return JSON.parse(call[1].body)
42​
43function nthCall(index: number): [any, any] {
44 const call = fetchMock.mock.calls[index]
45 if (!call) throw new Error('fetch was not called')
46 return [call[0], call[1]]
48​
49beforeEach(() => {
50 fetchMock.mockReset()
51})
52​
53afterEach(() => {
54 vi.unstubAllEnvs()
55})
56​
57describe('Cohere Embedding Adapter', () => {
58 describe('createCohereEmbedding', () => {
59 it('creates an adapter with the provided API key', () => {
60 const adapter = createCohereEmbedding('embed-v4.0', 'test-api-key')
61 expect(adapter).toBeInstanceOf(CohereEmbeddingAdapter)
62 expect(adapter.kind).toBe('embedding')
63 expect(adapter.name).toBe('cohere')
64 expect(adapter.model).toBe('embed-v4.0')
65 })
66 })
67​
68 describe('cohereEmbedding', () => {
69 it('reads the API key from COHERE_API_KEY', () => {
70 vi.stubEnv('COHERE_API_KEY', 'env-api-key')
71 const adapter = cohereEmbedding('embed-v4.0')
72 expect(adapter).toBeInstanceOf(CohereEmbeddingAdapter)
73 expect(adapter.model).toBe('embed-v4.0')
74 })
75​
76 it('throws when COHERE_API_KEY is not set', () => {
77 vi.stubEnv('COHERE_API_KEY', '')
78 expect(() => cohereEmbedding('embed-v4.0')).toThrow('COHERE_API_KEY')
79 })
80 })
81​
82 describe('createEmbeddings', () => {
83 it('sends texts as a batch with auth headers and maps the response', async () => {
84 fetchMock.mockResolvedValue(
85 embedResponse({
86 vectors: [
87 [0.1, 0.2],
88 [0.3, 0.4],
89 ],
90 inputTokens: 7,
91 }),
92 )
93 const adapter = createCohereEmbedding('embed-v4.0', 'test-key')
94​
95 const result = await adapter.createEmbeddings({
96 model: 'embed-v4.0',
97 input: ['a red guitar', { type: 'text', content: 'a blue drum kit' }],
98 modelOptions: { inputType: 'search_document' },
99 logger: testLogger,
100 })
101​
102 expect(fetchMock).toHaveBeenCalledTimes(1)
103 const [url, init] = nthCall(0)
104 expect(url).toBe(EMBED_URL)
105 expect(init.method).toBe('POST')
106 expect(init.headers).toMatchObject({
107 Authorization: 'Bearer test-key',
108 'Content-Type': 'application/json',
109 })
110​
111 expect(lastRequestBody()).toEqual({
112 model: 'embed-v4.0',
113 inputs: [
114 { content: [{ type: 'text', text: 'a red guitar' }] },
115 { content: [{ type: 'text', text: 'a blue drum kit' }] },
116 ],
117 input_type: 'search_document',
118 embedding_types: ['float'],
119 })
120​
121 expect(result.embeddings).toEqual([
122 { vector: [0.1, 0.2], index: 0 },
123 { vector: [0.3, 0.4], index: 1 },
124 ])
125 expect(result.usage).toEqual({
126 promptTokens: 7,
127 completionTokens: 0,
128 totalTokens: 7,
129 })
130 expect(result.model).toBe('embed-v4.0')
131 })
132​
133 it('honors baseUrl and custom headers', async () => {
134 fetchMock.mockResolvedValue(embedResponse({ vectors: [[0.1]] }))
135 const adapter = createCohereEmbedding('embed-v4.0', 'test-key', {
136 baseUrl: 'https://proxy.example.com',
137 headers: { 'X-Custom': 'yes' },
138 })
139​
140 await adapter.createEmbeddings({
141 model: 'embed-v4.0',
142 input: ['hello'],
143 modelOptions: { inputType: 'search_query' },
144 logger: testLogger,
145 })
146​
147 const [url, init] = nthCall(0)
148 expect(url).toBe('https://proxy.example.com/v2/embed')
149 expect(init.headers).toMatchObject({ 'X-Custom': 'yes' })
150 })
151​
152 it('maps a data-source image to a data: URI content part', async () => {
153 fetchMock.mockResolvedValue(embedResponse({ vectors: [[0.5]] }))
154 const adapter = createCohereEmbedding('embed-v4.0', 'test-key')
155​
156 await adapter.createEmbeddings({
157 model: 'embed-v4.0',
158 input: [
159 {
160 type: 'image',
161 source: { type: 'data', value: 'aGk=', mimeType: 'image/png' },
162 },
163 ],
164 modelOptions: { inputType: 'search_document' },
165 logger: testLogger,
166 })
167​
168 expect(lastRequestBody().inputs).toEqual([
169 {
170 content: [
171 {
172 type: 'image_url',
173 image_url: { url: 'data:image/png;base64,aGk=' },
174 },
175 ],
176 },
177 ])
178 })
179​
180 it('passes url-source data: URIs through unchanged', async () => {
181 fetchMock.mockResolvedValue(embedResponse({ vectors: [[0.5]] }))
182 const adapter = createCohereEmbedding('embed-v4.0', 'test-key')
183​
184 await adapter.createEmbeddings({
185 model: 'embed-v4.0',
186 input: [
187 {
188 type: 'image',
189 source: { type: 'url', value: 'data:image/jpeg;base64,aGk=' },
190 },
191 ],
192 modelOptions: { inputType: 'search_document' },
193 logger: testLogger,
194 })
195​
196 expect(lastRequestBody().inputs[0].content[0].image_url.url).toBe(
197 'data:image/jpeg;base64,aGk=',
198 )
199 })
200​
201 it('sends a fused text+image item as one content array (one vector)', async () => {
202 fetchMock.mockResolvedValue(embedResponse({ vectors: [[0.9]] }))
203 const adapter = createCohereEmbedding('embed-v4.0', 'test-key')
204​
205 const result = await adapter.createEmbeddings({
206 model: 'embed-v4.0',
207 input: [
208 [
209 { type: 'text', content: 'product photo' },
210 {
211 type: 'image',
212 source: { type: 'data', value: 'aGk=', mimeType: 'image/png' },
213 },
214 ],
215 ],
216 modelOptions: { inputType: 'search_document' },
217 logger: testLogger,
218 })
219​
220 expect(lastRequestBody().inputs).toEqual([
221 {
222 content: [
223 { type: 'text', text: 'product photo' },
224 {
225 type: 'image_url',
226 image_url: { url: 'data:image/png;base64,aGk=' },
227 },
228 ],
229 },
230 ])
231 expect(result.embeddings).toEqual([{ vector: [0.9], index: 0 }])
232 })
233​
234 it('maps inputType, truncate, and dimensions onto the request body', async () => {
235 fetchMock.mockResolvedValue(embedResponse({ vectors: [[0.1]] }))
236 const adapter = createCohereEmbedding('embed-v4.0', 'test-key')
237​
238 await adapter.createEmbeddings({
239 model: 'embed-v4.0',
240 input: ['hello'],
241 dimensions: 1024,
242 modelOptions: { inputType: 'clustering', truncate: 'END' },
243 logger: testLogger,
244 })
245​
246 const body = lastRequestBody()
247 expect(body.input_type).toBe('clustering')
248 expect(body.truncate).toBe('END')
249 expect(body.output_dimension).toBe(1024)
250 })
251​
252 it('omits truncate and output_dimension when not provided', async () => {
253 fetchMock.mockResolvedValue(embedResponse({ vectors: [[0.1]] }))
254 const adapter = createCohereEmbedding('embed-v4.0', 'test-key')
255​
256 await adapter.createEmbeddings({
257 model: 'embed-v4.0',
258 input: ['hello'],
259 modelOptions: { inputType: 'search_query' },
260 logger: testLogger,
261 })
262​
263 const body = lastRequestBody()
264 expect('truncate' in body).toBe(false)
265 expect('output_dimension' in body).toBe(false)
266 })
267​
268 it('always pins embedding_types to ["float"]', async () => {
269 fetchMock.mockResolvedValue(embedResponse({ vectors: [[0.1]] }))
270 const adapter = createCohereEmbedding('embed-v4.0', 'test-key')
271​
272 await adapter.createEmbeddings({
273 model: 'embed-v4.0',
274 input: ['hello'],
275 modelOptions: {
276 inputType: 'search_document',
277 embeddingTypes: ['float'],
278 },
279 logger: testLogger,
280 })
281​
282 expect(lastRequestBody().embedding_types).toEqual(['float'])
283 })
284​
285 it('throws when modelOptions.inputType is missing', async () => {
286 const adapter = createCohereEmbedding('embed-v4.0', 'test-key')
287​
288 await expect(
289 adapter.createEmbeddings({
290 model: 'embed-v4.0',
291 input: ['hello'],
292 logger: testLogger,
293 }),
294 ).rejects.toThrow('modelOptions.inputType')
295 expect(fetchMock).not.toHaveBeenCalled()
296 })
297​
298 it('rejects http(s) image URLs by default', async () => {
299 const adapter = createCohereEmbedding('embed-v4.0', 'test-key')
300​
301 await expect(
302 adapter.createEmbeddings({
303 model: 'embed-v4.0',
304 input: [
305 {
306 type: 'image',
307 source: { type: 'url', value: 'https://example.com/cat.png' },
308 },
309 ],
310 modelOptions: { inputType: 'search_document' },
311 logger: testLogger,
312 }),
313 ).rejects.toThrow('Cohere does not fetch remote image URLs')
314 expect(fetchMock).not.toHaveBeenCalled()
315 })
316​
317 it('downloads http(s) image URLs when allowUrlFetch is enabled', async () => {
318 const imageUrl = 'https://example.com/cat.png'
319 // "Hello" → base64 "SGVsbG8="
320 const imageBytes = new Uint8Array([72, 101, 108, 108, 111])
321 fetchMock.mockImplementation((url: unknown) => {
322 if (url === imageUrl) {
323 return Promise.resolve(
324 new Response(imageBytes, {
325 status: 200,
326 headers: { 'content-type': 'image/png' },
327 }),
328 )
329 }
330 return Promise.resolve(embedResponse({ vectors: [[0.7]] }))
331 })
332 const adapter = createCohereEmbedding('embed-v4.0', 'test-key', {
333 allowUrlFetch: true,
334 })
335​
336 const result = await adapter.createEmbeddings({
337 model: 'embed-v4.0',
338 input: [{ type: 'image', source: { type: 'url', value: imageUrl } }],
339 modelOptions: { inputType: 'search_document' },
340 logger: testLogger,
341 })
342​
343 expect(fetchMock).toHaveBeenCalledTimes(2)
344 expect(fetchMock).toHaveBeenCalledWith(
345 imageUrl,
346 expect.objectContaining({ signal: expect.any(AbortSignal) }),
347 )
348 expect(lastRequestBody().inputs[0].content[0].image_url.url).toBe(
349 'data:image/png;base64,SGVsbG8=',
350 )
351 expect(result.embeddings).toEqual([{ vector: [0.7], index: 0 }])
352 })
353​
354 it('rejects private/loopback image URLs even when allowUrlFetch is enabled', async () => {
355 const adapter = createCohereEmbedding('embed-v4.0', 'test-key', {
356 allowUrlFetch: true,
357 })
358​
359 for (const value of [
360 'http://127.0.0.1/secret.png',
361 'http://localhost/secret.png',
362 'http://169.254.169.254/latest/meta-data/',
363 'http://192.168.1.1/img.png',
364 'http://10.0.0.5/img.png',
365 'http://172.16.0.1/img.png',
366 ]) {
367 await expect(
368 adapter.createEmbeddings({
369 model: 'embed-v4.0',
370 input: [{ type: 'image', source: { type: 'url', value } }],
371 modelOptions: { inputType: 'search_document' },
372 logger: testLogger,
373 }),
374 ).rejects.toThrow('Refusing to fetch internal or private URL')
375 }
376 expect(fetchMock).not.toHaveBeenCalled()
377 })
378​
379 it('passes an AbortSignal on the Cohere API fetch', async () => {
380 fetchMock.mockResolvedValue(embedResponse({ vectors: [[0.1]] }))
381 const adapter = createCohereEmbedding('embed-v4.0', 'test-key')
382​
383 await adapter.createEmbeddings({
384 model: 'embed-v4.0',
385 input: ['hello'],
386 modelOptions: { inputType: 'search_document' },
387 logger: testLogger,
388 })
389​
390 const [, init] = nthCall(0)
391 expect(init.signal).toBeInstanceOf(AbortSignal)
392 })
393​
394 it('omits usage when billed_units.input_tokens is absent', async () => {
395 fetchMock.mockResolvedValue(embedResponse({ vectors: [[0.1]] }))
396 const adapter = createCohereEmbedding('embed-v4.0', 'test-key')
397​
398 const result = await adapter.createEmbeddings({
399 model: 'embed-v4.0',
400 input: ['hello'],
401 modelOptions: { inputType: 'search_document' },
402 logger: testLogger,
403 })
404​
405 expect(result.usage).toBeUndefined()
406 })
407​
408 it('throws when the embedding count does not match the input count', async () => {
409 fetchMock.mockResolvedValue(embedResponse({ vectors: [[0.1]] }))
410 const adapter = createCohereEmbedding('embed-v4.0', 'test-key')
411​
412 await expect(
413 adapter.createEmbeddings({
414 model: 'embed-v4.0',
415 input: ['one', 'two'],
416 modelOptions: { inputType: 'search_document' },
417 logger: testLogger,
418 }),
419 ).rejects.toThrow('returned 1 embeddings for 2 inputs')
420 })
421​
422 it('throws a clear error with the API message on non-2xx responses', async () => {
423 fetchMock.mockResolvedValue(
424 new Response(JSON.stringify({ message: 'invalid api token' }), {
425 status: 401,
426 headers: { 'content-type': 'application/json' },
427 }),
428 )
429 const adapter = createCohereEmbedding('embed-v4.0', 'bad-key')
430​
431 await expect(
432 adapter.createEmbeddings({
433 model: 'embed-v4.0',
434 input: ['hello'],
435 modelOptions: { inputType: 'search_document' },
436 logger: testLogger,
437 }),
438 ).rejects.toThrow('Cohere embed failed (401): invalid api token')
439 })
440​
441 it('falls back to the raw body text for non-JSON error responses', async () => {
442 fetchMock.mockResolvedValue(new Response('Bad Gateway', { status: 502 }))
443 const adapter = createCohereEmbedding('embed-v4.0', 'test-key')
444​
445 await expect(
446 adapter.createEmbeddings({
447 model: 'embed-v4.0',
448 input: ['hello'],
449 modelOptions: { inputType: 'search_document' },
450 logger: testLogger,
451 }),
452 ).rejects.toThrow('Cohere embed failed (502): Bad Gateway')
453 })
454 })
455})