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

# Node SDK

> Overview of the Node Metal SDK.

<Card title="Node SDK" icon="github" href="https://github.com/getmetal/metal-ts">
  Visit the GitHub Repo
</Card>

<Note>
  You'll need to [Create an API Key](/misc-get-keys) to
  [Authentication](/api-reference/introduction#authentication) with Metal.
</Note>

## Installation

```bash theme={null}
npm install @getmetal/metal-sdk
# or
yarn add @getmetal/metal-sdk
```

# Retrieval

<Note>
  You'll need to [Create an API Key](/misc-get-keys) to
  [Authenticate](/api-reference/introduction#authentication) with Metal.
</Note>

## App Setup

| Param      | Type   | Description                                                                     |
| ---------- | ------ | ------------------------------------------------------------------------------- |
| `apiKey`   | string | The API Key for your Org. [Learn more.](/misc-get-keys)                         |
| `clientId` | string | The Client ID for your Org. [Learn more.](/misc-get-keys)                       |
| `indexId`  | string | The ID of the index you want to connect with. [Learn more.](/misc-create-index) |

```ts theme={null}
import { Metal } from "@getmetal/metal-sdk";
const metal = new Metal("pk_123", "ci_123", "index-id");
```

## `addApp()`

#### Parameters

| Param  | Type   | Description      |
| ------ | ------ | ---------------- |
| `name` | string | Name of the app. |

```ts theme={null}
const app = await metal.addApp({
    name: "My App",
    indexes: ["index-id"]
});
```

## `getApp()`

#### Parameters

| Param   | Type   | Description             |
| ------- | ------ | ----------------------- |
| `appId` | string | Identifier for the app. |

```ts theme={null}
const app = await metal.getApp("app-id");
```

## `getApps()`

```ts theme={null}
const apps = await metal.getApps();
```

## `updateApp()`

#### Parameters

| Param     | Type              | Description                                          |   |
| --------- | ----------------- | ---------------------------------------------------- | - |
| `appId`   | string            | The unique identifier of the app you want to update. |   |
| `name`    | string (optional) | The updated name for the App.                        |   |
| `indexes` | array (optional)  | An updated array of the index connected to the app.  |   |

```ts theme={null}
const app = await metal.updateApp("app-id", { name: "updated name", indexes: ["index-id"] });
```

## `addIndex()`

#### Parameters

| Param        | Type   | Description                                                          |
| ------------ | ------ | -------------------------------------------------------------------- |
| `model`      | string | Identifier for the model being used, e.g., "text-embedding-ada-002". |
| `name`       | string | Name of the index.                                                   |
| `datasource` | string | Unique identifier for the Datasource.                                |
| `indexType`  | string | Type of index structure, e.g., "FLAT", "HNSW".                       |
| `dimensions` | number | Number of dimensions for the index. e.g.1536                         |
| `filters`    | array  | An array of filters specifying fields for advanced searching.        |

#### Filters

| Param   | Type   | Description                                       |
| ------- | ------ | ------------------------------------------------- |
| `field` | string | Name of the attribute you wish to filter by.      |
| `type`  | string | Type of the attribute (e.g., "string", "number"). |

```ts theme={null}
const payload = {
    model: "text-embedding-ada-002",
    name: "my index",
    datasource: "<datasource_id>",
    indexType: "FLAT",
    dimensions: 1536,
    filters: [
        {
            field: "name",
            type: "string"
        },
        {
            field: "age",
            type: "number"
        }
    ]
};

const newIndex = await metal.addIndex(payload);

```

## `getIndex()`

#### Parameters

| Param     | Type   | Description               |
| --------- | ------ | ------------------------- |
| `indexId` | string | Identifier for the index. |

```ts theme={null}
const index = await metal.getIndex("index-id");
```

## `index()`

Add a single embedding to an index. When invoked, we will generate an embedding with one of the below embedding params and store it into a vector db.

<Note>
  You can only pass one of the following fields: `text`, `imageUrl`, or
  `embedding`. We only embed one field in a single request.
</Note>

```ts theme={null}
const textEmbedding = await metal.index({ text: "Rocket" });
// or
const imgEmbedding = await metal.index({ imageUrl: "https://path-to.img" });
// or
const rawEmbedding = await metal.index({ embedding: [0.1, 0.2, 0.3] });
```

You can also pass an optional `id` and `metadata` object to be stored with the embedding. Eg.

```ts theme={null}
const opts = {
  id: "rocket1",
  metadata: {
    category: "space",
    another: "field",
  },
};

const embedding = await metal.index({
  text: "Rocket",
  ...opts,
});
```

#### Parameters

| Param               | Type      | Description                                                        |
| ------------------- | --------- | ------------------------------------------------------------------ |
| Embed - `embedding` | number\[] | Raw embedding to be indexed.                                       |
| Embed - `imageUrl`  | string    | A URL for an image to be embedded and indexed.                     |
| Embed - `text`      | string    | The text to be embedded and indexed.                               |
| `id`                | string    | Optional. Identifier for your embedding.                           |
| `metadata`          | object    | Optional. A flexible metdata object to be stored w/ the embedding. |

## `indexMany()`

Bulk add multiple embedding documents to an index. When invoked, we will generate an embedding with one of the below "Embed" params and store it in a vector index.

<Note>
  You can only pass one of the following fields: `text`, `imageUrl`, or
  `embedding`. We only embed one field in a single request.
</Note>

#### Parameters

| Param       | Type      | Description                                                        |
| ----------- | --------- | ------------------------------------------------------------------ |
| `index`     | string    | Required. Index id.                                                |
| `embedding` | number\[] | Raw embeddings to be indexed.                                      |
| `imageUrl`  | string    | A URL for an image to be vectorized and indexed.                   |
| `text`      | string    | The text to be vectorized and indexed.                             |
| `id`        | string    | Optional. identifier for your embedding.                           |
| `metadata`  | object    | Optional. A flexible metdata object to be stored w/ the embedding. |

```typescript theme={null}
await metal.indexMany([
  { text: "Megadeth", index: "index-id" },
  { text: "Metallica", index: "index-id" },
]);
```

## `search()`

#### Parameters

| Param       | Type      | Description                                       |
| ----------- | --------- | ------------------------------------------------- |
| `embedding` | number\[] | Raw embeddings to be searched.                    |
| `imageUrl`  | string    | A URL for an image to be vectorized and searched. |
| `text`      | string    | The text to be vectorized and searched.           |
| `filters`   | Filter    | Filters included for filtered search.             |
| `indexId`   | string    | Optional index id where record will get indexed.  |
| `idsOnly`   | boolean   | Return only the ids of the documents.             |
| `limit`     | number    | Number of documents returned by the API           |

**Filter Object**

| Param | Type          | Description                                         |
| ----- | ------------- | --------------------------------------------------- |
| `and` | FilterItem\[] | And clause, all members have to be satisfied.       |
| `or`  | FilterItem\[] | Or clause, at least one member has to be satisfied. |

**Filter Item**

| Param      | Type             | Description                             |
| ---------- | ---------------- | --------------------------------------- |
| `field`    | string           | Name of the field to filter             |
| `value`    | string \| number | Value to match the filter               |
| `operator` | string           | One of: `eq`, `gt`, `gte`, `lt`, `lte`. |

```typescript theme={null}
const results = await metal.search({
  text: "term-to-search",
  filters: { and: [{ field: "favoriteNumber", value: 666, operator:"lt"}] },
  indexId: "indexId",
  idsOnly: false,
  limit: 100,
});
```

## `getOne()`

Retrieve a single embedding document.

#### Parameters

| Param     | Type   | Description                                       |
| --------- | ------ | ------------------------------------------------- |
| `id`      | string | The ID of the document to retrieve.               |
| `indexId` | string | Optional. index id where record will get indexed. |

```typescript theme={null}
const document = await metal.getOne("documentId-123");
```

## `getMany()`

#### Parameters

| Name      | Type          | Description                                                                                               |
| --------- | ------------- | --------------------------------------------------------------------------------------------------------- |
| `ids`     | Array of str  | An array of document IDs to retrieve.                                                                     |
| `indexId` | str, optional | The ID of the index from which to retrieve documents. If not provided, the default index ID will be used. |

```ts theme={null}

const documentIDs = ['document_id_123', 'document_id_456'];
const result = await Metal.getMany(documentIDs);

```

## `getQueries()`

#### Parameters

| Name      | Type | Description                                           |
| --------- | ---- | ----------------------------------------------------- |
| `indexId` | str  | The ID of the index from which to retrieve documents. |

```typescript theme={null}
const queries = await metal.getQueries("index-id");
```

## `deleteOne()`

Delete a single embedding document.

#### Parameters

| Param     | Type   | Description                                            |
| --------- | ------ | ------------------------------------------------------ |
| `id`      | string | The ID of the document to delte.                       |
| `indexId` | string | Optional. The ID of the index containing the document. |

```typescript theme={null}
const document = await metal.deleteOne("documentId-123");
```

## `deleteMany()`

Deletes multiple documents in an index based on their IDs.

#### Parameters

| Param     | Type      | Description                                            |
| --------- | --------- | ------------------------------------------------------ |
| `id`      | string\[] | The IDs of the documents to delete.                    |
| `indexId` | string    | Optional. The ID of the index containing the document. |

```typescript theme={null}
const document = await metal.deleteOne("documentId-123");
```

# Memory (Motorhead)

## App Setup

| Param      | Type   | Description                                                                                                                                                 |
| ---------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiKey`   | string | For Managed. The API Key for your Org. \[details]\(- [Create an API Key](/misc-get-keys) for [Authentication](/api-reference/introduction#authentication).  |
| `clientId` | string | For Managed.The Client ID for your Org. \[details]\(- [Create an API Key](/misc-get-keys) for [Authentication](/api-reference/introduction#authentication). |
| `baseUrl`  | string | For Self-hosted. The URL path to your motorhead instance                                                                                                    |

```typescript theme={null}
import { Motorhead } from "@getmetal/metal-sdk";

// Managed
const motorhead = new Motorhead({ apiKey: "apiKey", clientId: "clientId" });

// Self-hosted
const motorhead = new Motorhead({
  baseUrl: "https://motorhead.yourdomain.com",
});
```

## `addMemory()`

```ts theme={null}
interface Memory {
  messages: {
    content: string;
    role: "AI" | "Human";
  };
  context: string;
}
```

| Param       | Type      | Description                                                              |
| ----------- | --------- | ------------------------------------------------------------------------ |
| `sessionId` | string    | The ID of the session. If the session does not exist, it will create one |
| `memory`    | Memory\[] | A memory payload to update the session memory                            |

```ts theme={null}
const memoryPayload = {
  messages: [
    { role: "Human", content: "Who is the best vocalist of all time?" },
    { role: "AI", content: "Ozzy!" },
  ],
  context:
    "User ask what can he eat in Colombia. The AI responds arepas are really nice",
};

await motorhead.addMemory("session-id", memoryPayload);
```

## `getMemory()`

| Param       | Type   | Description                                  |
| ----------- | ------ | -------------------------------------------- |
| `sessionId` | string | The ID of the session to retrieve memory for |

```ts theme={null}
await motorhead.getMemory("session-id");
```

## `deleteMemory()`

| Param       | Type   | Description                                |
| ----------- | ------ | ------------------------------------------ |
| `sessionId` | string | The ID of the session to delete memory for |

```ts theme={null}
await motorhead.deleteMemory("session-id");
```

# Datasources

## `addDatasource()`

Add a new Datasource to your Metal instance.

#### Parameters

| Name             | Type    | Description                                                                                                                               |
| ---------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `name`           | string  | Name of the Datasource.                                                                                                                   |
| `sourcetype`     | string  | Type of the source. It can either be 'File' or 'Text'.                                                                                    |
| `autoExtract`    | boolean | Flag indicating whether auto-extraction is enabled.                                                                                       |
| `metadataFields` | array   | An array of fields specifying which attributes you wish to extract. Each object should have `name`, `type`, and `description` properties. |

#### Metadata Fields

| Name          | Type    | Description                                                         |
| ------------- | ------- | ------------------------------------------------------------------- |
| `name`        | string  | Name of the attribute you wish to extract.                          |
| `type`        | string  | Type of the attribute (e.g., "String", "Number").                   |
| `description` | string  | Brief description or example of the attribute.                      |
| `autoExtract` | boolean | Determines if attribute will be auto extracted from content or not. |

```ts theme={null}
const dataSourcePayload = {
    name: "my datasource",
    sourcetype: "File",
    autoExtract: true,
    metadataFields: [
      {
        name: "band",
        type: "String",
        description: "Which heavy metal band is represented by the iconic mascot Eddie?",
        autoExtract: true,
      }
    ]
};

const response = await metal.addDatasource(datasourcePayload);
```

## `updateDatasource()`

#### Parameters

| Name             | Type    | Description                                                     |
| ---------------- | ------- | --------------------------------------------------------------- |
| `datasourceId`   | string  | Identifier of the Datasource you want to update.                |
| `name`           | string  | Updated name of the Datasource.                                 |
| `sourcetype`     | string  | Updated type of the source. Either 'File' or 'Text'.            |
| `autoExtract`    | boolean | Updated flag indicating whether auto-extraction is enabled.     |
| `metadataFields` | array   | Updated fields specifying which attributes you wish to extract. |

```ts theme={null}

const updatedDatasourcePayload = {
    name: "updated_datasource",
    sourcetype: "Text",
    autoExtract: false,
    metadataFields: [
        {
            name: "song",
            type: "String",
            description: "Which was Iron Maiden's first single?"
        }
    ]
};

const response = await Metal.updateDatasource("existing_dataSourceId", updatedDataSourcePayload);

```

## `getDatasource()`

#### Parameters

| Name           | Type   | Description                                                          |
| -------------- | ------ | -------------------------------------------------------------------- |
| `dataSourceId` | string | Identifier of the Datasource you want to retrieve information about. |

```ts theme={null}
const datasourceId = "existing_datasourceId";
const response = await Metal.getDatasource(datasourceId);
```

## `getAllDatasources()`

#### Parameters

| Name    | Type   | Description                                                                                   |
| ------- | ------ | --------------------------------------------------------------------------------------------- |
| `limit` | number | (Optional) The maximum number of Datasources to return. Default is 10, with a maximum of 100. |
| `page`  | number | (Optional) The page number for pagination. Should be a positive integer up to 100.            |

```ts theme={null}

const limit = 10;
const page = 2;

const response = await Metal.getAllDatasources({ limit, page });
```

## `deleteDatasource()`

#### Parameters

| Name           | Type   | Description                                  |
| -------------- | ------ | -------------------------------------------- |
| `datasourceId` | string | The ID of the Datasource you want to delete. |

```ts theme={null}
const datasourceId = 'your_data_source_id';
const response = await Metal.deleteDatasource(datasourceId);
```

# Data Entities

## `addDataEntity()`

#### Parameters

| Name           | Type   | Description                                      |
| -------------- | ------ | ------------------------------------------------ |
| `datasourceId` | string | The ID of the datasource where the file belongs. |
| `filepath`     | string | The local file path of the file to upload.       |
| `metadata`     | object | Additional Metadata that isn't extracted.        |

### Example

```ts theme={null}

const datasourceId = 'your_datasource_id';
const filePath = './file_path.csv';

const results = await metal.addDataEntity({
  datasource: datasourceId,
  filepath,
  metadata: {
    band: 'Iron Maiden',
    song: 'The Trooper',
  },
});

```

## `getDataEntity()`

#### Parameters

| Name | Type   | Description                                     |
| ---- | ------ | ----------------------------------------------- |
| `id` | string | The ID of the data entity you want to retrieve. |

```ts theme={null}

const dataEntityId = 'your_dataentity_id';

const dataEntity = await metal.getDataEntity(dataEntityId);
```

## `getAllDataEntities()`

#### Parameters

| Name           | Type   | Description                                                                                     |
| -------------- | ------ | ----------------------------------------------------------------------------------------------- |
| `datasourceID` | string | The ID of the datasource for which you want to list the data entities.                          |
| `limit`        | number | (Optional) The maximum number of data entities to return. Default is 10, with a maximum of 100. |
| `page`         | number | (Optional) The page number for pagination. Should be a positive integer up to 100.              |

```ts theme={null}

const datasourceID = 'your_datasource_id';
const page = 1;
const limit = 10;

const dataEntities = await Metal.listDataEntities(datasourceID, page, limit);
```

## `deleteDataEntity()`

#### Parameters

| Name | Type   | Description                                   |
| ---- | ------ | --------------------------------------------- |
| `id` | string | The ID of the data entity you want to delete. |

### Example

```ts theme={null}

const dataEntityID = 'your_dataentity_id';

const result = await Metal.deleteDataEntity(dataEntityID);
```

***

Checkout the code on [Github](https://github.com/getmetal/metal-ts)
