Open History to see the last commit
1---
2title: Embeddings
3id: embeddings
4order: 1
5description: "Turn text and images into vectors with embed(). Use them for semantic search, RAG, and clustering with OpenAI, Cohere, Gemini, Mistral, Amazon Bedrock, Ollama, or Vercel AI Gateway."
6keywords:
7 - tanstack ai
8 - embeddings
9 - embedding vectors
10 - multimodal embeddings
11 - semantic search
12 - rag
13 - embed
14 - openai
15 - cohere
16 - gemini
17 - mistral
18 - bedrock
19 - ollama
20 - vercel ai gateway
21---
22
23`embed()` turns text into a vector. Search, RAG, and clustering then compare those vectors.
24
25Multimodal models also embed images.
26
27## Quick setup
28
291. Install the core package and an adapter:
30
31<!-- ::start:tabs variant="package-manager" mode="install" -->
32
33react: @tanstack/ai @tanstack/ai-openai
34vue: @tanstack/ai @tanstack/ai-openai
35solid: @tanstack/ai @tanstack/ai-openai
36svelte: @tanstack/ai @tanstack/ai-openai
37preact: @tanstack/ai @tanstack/ai-openai
38angular: @tanstack/ai @tanstack/ai-openai
39vanilla: @tanstack/ai @tanstack/ai-openai
40octane: @tanstack/ai @tanstack/ai-openai
41
42<!-- ::end:tabs -->
43
442. Put your key on the server. The adapter reads it at runtime:
45
46```bash
47OPENAI_API_KEY=your-openai-api-key
48```
49
503. Call `embed()` on the server:
51
52```typescript
53import { embed } from "@tanstack/ai";
54import { openaiEmbedding } from "@tanstack/ai-openai";
55
56const result = await embed({
57 adapter: openaiEmbedding("text-embedding-3-small"),
58 input: ["a red guitar", "a blue drum kit", "a vintage synthesizer"],
59});
60
61for (const embedding of result.embeddings) {
62 console.log(embedding.index, embedding.vector.length);
63}
64```
65
66You now have one `number[]` vector per input string. Store them in your vector database.
67
68## How it works
69
70- `input` is one item or an array of items.
71- Each item gives exactly one vector.
72- `result.embeddings` keeps the input order. Each entry has an `index` and a `vector`.
73- Every provider uses the same `embed()` call. To change provider, change the adapter.
74
75## Providers
76
77| Provider | Adapter | Models | Input |
78| ----------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------- | ------------ |
79| OpenAI | `openaiEmbedding` (`@tanstack/ai-openai`) | `text-embedding-3-small`, `text-embedding-3-large` | text |
80| Cohere | `cohereEmbedding` (`@tanstack/ai-cohere`) | `embed-v4.0` | text + image |
81| Google Gemini | `geminiEmbedding` (`@tanstack/ai-gemini`) | `gemini-embedding-001` | text |
82| Mistral | `mistralEmbedding` (`@tanstack/ai-mistral`) | `mistral-embed`, `codestral-embed` | text |
83| Amazon Bedrock | `bedrockEmbedding` (`@tanstack/ai-bedrock`) | Titan Text Embeddings V2 (text), Titan Multimodal Embeddings G1 (text + image), Cohere Embed v3 (text) | text, or text + image |
84| Ollama | `ollamaEmbedding` (`@tanstack/ai-ollama`) | `nomic-embed-text`, `mxbai-embed-large`, and any local embedding model | text |
85| Vercel AI Gateway | `vercelGatewayEmbedding` (`@tanstack/ai-vercel-gateway`) | OpenAI-compatible models such as `openai/text-embedding-3-small` | text |
86
87Vercel AI Gateway takes a `creator/model` id:
88
89```typescript
90import { embed } from "@tanstack/ai";
91import { vercelGatewayEmbedding } from "@tanstack/ai-vercel-gateway";
92
93const result = await embed({
94 adapter: vercelGatewayEmbedding("openai/text-embedding-3-small"),
95 input: "a red guitar",
96});
97```
98
99## Pick the vector size
100
101Some models (Matryoshka models) let you choose the number of dimensions. Pass `dimensions`:
102
103```typescript
104import { embed } from "@tanstack/ai";
105import { openaiEmbedding } from "@tanstack/ai-openai";
106
107const result = await embed({
108 adapter: openaiEmbedding("text-embedding-3-large"),
109 input: "a red guitar",
110 dimensions: 1024,
111});
112```
113
114Fixed-size models (for example `mistral-embed` or Ollama models) throw a runtime error when you set `dimensions`.
115
116## Embed documents and queries differently
117
118Retrieval models give better results when they know if the text is a document or a query.
119
120Cohere requires an `inputType`. The types make `modelOptions` required for this model:
121
122```typescript
123import { embed } from "@tanstack/ai";
124import { cohereEmbedding } from "@tanstack/ai-cohere";
125
126// Index time: embed the documents
127const docs = await embed({
128 adapter: cohereEmbedding("embed-v4.0"),
129 input: ["doc one", "doc two"],
130 modelOptions: { inputType: "search_document" },
131});
132
133// Query time: embed the query
134const query = await embed({
135 adapter: cohereEmbedding("embed-v4.0"),
136 input: "which doc mentions one?",
137 modelOptions: { inputType: "search_query" },
138});
139```
140
141Gemini has an optional `taskType` for the same purpose:
142
143```typescript
144import { embed } from "@tanstack/ai";
145import { geminiEmbedding } from "@tanstack/ai-gemini";
146
147const result = await embed({
148 adapter: geminiEmbedding("gemini-embedding-001"),
149 input: "a red guitar",
150 modelOptions: { taskType: "RETRIEVAL_DOCUMENT" },
151});
152```
153
154## Embed images
155
156Multimodal models embed images, or an image and text together as one vector. Image items use the same content-part shape as chat messages.
157
158The types narrow the accepted items per model. An image sent to a text-only model is a type error.
159
160Each item in the top-level `input` array gives one vector:
161
162- A string or a text part embeds that text.
163- An image part embeds that image.
164- A nested array of parts (`[textPart, imagePart]`) fuses the parts into one vector.
165
166So `[textPart, imagePart]` gives two vectors, and `[[textPart, imagePart]]` gives one fused vector.
167
168```typescript
169import { embed } from "@tanstack/ai";
170import { cohereEmbedding } from "@tanstack/ai-cohere";
171
172const productPhoto = "iVBORw0KGgo..."; // base64 image data
173
174const result = await embed({
175 adapter: cohereEmbedding("embed-v4.0"),
176 input: [
177 "a red guitar",
178 {
179 type: "image",
180 source: {
181 type: "data",
182 value: productPhoto,
183 mimeType: "image/png",
184 },
185 },
186 // A nested array fuses its parts into one vector.
187 [
188 { type: "text", content: "Fender Stratocaster, sunburst finish" },
189 {
190 type: "image",
191 source: {
192 type: "data",
193 value: productPhoto,
194 mimeType: "image/png",
195 },
196 },
197 ],
198 ],
199 modelOptions: { inputType: "search_document" },
200});
201
202console.log(result.embeddings.length); // 3, one vector per input item
203```
204
205Amazon Titan Multimodal works the same way. Nest the parts to fuse them:
206
207```typescript
208import { embed } from "@tanstack/ai";
209import { bedrockEmbedding } from "@tanstack/ai-bedrock";
210
211const productPhoto = "iVBORw0KGgo..."; // base64 image data
212
213const result = await embed({
214 adapter: bedrockEmbedding("amazon.titan-embed-image-v1"),
215 input: [
216 [
217 { type: "text", content: "a red guitar" },
218 {
219 type: "image",
220 source: {
221 type: "data",
222 value: productPhoto,
223 mimeType: "image/png",
224 },
225 },
226 ],
227 ],
228 dimensions: 1024,
229});
230```
231
232Pass images as base64 data or as a `data:` URI. Adapters do not download remote image URLs by default.
233
234Need to rank the results after a vector search? See [Reranking](./rerank/rerank).
235
236## Advanced
237
238### Remote image URLs
239
240The Cohere adapter has an `allowUrlFetch` config option. When you turn it on, the adapter downloads `http(s)` image URLs for you.
241
242### Token usage and middleware
243
244Adapters report token usage when the provider does. `embed()` accepts the same observe-only generation middleware as the media activities. See [Generation Hooks](./media/generation-hooks.md).
245
246```typescript
247import { embed } from "@tanstack/ai";
248import { openaiEmbedding } from "@tanstack/ai-openai";
249
250const result = await embed({
251 adapter: openaiEmbedding("text-embedding-3-small"),
252 input: ["a red guitar", "a blue drum kit"],
253 middleware: [
254 {
255 name: "usage-logger",
256 onUsage: (ctx, usage) => {
257 console.log(`${ctx.model}: ${usage.promptTokens} tokens`);
258 },
259 },
260 ],
261});
262
263console.log(result.usage?.promptTokens);
264```
265
266### Errors
267
268`embed()` rejects with the provider error. Middleware `onError` hooks run before the rejection reaches your code.
269
270```typescript
271import { embed } from "@tanstack/ai";
272import { openaiEmbedding } from "@tanstack/ai-openai";
273
274try {
275 await embed({
276 adapter: openaiEmbedding("text-embedding-3-small"),
277 input: "a red guitar",
278 });
279} catch (error) {
280 console.error("embedding failed", error);
281}
282```