> ## Documentation Index
> Fetch the complete documentation index at: https://openrouter.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Embeddings

> Generate vector embeddings from text and images

Embeddings are numerical representations of text that capture semantic meaning. They convert text into vectors (arrays of numbers) that can be used for various machine learning tasks. OpenRouter provides a unified API to access embedding models from multiple providers.

## What are embeddings?

Embeddings transform text into high-dimensional vectors where semantically similar texts are positioned closer together in vector space. For example, "cat" and "kitten" would have similar embeddings, while "cat" and "airplane" would be far apart.

These vector representations enable machines to understand relationships between pieces of text, making them essential for many AI applications.

## Common use cases

Embeddings are used in a wide variety of applications:

**RAG (Retrieval-Augmented Generation)**: Build RAG systems that retrieve relevant context from a knowledge base before generating answers. Embeddings help find the most relevant documents to include in the LLM's context.

**Semantic Search**: Convert documents and queries into embeddings, then find the most relevant documents by comparing vector similarity. This provides more accurate results than traditional keyword matching because it understands meaning rather than just matching words.

**Recommendation Systems**: Generate embeddings for items (products, articles, movies) and user preferences to recommend similar items. By comparing embedding vectors, you can find items that are semantically related even if they don't share obvious keywords.

**Clustering and Classification**: Group similar documents together or classify text into categories by analyzing embedding patterns. Documents with similar embeddings likely belong to the same topic or category.

**Duplicate Detection**: Identify duplicate or near-duplicate content by comparing embedding similarity. This works even when text is paraphrased or reworded.

**Anomaly Detection**: Detect unusual or outlier content by identifying embeddings that are far from typical patterns in your dataset.

## How to use embeddings

### Basic request

To generate embeddings, send a POST request to `/embeddings` with your text input and chosen model:

```typescript title="TypeScript SDK" lines theme={null}
import { OpenRouter } from '@openrouter/sdk';

const openRouter = new OpenRouter({
  apiKey: '<OPENROUTER_API_KEY>',
});

const response = await openRouter.embeddings.generate({
  requestBody: {
    model: 'openai/text-embedding-3-small',
    input: 'The quick brown fox jumps over the lazy dog',
  },
});

console.log(response.data[0].embedding);
```

```python title="Python" lines theme={null}
import requests

response = requests.post(
  "https://openrouter.ai/api/v1/embeddings",
  headers={
    "Authorization": f"Bearer <OPENROUTER_API_KEY>",
    "Content-Type": "application/json",
  },
  json={
    "model": "openai/text-embedding-3-small",
    "input": "The quick brown fox jumps over the lazy dog"
  }
)

data = response.json()
embedding = data["data"][0]["embedding"]
print(f"Embedding dimension: {len(embedding)}")
```

```typescript title="TypeScript (fetch)" lines theme={null}
const response = await fetch('https://openrouter.ai/api/v1/embeddings', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer <OPENROUTER_API_KEY>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/text-embedding-3-small',
    input: 'The quick brown fox jumps over the lazy dog',
  }),
});

const data = await response.json();
const embedding = data.data[0].embedding;
console.log(`Embedding dimension: ${embedding.length}`);
```

```shell title="Shell" lines theme={null}
curl https://openrouter.ai/api/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -d '{
    "model": "openai/text-embedding-3-small",
    "input": "The quick brown fox jumps over the lazy dog"
  }'
```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
)

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "openai/text-embedding-3-small",
		"input": "The quick brown fox jumps over the lazy dog",
	})

	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/embeddings", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var result struct {
		Data []struct {
			Embedding []float64 `json:"embedding"`
		} `json:"data"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}
	if len(result.Data) == 0 {
		log.Fatalf("no embeddings returned (status %s)", resp.Status)
	}

	fmt.Println(result.Data[0].Embedding)
}

```

```text title="Output" theme={null}
[
  -0.0208282470703125, -0.01690673828125, -0.0045318603515625, -0.05084228515625,
  -0.02593994140625, 0.0295867919921875, 0.029998779296875, 0.0290679931640625, 0.010589599609375,
  -0.024383544921875, -0.0093536376953125, 0.00662994384765625, -0.0260467529296875,
  0.0347900390625, -0.0165557861328125, 0.00022661685943603516, -0.00965118408203125,
  -0.055572509765625, -0.0379638671875, -0.024017333984375, -0.0213775634765625, 0.0030517578125,
  0.01099395751953125, -0.00490570068359375, -0.0007491111755371094, -0.00244140625,
  0.0113983154296875, -0.031524658203125, 0.010772705078125, -0.0010700225830078125,
  0.0298919677734375, -0.031097412109375, -0.01044464111328125, -0.061370849609375,
  -0.0149993896484375, -0.03729248046875, -0.0293731689453125, -0.0111541748046875,
  -0.0218353271484375, -0.004467010498046875, 0.0037364959716796875, -0.06390380859375,
  0.03448486328125, -0.050872802734375, 0.06536865234375, 0.035797119140625, 0.029998779296875,
  -0.028961181640625, 0.00821685791015625, 0.043914794921875, -0.0123138427734375,
  0.03131103515625, -0.0292510986328125, 0.01812744140625, -0.002674102783203125,
  0.0016508102416992188, 0.0313720703125, 0.022430419921875, -0.0292816162109375,
  -0.089599609375, 0.036529541015625, -0.004489898681640625, 0.0089263916015625, -0.01013946533203125,
  -0.0112152099609375, -0.01397705078125, -0.0030994415283203125, -0.02301025390625,
  0.019378662109375, -0.02777099609375, 0.02362060546875, 0.0185699462890625, -0.031585693359375,
  0.03509521484375, 0.0489501953125, 0.02294921875, 0.00844573974609375, 0.01560211181640625,
  0.0163726806640625, 0.046661376953125, 0.00504302978515625, 0.0225830078125, -0.008209228515625,
  -0.06842041015625, -0.00664520263671875, 0.048553466796875, -0.049591064453125,
  0.0291900634765625, 0.0301055908203125, -0.03814697265625, 0.06549072265625, 0.038330078125,
  -0.0211029052734375, -0.044464111328125, 0.05279541015625, -0.00145721435546875,
  0.01337432861328125, 0.019317626953125, 0.043701171875, 0.0234222412109375,
  ... 1436 more items
]
```

### Batch processing

You can generate embeddings for multiple texts in a single request by passing an array of strings:

```typescript title="TypeScript SDK" lines theme={null}
import { OpenRouter } from '@openrouter/sdk';

const openRouter = new OpenRouter({
  apiKey: '<OPENROUTER_API_KEY>',
});

const response = await openRouter.embeddings.generate({
  requestBody: {
    model: 'openai/text-embedding-3-small',
    input: [
      'Machine learning is a subset of artificial intelligence',
      'Deep learning uses neural networks with multiple layers',
      'Natural language processing enables computers to understand text'
    ],
  },
});

// Process each embedding
response.data.forEach((item, index) => {
  console.log(`Embedding ${index}: ${item.embedding.length} dimensions`);
});

```

```python title="Python" expandable lines theme={null}
import requests

response = requests.post(
  "https://openrouter.ai/api/v1/embeddings",
  headers={
    "Authorization": f"Bearer <OPENROUTER_API_KEY>",
    "Content-Type": "application/json",
  },
  json={
    "model": "openai/text-embedding-3-small",
    "input": [
      "Machine learning is a subset of artificial intelligence",
      "Deep learning uses neural networks with multiple layers",
      "Natural language processing enables computers to understand text"
    ]
  }
)

data = response.json()
for i, item in enumerate(data["data"]):
  print(f"Embedding {i}: {len(item['embedding'])} dimensions")
```

```typescript title="TypeScript (fetch)" lines theme={null}
const response = await fetch('https://openrouter.ai/api/v1/embeddings', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer <OPENROUTER_API_KEY>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/text-embedding-3-small',
    input: [
      'Machine learning is a subset of artificial intelligence',
      'Deep learning uses neural networks with multiple layers',
      'Natural language processing enables computers to understand text'
    ],
  }),
});

const data = await response.json();
data.data.forEach((item, index) => {
  console.log(`Embedding ${index}: ${item.embedding.length} dimensions`);
});
```

```shell title="Shell" lines theme={null}
curl https://openrouter.ai/api/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -d '{
    "model": "openai/text-embedding-3-small",
    "input": [
      "Machine learning is a subset of artificial intelligence",
      "Deep learning uses neural networks with multiple layers",
      "Natural language processing enables computers to understand text"
    ]
  }'
```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
)

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "openai/text-embedding-3-small",
		"input": []string{
			"Machine learning is a subset of artificial intelligence",
			"Deep learning uses neural networks with multiple layers",
			"Natural language processing enables computers to understand text",
		},
	})

	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/embeddings", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	var result struct {
		Data []struct {
			Embedding []float64 `json:"embedding"`
		} `json:"data"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}
	if len(result.Data) == 0 {
		log.Fatalf("no embeddings returned (status %s)", resp.Status)
	}

	// Process each embedding
	for i, item := range result.Data {
		fmt.Printf("Embedding %d: %d dimensions\n", i, len(item.Embedding))
	}
}

```

```text title="Output" theme={null}
Embedding 0: 1536 dimensions
Embedding 1: 1536 dimensions
Embedding 2: 1536 dimensions
```

### Image input

Some embedding models support image inputs, enabling multimodal embeddings that capture visual content alongside text. This is useful for image search, visual similarity, and cross-modal retrieval tasks.

To send an image, wrap your input in the multimodal format with a `content` array containing `image_url` objects. You can also combine text and images in a single input block.

```python title="Python" expandable lines theme={null}
import requests

response = requests.post(
  "https://openrouter.ai/api/v1/embeddings",
  headers={
    "Authorization": f"Bearer <OPENROUTER_API_KEY>",
    "Content-Type": "application/json",
  },
  json={
    "model": "google/gemini-embedding-2-preview",
    "input": [
      {
        "content": [
          {"type": "image_url", "image_url": {"url": "https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg"}}
        ]
      }
    ],
    "encoding_format": "float",
  }
)

data = response.json()
if not data.get("data"):
  raise RuntimeError(f"No embeddings returned: {data}")
embedding = data["data"][0]["embedding"]
print(f"Embedding dimension: {len(embedding)}")
print(embedding[:5])

```

```typescript title="TypeScript (fetch)" expandable lines theme={null}
const response = await fetch('https://openrouter.ai/api/v1/embeddings', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer <OPENROUTER_API_KEY>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'google/gemini-embedding-2-preview',
    input: [
      {
        content: [
          { type: 'image_url', image_url: { url: 'https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg' } }
        ]
      }
    ],
    encoding_format: 'float',
  }),
});

const data = await response.json();
if (!data.data?.length) {
  throw new Error(`No embeddings returned: ${JSON.stringify(data)}`);
}
const embedding = data.data[0].embedding;
console.log(`Embedding dimension: ${embedding.length}`);
console.log(embedding.slice(0, 5));

```

```shell title="Shell" lines theme={null}
curl https://openrouter.ai/api/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -d '{
    "model": "google/gemini-embedding-2-preview",
    "input": [
      {
        "content": [
          {"type": "image_url", "image_url": {"url": "https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg"}}
        ]
      }
    ],
    "encoding_format": "float"
  }' | jq '{dimension: (.data[0].embedding | length), first_values: .data[0].embedding[:5]}'
```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "google/gemini-embedding-2-preview",
		"input": []map[string]any{
			{
				"content": []map[string]any{
					{"type": "image_url", "image_url": map[string]string{"url": "https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg"}},
				},
			},
		},
		"encoding_format": "float",
	})

	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/embeddings", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	raw, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	var result struct {
		Data []struct {
			Embedding []float64 `json:"embedding"`
		} `json:"data"`
	}
	if err := json.Unmarshal(raw, &result); err != nil || len(result.Data) == 0 {
		log.Fatalf("no embeddings returned: %s", raw)
	}

	embedding := result.Data[0].Embedding
	fmt.Printf("Embedding dimension: %d\n", len(embedding))
	fmt.Println(embedding[:min(5, len(embedding))])
}

```

```text title="Output" theme={null}
Embedding dimension: 3072
[ -0.016795406, -0.015404839, -0.00029555237, 0.011511302, -0.0063522956 ]
```

You can also combine text and images in a single input to generate a joint embedding:

```python title="Python" expandable lines theme={null}
import requests

response = requests.post(
  "https://openrouter.ai/api/v1/embeddings",
  headers={
    "Authorization": f"Bearer <OPENROUTER_API_KEY>",
    "Content-Type": "application/json",
  },
  json={
    "model": "google/gemini-embedding-2-preview",
    "input": [
      {
        "content": [
          {"type": "text", "text": "A scenic boardwalk through a green meadow"},
          {"type": "image_url", "image_url": {"url": "https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg"}}
        ]
      }
    ],
    "encoding_format": "float",
  }
)

data = response.json()
embedding = data["data"][0]["embedding"]
print(f"Embedding dimension: {len(embedding)}")
```

```typescript title="TypeScript (fetch)" expandable lines theme={null}
const response = await fetch('https://openrouter.ai/api/v1/embeddings', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer <OPENROUTER_API_KEY>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'google/gemini-embedding-2-preview',
    input: [
      {
        content: [
          { type: 'text', text: 'A scenic boardwalk through a green meadow' },
          { type: 'image_url', image_url: { url: 'https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg' } }
        ]
      }
    ],
    encoding_format: 'float',
  }),
});

const data = await response.json();
const embedding = data.data[0].embedding;
console.log(`Embedding dimension: ${embedding.length}`);
```

```shell title="Shell" lines theme={null}
curl https://openrouter.ai/api/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -d '{
    "model": "google/gemini-embedding-2-preview",
    "input": [
      {
        "content": [
          {"type": "text", "text": "A scenic boardwalk through a green meadow"},
          {"type": "image_url", "image_url": {"url": "https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg"}}
        ]
      }
    ],
    "encoding_format": "float"
  }'
```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "google/gemini-embedding-2-preview",
		"input": []map[string]any{
			{
				"content": []map[string]any{
					{"type": "text", "text": "A scenic boardwalk through a green meadow"},
					{"type": "image_url", "image_url": map[string]string{"url": "https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg"}},
				},
			},
		},
		"encoding_format": "float",
	})

	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/embeddings", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	raw, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	var result struct {
		Data []struct {
			Embedding []float64 `json:"embedding"`
		} `json:"data"`
	}
	if err := json.Unmarshal(raw, &result); err != nil || len(result.Data) == 0 {
		log.Fatalf("no embeddings returned: %s", raw)
	}

	fmt.Printf("Embedding dimension: %d\n", len(result.Data[0].Embedding))
}

```

```text title="Output" theme={null}
Embedding dimension: 3072
```

### Contextual embeddings

Some embedding models embed every chunk of a document with the rest of that document as context, so each chunk's vector carries the meaning of the document it came from. This improves retrieval when chunks are short or ambiguous on their own, such as a paragraph that refers to "it" or "the company" without naming the subject.

To use contextual mode, send `input` as an array of documents, where each document is an ordered array of chunk strings, and set `input_type` to `"document"`. You get one embedding back per chunk, in document order.

```python title="Python" lines theme={null}
import requests

response = requests.post(
  "https://openrouter.ai/api/v1/embeddings",
  headers={
    "Authorization": f"Bearer {{API_KEY_REF}}",
    "Content-Type": "application/json",
  },
  json={
    "model": "{{MODEL}}",
    "input_type": "document",
    "input": [
      ["Paris is the capital of France.", "It sits on the Seine.", "Its population is about two million."],
      ["Berlin is the capital of Germany."]
    ]
  }
)

data = response.json()
for item in data["data"]:
  print(item["document_index"], item["index"], len(item["embedding"]))
```

```typescript title="TypeScript (fetch)" lines theme={null}
const response = await fetch('https://openrouter.ai/api/v1/embeddings', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer {{API_KEY_REF}}',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: '{{MODEL}}',
    input_type: 'document',
    input: [
      ['Paris is the capital of France.', 'It sits on the Seine.', 'Its population is about two million.'],
      ['Berlin is the capital of Germany.'],
    ],
  }),
});

const data = await response.json();
for (const item of data.data) {
  console.log(item.document_index, item.index, item.embedding.length);
}
```

```shell title="Shell" lines theme={null}
curl https://openrouter.ai/api/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -d '{
    "model": "{{MODEL}}",
    "input_type": "document",
    "input": [
      ["Paris is the capital of France.", "It sits on the Seine.", "Its population is about two million."],
      ["Berlin is the capital of Germany."]
    ]
  }'
```

#### Response shape

The response is the same flat `data` array as every other embeddings request, with one extra field. `index` counts across all chunks in the request, and `document_index` is the position of the chunk's document in your `input`:

```json theme={null}
{
  "object": "list",
  "model": "perplexity/pplx-embed-v2-context-9b",
  "data": [
    { "object": "embedding", "index": 0, "document_index": 0, "embedding": [...] },
    { "object": "embedding", "index": 1, "document_index": 0, "embedding": [...] },
    { "object": "embedding", "index": 2, "document_index": 0, "embedding": [...] },
    { "object": "embedding", "index": 3, "document_index": 1, "embedding": [...] }
  ],
  "usage": { "prompt_tokens": 33, "total_tokens": 33 }
}
```

> [!NOTE]
>
> Providers that offer contextual embeddings natively, such as Perplexity, return a nested response: one list per document, each with its own `data` array and a chunk `index` that restarts at 0 in every document. OpenRouter flattens that into the single `data` array that existing embeddings clients expect. If you are porting code from a provider's SDK, read `document_index` instead of nesting, and treat `index` as global rather than per document.

Chunks of the same document are contiguous and in the order you sent them, so grouping is a one-liner:

```python lines theme={null}
by_document = {}
for item in data["data"]:
  by_document.setdefault(item["document_index"], []).append(item["embedding"])
```

#### Querying a contextual index

Embed search queries as a plain string or string array with `input_type: "query"`. Queries have no document context, so they never use the nested shape:

```json theme={null}
{
  "model": "perplexity/pplx-embed-v2-context-9b",
  "input_type": "query",
  "input": "Which city is on the Seine?"
}
```

#### Constraints

| Request | Result |
| - | - |
| Nested `input` with a model that does not support contextual embeddings | `404` No endpoints found that support document-chunk (`string[][]`) input |
| Nested `input` with `input_type: "query"` | `400` Document-chunk input is only supported with `input_type: "document"` |
| Flat `input` on a Perplexity v2 model without `input_type` | `400` Perplexity embeddings require `input_type` |
| An empty chunk string, or an empty document alongside a non-empty one | `400` schema validation error |
| Nested `input` through the [Batch API](https://openrouter.ai/docs/guides/features/batch-api.md) | `400` not supported |

Only models that advertise contextual embeddings accept nested `input`; other models accept strings and string arrays, and token arrays only where the provider supports them. Contextual input is text only.

## API reference

For detailed information about request parameters, response format, and all available options, see the [Embeddings API Reference](https://openrouter.ai/docs/api/api-reference/embeddings/submit-an-embedding-request.md).

## Available models

OpenRouter provides access to various embedding models from different providers. You can view all available embedding models at:

[https://openrouter.ai/models?fmt=cards\&output\_modalities=embeddings](https://openrouter.ai/models?fmt=cards\&output_modalities=embeddings)

To list all available embedding models programmatically:

```typescript title="TypeScript SDK" lines theme={null}
const response = await fetch('https://openrouter.ai/api/v1/embeddings/models', {
  headers: {
    'Authorization': 'Bearer <OPENROUTER_API_KEY>',
  },
});

const models = await response.json();
console.log(models.data);

```

```python title="Python" lines theme={null}
import requests

response = requests.get(
  "https://openrouter.ai/api/v1/embeddings/models",
  headers={
    "Authorization": f"Bearer <OPENROUTER_API_KEY>",
  }
)

models = response.json()
for model in models["data"]:
  print(f"{model['id']}: {model.get('context_length', 'N/A')} tokens")
```

```typescript title="TypeScript (fetch)" lines theme={null}
const response = await fetch('https://openrouter.ai/api/v1/embeddings/models', {
  headers: {
    'Authorization': 'Bearer <OPENROUTER_API_KEY>',
  },
});

const models = await response.json();
console.log(models.data);
```

```shell title="Shell" lines theme={null}
curl https://openrouter.ai/api/v1/embeddings/models \
  -H "Authorization: Bearer $OPENROUTER_API_KEY"
```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

func main() {
	req, _ := http.NewRequest("GET", "https://openrouter.ai/api/v1/embeddings/models", nil)
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	raw, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	var models struct {
		Data json.RawMessage `json:"data"`
	}
	if err := json.Unmarshal(raw, &models); err != nil || models.Data == nil {
		log.Fatalf("no models returned: %s", raw)
	}

	var out bytes.Buffer
	json.Indent(&out, models.Data, "", "  ")
	fmt.Println(out.String())
}

```

```text title="Output" theme={null}
[
  {
    id: "cohere/embed-5-fast",
    canonical_slug: "cohere/embed-5-fast-20261029",
    hugging_face_id: null,
    name: "Cohere: Embed 5 Fast",
    created: 1793739025,
    description: "Embed 5 Fast is the lower-latency, cost-efficient tier of Cohere's Embed 5 family of multimodal embedding models (about 1B parameters). It embeds text, images, and interleaved text and image content...",
    context_length: 128000,
    architecture: {
      modality: "text+image->embeddings",
      input_modalities: [Array ...],
      output_modalities: [Array ...],
      tokenizer: "Cohere",
      instruct_type: null,
    },
    pricing: {
      prompt: "0.00000008",
      completion: "0",
      image_token: "0.0000004",
    },
    top_provider: {
      context_length: 128000,
      max_completion_tokens: null,
      is_moderated: true,
    },
    per_request_limits: null,
    supported_parameters: [],
    default_parameters: {},
    supported_voices: null,
    knowledge_cutoff: null,
    expiration_date: null,
    links: {
      details: "/api/v1/models/cohere/embed-5-fast-20261029/endpoints",
    },
    endpoints: [ "/api/v1/embeddings" ],
  }, {
    id: "cohere/embed-5-pro",
    canonical_slug: "cohere/embed-5-pro-20261029",
    hugging_face_id: null,
```

## Practical example: semantic search

Here's a complete example of building a semantic search system using embeddings:

```typescript title="TypeScript SDK" expandable lines theme={null}
import { OpenRouter } from '@openrouter/sdk';

const openRouter = new OpenRouter({
  apiKey: '<OPENROUTER_API_KEY>',
});

// Sample documents
const documents = [
  "The cat sat on the mat",
  "Dogs are loyal companions",
  "Python is a programming language",
  "Machine learning models require training data",
  "The weather is sunny today"
];

// Function to calculate cosine similarity
function cosineSimilarity(a: number[], b: number[]): number {
  const dotProduct = a.reduce((sum, val, i) => sum + val * b[i], 0);
  const magnitudeA = Math.sqrt(a.reduce((sum, val) => sum + val * val, 0));
  const magnitudeB = Math.sqrt(b.reduce((sum, val) => sum + val * val, 0));
  return dotProduct / (magnitudeA * magnitudeB);
}

async function semanticSearch(query: string, documents: string[]) {
  // Generate embeddings for all documents and the query
  const response = await openRouter.embeddings.generate({
    requestBody: {
      model: 'openai/text-embedding-3-small',
      input: [query, ...documents],
    },
  });

  const queryEmbedding = response.data[0].embedding;
  const docEmbeddings = response.data.slice(1);

  // Calculate similarity scores
  const results = documents.map((doc, i) => ({
    document: doc,
    similarity: cosineSimilarity(
      queryEmbedding as number[],
      docEmbeddings[i].embedding as number[]
    ),
  }));

  // Sort by similarity (highest first)
  results.sort((a, b) => b.similarity - a.similarity);

  return results;
}

// Search for documents related to pets
const results = await semanticSearch("pets and animals", documents);
console.log("Search results:");
results.forEach((result, i) => {
  console.log(`${i + 1}. ${result.document} (similarity: ${result.similarity.toFixed(4)})`);
});
```

```python title="Python" expandable lines theme={null}
import requests
import numpy as np

OPENROUTER_API_KEY = "<OPENROUTER_API_KEY>"

# Sample documents
documents = [
  "The cat sat on the mat",
  "Dogs are loyal companions",
  "Python is a programming language",
  "Machine learning models require training data",
  "The weather is sunny today"
]

def cosine_similarity(a, b):
  """Calculate cosine similarity between two vectors"""
  dot_product = np.dot(a, b)
  magnitude_a = np.linalg.norm(a)
  magnitude_b = np.linalg.norm(b)
  return dot_product / (magnitude_a * magnitude_b)

def semantic_search(query, documents):
  """Perform semantic search using embeddings"""
  # Generate embeddings for query and all documents
  response = requests.post(
    "https://openrouter.ai/api/v1/embeddings",
    headers={
      "Authorization": f"Bearer {OPENROUTER_API_KEY}",
      "Content-Type": "application/json",
    },
    json={
      "model": "openai/text-embedding-3-small",
      "input": [query] + documents
    }
  )
  
  data = response.json()
  query_embedding = np.array(data["data"][0]["embedding"])
  doc_embeddings = [np.array(item["embedding"]) for item in data["data"][1:]]
  
  # Calculate similarity scores
  results = []
  for i, doc in enumerate(documents):
    similarity = cosine_similarity(query_embedding, doc_embeddings[i])
    results.append({"document": doc, "similarity": similarity})
  
  # Sort by similarity (highest first)
  results.sort(key=lambda x: x["similarity"], reverse=True)
  
  return results

# Search for documents related to pets
results = semantic_search("pets and animals", documents)
print("Search results:")
for i, result in enumerate(results):
  print(f"{i + 1}. {result['document']} (similarity: {result['similarity']:.4f})")
```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"math"
	"net/http"
	"os"
	"sort"
)

// Sample documents
var documents = []string{
	"The cat sat on the mat",
	"Dogs are loyal companions",
	"Python is a programming language",
	"Machine learning models require training data",
	"The weather is sunny today",
}

// cosineSimilarity calculates the cosine similarity of two vectors
func cosineSimilarity(a, b []float64) float64 {
	var dot, magA, magB float64
	for i := range a {
		dot += a[i] * b[i]
		magA += a[i] * a[i]
		magB += b[i] * b[i]
	}
	return dot / (math.Sqrt(magA) * math.Sqrt(magB))
}

type result struct {
	Document   string
	Similarity float64
}

func semanticSearch(query string, documents []string) []result {
	// Generate embeddings for all documents and the query
	body, _ := json.Marshal(map[string]any{
		"model": "openai/text-embedding-3-small",
		"input": append([]string{query}, documents...),
	})

	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/embeddings", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	raw, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	var response struct {
		Data []struct {
			Embedding []float64 `json:"embedding"`
		} `json:"data"`
	}
	if err := json.Unmarshal(raw, &response); err != nil || len(response.Data) != len(documents)+1 {
		log.Fatalf("unexpected embeddings response: %s", raw)
	}

	queryEmbedding := response.Data[0].Embedding
	docEmbeddings := response.Data[1:]

	// Calculate similarity scores
	results := make([]result, len(documents))
	for i, doc := range documents {
		results[i] = result{doc, cosineSimilarity(queryEmbedding, docEmbeddings[i].Embedding)}
	}

	// Sort by similarity (highest first)
	sort.Slice(results, func(i, j int) bool { return results[i].Similarity > results[j].Similarity })

	return results
}

func main() {
	// Search for documents related to pets
	results := semanticSearch("pets and animals", documents)
	fmt.Println("Search results:")
	for i, r := range results {
		fmt.Printf("%d. %s (similarity: %.4f)\n", i+1, r.Document, r.Similarity)
	}
}

```

```bash title="cURL" lines theme={null}
DOCS='["The cat sat on the mat", "Dogs are loyal companions", "Python is a programming language", "Machine learning models require training data", "The weather is sunny today"]'

curl -s https://openrouter.ai/api/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -d "$(jq -n --argjson docs "$DOCS" '{model: "openai/text-embedding-3-small", input: (["pets and animals"] + $docs)}')" \
| jq -r --argjson docs "$DOCS" '
  def dot($a; $b): [$a, $b] | transpose | map(.[0] * .[1]) | add;
  (.data | sort_by(.index) | map(.embedding)) as $e
  | [range(1; $e | length) as $i
     | {doc: $docs[$i - 1], sim: (dot($e[0]; $e[$i]) / ((dot($e[0]; $e[0]) * dot($e[$i]; $e[$i])) | sqrt))}]
  | sort_by(-.sim)
  | "Search results:",
    (to_entries[] | "\(.key + 1). \(.value.doc) (similarity: \(.value.sim * 10000 | round / 10000))")'

```

Expected output:

```lines theme={null}
Search results:
1. Dogs are loyal companions (similarity: 0.8234)
2. The cat sat on the mat (similarity: 0.7891)
3. The weather is sunny today (similarity: 0.3456)
4. Machine learning models require training data (similarity: 0.2987)
5. Python is a programming language (similarity: 0.2654)
```

## Best practices

**Choose the right model**: Different embedding models have different strengths. Smaller models (like perplexity/pplx-embed-v1-0.6b or openai/text-embedding-3-small) are faster and cheaper, while larger models (like openai/text-embedding-3-large) provide better quality. Test multiple models to find the best fit for your use case.

**Batch your requests**: When processing multiple texts, send them in a single request rather than making individual API calls. This reduces latency and costs.

**Cache embeddings**: Embeddings for the same text are deterministic (they don't change). Store embeddings in a database or vector store to avoid regenerating them repeatedly.

**Normalize for comparison**: When comparing embeddings, use cosine similarity rather than Euclidean distance. Cosine similarity is scale-invariant and works better for high-dimensional vectors.

**Consider Context Length**: Each model has a maximum input length (context window). Longer texts may need to be chunked or truncated. Check the model's specifications before processing long documents.

**Use Appropriate Chunking**: For long documents, split them into meaningful chunks (paragraphs, sections) rather than arbitrary character limits. This preserves semantic coherence.

## Provider routing

You can control which providers serve your embedding requests using the `provider` parameter. This is useful for:

* Ensuring data privacy with specific providers
* Optimizing for cost or latency
* Using provider-specific features

Example with provider preferences:

```typescript lines theme={null}
{
  "model": "openai/text-embedding-3-small",
  "input": "Your text here",
  "provider": {
    "order": ["openai", "azure"],
    "allow_fallbacks": true,
    "data_collection": "deny"
  }
}
```

```python title="Python" lines theme={null}
payload = {
    "model": "openai/text-embedding-3-small",
    "input": "Your text here",
    "provider": {
        "order": ["openai", "azure"],
        "allow_fallbacks": True,
        "data_collection": "deny",
    },
}

```

```go title="Go" lines theme={null}
body := map[string]any{
	"model": "openai/text-embedding-3-small",
	"input": "Your text here",
	"provider": map[string]any{
		"order":           []string{"openai", "azure"},
		"allow_fallbacks": true,
		"data_collection": "deny",
	},
}

```

```bash title="cURL" lines theme={null}
curl -s https://openrouter.ai/api/v1/embeddings \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -d '{
    "model": "openai/text-embedding-3-small",
    "input": "Your text here",
    "provider": {
      "order": ["openai", "azure"],
      "allow_fallbacks": true,
      "data_collection": "deny"
    }
  }'
```

For more information, see [Provider Routing](https://openrouter.ai/docs/guides/routing/provider-selection.md).

## Error handling

Common errors you may encounter:

**400 Bad Request**: Invalid input format or missing required parameters. Check that your `input` and `model` parameters are correctly formatted.

**401 Unauthorized**: Invalid or missing API key. Verify your API key is correct and included in the Authorization header.

**402 Payment Required**: Insufficient credits. Add credits to your OpenRouter account.

**404 Not Found**: The specified model doesn't exist or isn't available for embeddings. Check the model name and verify it's an embedding model.

**429 Too Many Requests**: Rate limit exceeded. Implement exponential backoff and retry logic.

**529 Provider Overloaded**: The provider is temporarily overloaded. Enable `allow_fallbacks: true` to automatically use backup providers.

## Limitations

* **No Streaming**: Unlike chat completions, embeddings are returned as complete responses. Streaming is not supported.
* **Token Limits**: Each model has a maximum input length. Texts exceeding this limit will be truncated or rejected.
* **Deterministic Output**: Embeddings for the same input text will always be identical (no temperature or randomness).
* **Language Support**: Some models are optimized for specific languages. Check model documentation for language capabilities.

## Related resources

* [Models Page](https://openrouter.ai/models?fmt=cards\&output_modalities=embeddings) - Browse all available embedding models
* [Provider Routing](https://openrouter.ai/docs/guides/routing/provider-selection.md) - Control which providers serve your requests
* [Authentication](https://openrouter.ai/docs/api_reference/authentication.md) - Learn about API key authentication
* [Errors](https://openrouter.ai/docs/api_reference/errors-and-debugging.md) - Detailed error codes and handling
