# Embeddings

> Turns text into vectors for search, clustering and retrieval. OpenAI-compatible body and response, with the cost of the request in usage.

`POST https://api.getlykia.com/v1/embeddings`

This endpoint takes an OpenAI embeddings request and answers in the same format, so the OpenAI SDKs' `embeddings.create` works against it unchanged. Lykia picks a provider for the model the same way it does for chat: your project's own provider keys first, then Lykia's direct connections, cheapest first, moving to the next candidate when one fails. Reservations, key limits, project budgets and request records work as they do for [`POST /chat/completions`](https://www.getlykia.com/en/docs/api-reference/chat-completions).

Only models that produce vectors can be used here. They are left out of the default [`GET /models`](https://www.getlykia.com/en/docs/api-reference/models) list, which is meant for chat; list them with `GET /models?output_modalities=embedding`.

## Request body

- `model` (string, required) — An embedding model id (for example `openai/text-embedding-3-small`), or a preset as `@name` whose model is an embedding model (for example `@embedding`). A chat model returns `400` with the code `unsupported_model`; a preset whose model is not an embedding model returns `preset_modality_mismatch`.
- `input` (string | string\[], required) — The text to embed: one string, or an array of 1 to 2,048 non-empty strings. Token arrays are not accepted (`400`, `unsupported_input`).
- `dimensions` (integer) — The length of the vectors, for models that let you choose it.
- `encoding_format` (string) — `float` (default) or `base64`. Lykia returns base64 even for providers that only return floats.
- `models` (string\[]) — Fallback models, as in chat.
- `provider` (object) — Provider preferences, as in chat. See [Provider routing](https://www.getlykia.com/en/docs/guides/provider-routing).
- `user` (string) and `metadata` (object) — Tags stored with the request record and never sent to the provider. See [Tags and usage breakdown](https://www.getlykia.com/en/docs/guides/tags-and-usage).

## Example

The vectors in the response below are shortened to four numbers.

**Request**

cURL

```bash
curl https://api.getlykia.com/v1/embeddings \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/text-embedding-3-small",
    "input": ["Refund policy for annual plans", "How do I reset my password?"],
    "dimensions": 256,
    "user": "tenant-42",
    "metadata": { "feature": "search" }
  }'
```

Python

```python
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

result = client.embeddings.create(
    model="openai/text-embedding-3-small",
    input=["Refund policy for annual plans", "How do I reset my password?"],
    dimensions=256,
    user="tenant-42",
    extra_body={"metadata": {"feature": "search"}},
)
for item in result.data:
    print(item.index, len(item.embedding))
print(result.model, result.usage.total_tokens)
```

TypeScript

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });

const result = await client.embeddings.create({
  model: "openai/text-embedding-3-small",
  input: ["Refund policy for annual plans", "How do I reset my password?"],
  dimensions: 256,
  user: "tenant-42",
});
for (const item of result.data) console.log(item.index, item.embedding.length);
console.log(result.model, result.usage.total_tokens);
```

Go

```go
package main

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

func main() {
	payload, _ := json.Marshal(map[string]any{
		"model":      "openai/text-embedding-3-small",
		"input":      []string{"Refund policy for annual plans", "How do I reset my password?"},
		"dimensions": 256,
		"user":       "tenant-42",
		"metadata":   map[string]string{"feature": "search"},
	})

	req, err := http.NewRequest(http.MethodPost, "https://api.getlykia.com/v1/embeddings", bytes.NewReader(payload))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LYKIA_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

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

	body, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("Lykia returned %d: %s", resp.StatusCode, body))
	}

	var result struct {
		Data []struct {
			Index     int       `json:"index"`
			Embedding []float64 `json:"embedding"`
		} `json:"data"`
		Usage struct {
			TotalTokens int     `json:"total_tokens"`
			Cost        float64 `json:"cost"`
		} `json:"usage"`
	}
	if err := json.Unmarshal(body, &result); err != nil {
		panic(err)
	}
	for _, item := range result.Data {
		fmt.Println(item.Index, len(item.Embedding))
	}
	fmt.Println("tokens:", result.Usage.TotalTokens, "cost (USD):", result.Usage.Cost)
}
```

**Response (200)**

```json
{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "index": 0,
      "embedding": [0.385695, 0.449977, 0.707107, 0.385695]
    },
    {
      "object": "embedding",
      "index": 1,
      "embedding": [0.641223, 0.569976, 0.427482, 0.284988]
    }
  ],
  "model": "openai/text-embedding-3-small",
  "provider": "openai",
  "usage": {
    "prompt_tokens": 15,
    "total_tokens": 15,
    "cost": 0.000001,
    "is_byok": false,
    "cost_details": {
      "upstream_cost": 0.000001,
      "platform_fee": 0,
      "is_byok": false
    }
  }
}
```

## Response

- `object` (string) — Always `list`.
- `data` (array) — One item per input, in the same order.
  - `object` (string) — Always `embedding`.
  - `index` (integer) — The position of the input this vector belongs to.
  - `embedding` (number\[] | string) — The vector, or a base64 string with `encoding_format: "base64"`.
- `model` (string) — The model that produced the vectors; with a preset, the real model.
- `provider` (string) — The id of the provider that served the request.
- `usage` (object) — `prompt_tokens` and `total_tokens` (the input tokens), `cost` in USD, `is_byok` and `cost_details`, as in chat.

The response carries the request id in the `X-Generation-Id` header, and `X-Lykia-Preset` when `model` was a preset. Embedding requests are priced per input token at the model's `prompt` price. When a provider does not report token counts, Lykia estimates them at about four characters per token. Look the record up with [`GET /generation`](https://www.getlykia.com/en/docs/api-reference/generation); its `endpoint` is `embeddings`.

## Errors

The status codes are the same as for [`POST /chat/completions`](https://www.getlykia.com/en/docs/api-reference/chat-completions#errors), with the body described in [Errors](https://www.getlykia.com/en/docs/guides/errors). A provider that returns fewer vectors than inputs gives `502`, and the request is not billed.
