# Vector Search (totalum-sdk/vectors)

> Semantic search over your own content: store texts or images as vectors with metadata (upsert), then find the closest ones to a question, a text or an image (query). Totalum embeds the text and images for you and keeps each project environment's vectors private. Use it for "search by meaning", recommendations and retrieval for an AI answer. Server-side code only. Writes and queries are billed in credits; count() is free.

`import … from 'totalum-sdk/vectors'`, or the same namespace on `totalum` from `'totalum-sdk'`. Install, configuration and errors: [Totalum SDK](https://www.totalum.app/docs/sdk).

Semantic search over your own content: store texts or images as vectors with metadata (`upsert`), then find the
closest ones to a question, a text or an image (`query`). Totalum embeds the text and images for you and keeps each
project environment's vectors private. Use it for "search by meaning", recommendations and retrieval for an AI
answer. Server-side code only. Writes and queries are billed in credits; `count()` is free.

```ts
await totalum.vectors.upsert([{ id: 'faq-1', text: 'Refunds are possible for 30 days.', metadata: { source: 'faq' } }]);
const { matches } = await totalum.vectors.query({ text: 'Can I get my money back?', topK: 3 });
```

| Method or type | What it does |
|---|---|
| [`totalumVectors`](#totalumvectors) | Creates the `vectors` namespace (the same object as `totalum.vectors`; scope `vectors`; server-side code only: it needs the project key). |
| [`vectors.upsert`](#vectorsupsert) | Stores up to 100 items (at most 8 of them images) for semantic search: give each an `id` of yours (the row id), its content as `text`, `image` or ready-made `values`, and metadata to filter on. |
| [`vectors.query`](#vectorsquery) | Finds the stored items closest in meaning to a text, an image or a vector — "search by meaning". |
| [`vectors.get`](#vectorsget) | Reads stored items back by id, with their numbers and metadata. |
| [`vectors.delete`](#vectorsdelete) | Deletes items by id — when the row they describe is deleted. |
| [`vectors.count`](#vectorscount) | How many items this environment stores, in total and per space. |
| [`VectorFilter`](#vectorfilter) | A metadata filter for `vectors.query()`: an object from a metadata key (`source`, `type`, `tag`, `group` — strings — or `page` — a number) to a value it must equal, or to an operator object: `$eq`, `$ne` (equal, not equal), `$in`, `$nin` (one of, none of a list), `$lt`, `$lte`, `$gt`, `$gte` (ranges). |
| [`VectorMatch`](#vectormatch) | One result of `vectors.query()`. |
| [`VectorMetadata`](#vectormetadata) | The metadata stored with an item: an object from string keys (not starting with `_`) to a string, a number, a boolean or a list of strings; at most 9 KB as JSON. |
| [`VectorRecord`](#vectorrecord) | A stored item, from `vectors.get()`. |
| [`VectorSpace`](#vectorspace) | Which embedding space an item lives in. |
| [`VectorsQueryInput`](#vectorsqueryinput) | What `vectors.query()` searches for: exactly one of `text`, `image` or `values`. |
| [`VectorUpsertItem`](#vectorupsertitem) | One item to store with `vectors.upsert()`: an id, exactly one content (`text`, `image` or `values`) and optional metadata. |

## `totalumVectors`

```ts
totalumVectors(options?: TotalumClientOptions): TotalumVectors
```

Creates the `vectors` namespace (the same object as `totalum.vectors`; scope `vectors`; server-side code only: it
needs the project key). Every
project environment has its own private vector store: ids, namespaces and indexes are Totalum's, never yours to
name, and `x-totalum-env` (the `env` option) keeps dev and live apart. Vectors are 1,024 numbers; `text` is
embedded with the `embed` model and `image` (a project file key, a files URL, an https URL or a data URL) with the
`embed-image` model, whose space also embeds text: search images by words with `space: 'image'`. Filter on the
metadata keys `source`, `type`, `tag`, `group` (strings) and `page` (number).

**Parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `options` | [`TotalumClientOptions`](https://www.totalum.app/docs/sdk/types#totalumclientoptions) | no | The project key, API URL and environment; each falls back to its environment variable. |
| `options.key` | `string` | no | Project key `tlm_pk_…`; default `TOTALUM_PROJECT_KEY`. Server-side only. |
| `options.apiUrl` | `string` | no | The Totalum API's URL: default `TOTALUM_SDK_API_URL`, else `https://sdk-api.totalum.app`. |
| `options.env` | `'dev' \| 'live'` | no | Sent as `x-totalum-env` on every call (the database it targets, and dev vs live usage); default `TOTALUM_ENV`, else `live`. |

**Returns** [`TotalumVectors`](#totalumvectors) — The `vectors` namespace: the methods below.

**Example**

```ts
import { totalumVectors } from 'totalum-sdk/vectors';

const vectors = totalumVectors();
const { count } = await vectors.count();
```

The namespace's type is exported as `TotalumVectors` (`import type { TotalumVectors } from 'totalum-sdk/vectors'`).

## `vectors.upsert`

```ts
vectors.upsert(vectors: VectorUpsertItem[]): Promise<{ upserted, count, usage }>
```

Stores up to 100 items (at most 8 of them images) for semantic search: give each an `id` of yours (the row id),
its content as `text`, `image` or ready-made `values`, and metadata to filter on. Writing an existing id replaces
it. The answer (and `count()`) means stored; `query` and `get` see the write later — often seconds, sometimes 10+
minutes (the index applies writes asynchronously). Never wait or poll for a write to become searchable.

**Parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `vectors` | [`VectorUpsertItem[]`](#vectorupsertitem) | yes | The items to store; each has exactly one of `text`, `image` or `values`. |

**Returns** `Promise<{ upserted, count, usage }>` — How many were written, how many the environment now holds, and what it cost.

| Field | Type | Always present | Description |
|---|---|---|---|
| `upserted` | `number` | yes | How many items were written. |
| `count` | `number` | yes | How many items the environment holds now. |
| `usage` | `{ credits }` | yes | What the call cost. |
| `usage.credits` | `number` | yes | Credits charged for this call. |

**Errors** — besides the [errors every call can throw](https://www.totalum.app/docs/sdk#errors):

| Code | HTTP | When |
|---|---|---|
| `VALIDATION_ERROR` | 400 | More than 100 items or 8 images, duplicate ids, an item with no or several contents, a metadata key starting with `_`, or metadata over 9 KB. |
| `VECTORS_LIMIT_REACHED` | 403 | The plan's stored vectors per environment are used up; delete some or upgrade. |
| `FILE_TOO_LARGE` | 413 | An image is over 20 MB. |
| `AI_PROVIDER_UNAVAILABLE` | 502 | The text or image could not be embedded; retry. |
| `PROVIDER_UNAVAILABLE` | 503 | The vector store is unavailable (or being set up: retry in a minute). |

**Example**

```ts
await totalum.vectors.upsert([
  { id: 'faq-12', text: 'Refunds are possible for 30 days after purchase.', metadata: { source: 'faq', tag: 'billing' } },
  { id: 'product-88', image: product.photo.key, metadata: { type: 'product' } },
]);
```

Result:

```json
{ "upserted": 2, "count": 2, "usage": { "credits": 0.0021 } }
```

## `vectors.query`

```ts
vectors.query(input: VectorsQueryInput): Promise<{ matches, usage }>
```

Finds the stored items closest in meaning to a text, an image or a vector — "search by meaning". Results are best
first with a similarity `score`; filter them on metadata. Pass exactly one of `text`, `image` or `values`.

**Parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `input` | [`VectorsQueryInput`](#vectorsqueryinput) | yes | What to search for, how many results, and the metadata filter. |
| `input.text` | `string` | no | Find items close in meaning to this text. Allowed: at least 1 character, at most 20000 characters. |
| `input.values` | `number[]` | no | Find items close to this vector of 1,024 numbers. Allowed: at least 1024 items, at most 1024 items. |
| `input.image` | `string` | no | Find images close to this image (a project file key, a files URL, an `https://` URL or a `data:` URL). Allowed: at least 1 character. |
| `input.space` | `'text' \| 'image'` | no | `text` (default) searches texts; `image` searches images — with `text`, the words are matched against the images. |
| `input.topK` | `number` | no | How many results. Default 5. Allowed: ≥ 1, ≤ 50. |
| `input.filter` | [`VectorFilter`](#vectorfilter) | no | Only items whose metadata matches: `{ source: "faq" }`, `{ page: { $gte: 3 } }`, `{ tag: { $in: ["a", "b"] } }`. Keys: `source`, `type`, `tag`, `group`, `page`. Operators: `$eq`, `$ne`, `$in`, `$nin`, `$lt`, `$lte`, `$gt`, `$gte`. At most 2 KB. |
| `input.includeValues` | `boolean` | no | `true` also returns each match's 1,024 numbers. |

**Returns** `Promise<{ matches, usage }>` — The closest items (best first) and what the query cost.

| Field | Type | Always present | Description |
|---|---|---|---|
| `matches` | [`VectorMatch[]`](#vectormatch) | yes | The closest items, best first. |
| `usage` | `{ credits }` | yes | What the call cost. |
| `usage.credits` | `number` | yes | Credits charged for this call. |

**Errors** — besides the [errors every call can throw](https://www.totalum.app/docs/sdk#errors):

| Code | HTTP | When |
|---|---|---|
| `VALIDATION_ERROR` | 400 | None or several of `text`/`image`/`values`, `topK` over 50, a filter over 2 KB or on another metadata key. |
| `FILE_TOO_LARGE` | 413 | The image is over 20 MB. |
| `AI_PROVIDER_UNAVAILABLE` | 502 | The query could not be embedded; retry. |
| `PROVIDER_UNAVAILABLE` | 503 | The vector store is unavailable; retry later. |

**Examples**

```ts
const { matches } = await totalum.vectors.query({
  text: 'Can I get my money back?',
  topK: 3,
  filter: { source: 'faq' },
});
```

Result:

```json
{
  "matches": [
    { "id": "faq-12", "score": 0.83, "space": "text", "metadata": { "source": "faq", "tag": "billing" } },
    { "id": "faq-07", "score": 0.61, "space": "text", "metadata": { "source": "faq", "tag": "orders" } }
  ],
  "usage": { "credits": 0.0006 }
}
```

```ts
// images that look like a description (image search by words)
const { matches } = await totalum.vectors.query({ text: 'red running shoes', space: 'image', topK: 8 });
```

## `vectors.get`

```ts
vectors.get(ids: string[]): Promise<VectorRecord[]>
```

Reads stored items back by id, with their numbers and metadata. Unknown ids — and ids written in the last seconds
or minutes — are left out of the answer. Free.

**Parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `ids` | `string[]` | yes | Up to 100 ids. |

**Returns** `Promise<VectorRecord[]>` — The items found (possibly fewer than asked).

Each item:

| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | `string` | yes | The item's id. |
| `space` | [`VectorSpace`](#vectorspace) | yes | Its space. |
| `values` | `number[]` | yes | Its 1,024 numbers. |
| `metadata` | [`VectorMetadata`](#vectormetadata) | no | Its metadata. |

**Errors** — besides the [errors every call can throw](https://www.totalum.app/docs/sdk#errors):

| Code | HTTP | When |
|---|---|---|
| `VALIDATION_ERROR` | 400 | No ids, or more than 100. |

**Example**

```ts
const [doc] = await totalum.vectors.get(['faq-12']);
```

Result:

```ts
[
  { "id": "faq-12", "space": "text", "values": [0.0138, -0.0121, 0.0125, …], "metadata": { "source": "faq", "tag": "billing" } }
]
```

## `vectors.delete`

```ts
vectors.delete(ids: string[]): Promise<{ count, deleted, usage }>
```

Deletes items by id — when the row they describe is deleted. Ids that do not exist are ignored.

**Parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `ids` | `string[]` | yes | Up to 1,000 ids. |

**Returns** `Promise<{ count, deleted, usage }>` — How many existed and were deleted, how many the environment still holds, and what it cost.

| Field | Type | Always present | Description |
|---|---|---|---|
| `count` | `number` | yes | How many items the environment still holds. |
| `deleted` | `number` | yes | How many of the ids existed and were deleted. |
| `usage` | `{ credits }` | yes | What the call cost. |
| `usage.credits` | `number` | yes | Credits charged for this call. |

**Errors** — besides the [errors every call can throw](https://www.totalum.app/docs/sdk#errors):

| Code | HTTP | When |
|---|---|---|
| `VALIDATION_ERROR` | 400 | No ids, or more than 1,000. |

**Example**

```ts
const out = await totalum.vectors.delete(['faq-12', 'faq-13']);
```

Result:

```json
{ "deleted": 1, "count": 41, "usage": { "credits": 0 } }
```

## `vectors.count`

```ts
vectors.count(): Promise<{ count, text, image }>
```

How many items this environment stores, in total and per space. Free.

**Returns** `Promise<{ count, text, image }>` — The totals.

| Field | Type | Always present | Description |
|---|---|---|---|
| `count` | `number` | yes | Items stored in this environment. |
| `text` | `number` | yes | Of them, in the `text` space. |
| `image` | `number` | yes | Of them, in the `image` space. |

**Errors** — besides the [errors every call can throw](https://www.totalum.app/docs/sdk#errors):

| Code | HTTP | When |
|---|---|---|
| `PROVIDER_UNAVAILABLE` | 503 | The vector store is unavailable; retry later. |

**Example**

```ts
const counts = await totalum.vectors.count();
```

Result:

```json
{ "count": 42, "text": 40, "image": 2 }
```

## `VectorFilter`

A metadata filter for `vectors.query()`: an object from a metadata key (`source`, `type`, `tag`, `group` — strings — or `page` — a number) to a value it must equal, or to an operator object: `$eq`, `$ne` (equal, not equal), `$in`, `$nin` (one of, none of a list), `$lt`, `$lte`, `$gt`, `$gte` (ranges). Example: `{ source: "faq", page: { $gte: 3 } }`. Strings are compared on their first 64 bytes.

## `VectorMatch`

One result of `vectors.query()`.

| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | `string` | yes | The item's id. |
| `score` | `number` | yes | How similar it is, higher is closer (cosine similarity, up to 1). |
| `space` | [`VectorSpace`](#vectorspace) | yes | The space it was found in. |
| `metadata` | [`VectorMetadata`](#vectormetadata) | no | The item's metadata. |
| `values` | `number[]` | no | The item's 1,024 numbers (with `includeValues: true`). |

## `VectorMetadata`

The metadata stored with an item: an object from string keys (not starting with `_`) to a string, a number, a boolean or a list of strings; at most 9 KB as JSON.

```ts
type VectorMetadata = Record<string, string | number | boolean | string[]>
```

## `VectorRecord`

A stored item, from `vectors.get()`.

| Field | Type | Always present | Description |
|---|---|---|---|
| `id` | `string` | yes | The item's id. |
| `space` | [`VectorSpace`](#vectorspace) | yes | Its space. |
| `values` | `number[]` | yes | Its 1,024 numbers. |
| `metadata` | [`VectorMetadata`](#vectormetadata) | no | Its metadata. |

## `VectorSpace`

Which embedding space an item lives in.

| Value | Meaning |
|---|---|
| `'text'` | Texts, embedded with the `embed` model. |
| `'image'` | Images, embedded with the `embed-image` model; this space also embeds text, so words can find images. |

## `VectorsQueryInput`

What `vectors.query()` searches for: exactly one of `text`, `image` or `values`.

| Name | Type | Required | Description |
|---|---|---|---|
| `text` | `string` | no | Find items close in meaning to this text. Allowed: at least 1 character, at most 20000 characters. |
| `values` | `number[]` | no | Find items close to this vector of 1,024 numbers. Allowed: at least 1024 items, at most 1024 items. |
| `image` | `string` | no | Find images close to this image (a project file key, a files URL, an `https://` URL or a `data:` URL). Allowed: at least 1 character. |
| `space` | `'text' \| 'image'` | no | `text` (default) searches texts; `image` searches images — with `text`, the words are matched against the images. |
| `topK` | `number` | no | How many results. Default 5. Allowed: ≥ 1, ≤ 50. |
| `filter` | [`VectorFilter`](#vectorfilter) | no | Only items whose metadata matches: `{ source: "faq" }`, `{ page: { $gte: 3 } }`, `{ tag: { $in: ["a", "b"] } }`. Keys: `source`, `type`, `tag`, `group`, `page`. Operators: `$eq`, `$ne`, `$in`, `$nin`, `$lt`, `$lte`, `$gt`, `$gte`. At most 2 KB. |
| `includeValues` | `boolean` | no | `true` also returns each match's 1,024 numbers. |

## `VectorUpsertItem`

One item to store with `vectors.upsert()`: an id, exactly one content (`text`, `image` or `values`) and optional metadata.

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | `string` | yes | Your id for the item (usually the row id). Writing an existing id replaces it. Printable ASCII, no spaces. Allowed: at least 1 character, at most 48 characters. |
| `values` | `number[]` | no | Ready-made embedding: exactly 1,024 numbers. Allowed: at least 1024 items, at most 1024 items. |
| `text` | `string` | no | Text to embed with the `embed` model (the `text` space). Allowed: at least 1 character, at most 20000 characters. |
| `image` | `string` | no | An image to embed with the `embed-image` model (the `image` space): a project file key, a files URL, an `https://` URL or a `data:image/…` URL. Allowed: at least 1 character. |
| `space` | `'text' \| 'image'` | no | Only with `values`: the space they were made in, `text` (default) or `image`. |
| `metadata` | [`VectorMetadata`](#vectormetadata) | no | Key/value data kept with the item (strings, numbers, booleans or lists of strings; at most 9 KB; keys must not start with `_`). Queries can filter on `source`, `type`, `tag`, `group` and `page`. |
