> ## 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.

# Python SDK

> Overview of the Python Metal SDK.

<Card title="Python SDK" icon="github" href="https://github.com/getmetal/metal-python">
  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}
pip3 install metal-sdk
```

# Retrieval

## App Setup

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

```python theme={null}
from metal_sdk.metal import Metal

metal = Metal("api_key", "client_id", "index_id")
```

## Adding an App

| Param     | Type   | Description                                 |
| --------- | ------ | ------------------------------------------- |
| `name`    | string | Name of the App.                            |
| `indexes` | array  | An array of the index connected to the app. |

```python theme={null}
metal.add_app({"name": "My App", "indexes": ["index1"]})
```

## Get One App

| Param    | Type   | Description    |
| -------- | ------ | -------------- |
| `app_id` | string | ID of the App. |

```python theme={null}
metal.get_app("app_id")
```

## Get All Apps

```python theme={null}
metal.get_apps()
```

## Updating an App

| Param     | Type              | Description                                          |   |
| --------- | ----------------- | ---------------------------------------------------- | - |
| `app_id`  | 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.  |   |

```python theme={null}

metal.update_app("app_id", {"name": "Updated Metal App", "indexes": ["index1"]})

```

## Adding an Index

### Payload

| 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"). |

```python theme={null}
metal = Metal("api_key", "client_id")

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"
      }
    ]
}

metal.add_index(payload)
```

## Get One Index

| Param      | Type   | Description                                              |
| ---------- | ------ | -------------------------------------------------------- |
| `index_id` | string | The unique identifier of the index you want to retrieve. |

```python theme={null}
metal.get_index("index_id")
```

## Indexing a Document

| Param      | Type   | Description                                      |
| ---------- | ------ | ------------------------------------------------ |
| `payload`  | dict   | Dictionary with index parameters                 |
| `index_id` | string | Optional index id where record will get indexed. |

#### Payload

| Param       | Type      | Description                                              |
| ----------- | --------- | -------------------------------------------------------- |
| `id`        | string    | Optional identifier for your embedding.                  |
| `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.                   |
| `metadata`  | object    | A flexible metdata object to be stored w/ the embedding. |

```python theme={null}
metal.index({ "text": "text-to-index" }, "index_id")
```

## Multi(Bulk) Indexing

You can index up to `100` records in a single request.

| Param     | Type             | Description         |
| --------- | ---------------- | ------------------- |
| `payload` | BulkIndexItem\[] | Array of bulk items |

#### BulkIndexItem

| Param       | Type      | Description                                              |
| ----------- | --------- | -------------------------------------------------------- |
| `id`        | string    | Optional identifier for your embedding.                  |
| `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.                   |
| `metadata`  | object    | A flexible metdata object to be stored w/ the embedding. |

```python theme={null}
metal.index_many([{ "text": "blacksabbath", "index": "index-id" }, { "text": "ironmaiden", "index": "index-id" }])
```

## Searching

`self, payload: SearchPayload = {}, index_id=None, ids_only=False, limit=1`

| Param      | Type    | Description                                          |
| ---------- | ------- | ---------------------------------------------------- |
| `payload`  | dict    | search payload.                                      |
| `index_id` | string  | Id of index to search.                               |
| `ids_only` | boolean | Optional return only the ids                         |
| `limit`    | number  | Number of documents returned by the API (default=1). |

#### Payload

| 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`   | dict\[]   | List of filters to match in search.               |

#### Filter

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

#### Filter Item

| Param      | Type             | Description                                      |
| ---------- | ---------------- | ------------------------------------------------ |
| `value`    | string \| number | Value to match.                                  |
| `field`    | string           | Field to filter.                                 |
| `operator` | string           | Possible values: `eq`, `gt`, `gte`, `lt`, `lte`. |

```python theme={null}
results = metal.search({ "text": "term-to-search", "filters": { "and": [{"field": "band", "value": "Black Sabbath", "operator":"eq"}]} }, index_id="indexID", limit=10)
```

## Get One Document

| Param      | Type   | Description                         |
| ---------- | ------ | ----------------------------------- |
| `id`       | string | The ID of the document to retrieve. |
| `index_id` | string | Optional. Id of index to search.    |

```python theme={null}
document = metal.get_one("document_id_123")
```

## Get Many Documents

| Param      | Type          | Description                                                                                               |
| ---------- | ------------- | --------------------------------------------------------------------------------------------------------- |
| `ids`      | list of str   | A list of document IDs to retrieve.                                                                       |
| `index_id` | str, optional | The ID of the index from which to retrieve documents. If not provided, the default index ID will be used. |

```python theme={null}
document = metal.get_many("[document_id_123, document_id_456]")
```

## Get Queries

| Param      | Type   | Description                      |
| ---------- | ------ | -------------------------------- |
| `index_id` | string | The ID of the Index to retrieve. |

```python theme={null}
queries = metal.get_queries("index_id")
```

## Delete One

| Param          | Type   | Description                                    |
| -------------- | ------ | ---------------------------------------------- |
| `embedding_id` | string | The ID of the document or embedding to delete. |
| `index_id`     | string | The ID of the index containing the document.   |

```python theme={null}
metal.delete_one("embedding_id", "index_id")
```

## Delete Many (Bulk)

| Param           | Type   | Description                                              |
| --------------- | ------ | -------------------------------------------------------- |
| `embedding_ids` | list   | A list of IDs for the documents or embeddings to delete. |
| `index_id`      | string | The ID of the index containing the documents.            |

```python theme={null}
embedding_ids_to_delete = ["id1", "id2", "id3"]
metal.delete_many(embedding_ids_to_delete, "index_id")
```

# Memory (Motorhead)

## App Setup

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

```python theme={null}
from metal_sdk.motorhead import Motorhead

# Managed
motorhead = Motorhead({ "api_key": "api_key", "client_id": "client-id" })

# Self-hosted
motorhead = Motorhead({ "base_url": "https://motorhead.yourdomain.com" })
```

## Create Memory

```python theme={null}
class Message:
    content: str
    role: str  # "AI" or "Human"

class Memory:
    messages: list  # List of Message instances
    context: str
```

| Param        | Type      | Description                                                              |
| ------------ | --------- | ------------------------------------------------------------------------ |
| `session_id` | 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                            |

```python theme={null}
memory_payload = {
  "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",
}


motorhead.add_memory("session-id", memory_payload)
```

## Get Memory

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

```python theme={null}
motorhead.get_memory("session-id")
```

## Delete Memory

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

```python theme={null}
motorhead.delete_memory("session-id")
```

# Datasources

## Add a Datasource

| Param            | 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

| Param         | 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.    |

```python theme={null}
from metal_sdk.metal import Metal

payload = {
    "name": "my datasource",
    "sourcetype": "File",
    "autoExtract": True,
    "metadataFields": [
      {
        "name": "band",
        "type": "string",
        "description": "Which heavy metal band is represented by the iconic mascot Eddie?"
      }
    ]
}

metal.add_datasource(payload)
```

## Update Datasource

### Parameters

| Param            | 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. |

### Example

```python theme={null}
payload = {
    "name": "updated_datasource",
    "sourcetype": "Text",
    "autoExtract": False,
    "metadataFields": [
        {
            "name": "song",
            "type": "string",
            "description": "Which was Iron Maiden's first single?"
        }
    ]
}

metal.update_datasource("existing_datasourceId", payload)
```

## Get Datasource

### Parameters

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

### Example

```python theme={null}
metal.get_datasource("existing_datasourceId")
print(response)  # This will display detailed information about the Datasource
```

## List Datasources

### Parameters

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

```python theme={null}
metal.get_all_datasources(page=1, limit=10)
```

## Delete Datasource

### Parameters

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

### Example

```python theme={null}
response = metal.delete_datasource("datasourceID")
print(response)  # Expected: "Datasource successfully deleted."
```

# Data Entities

## Add a Data entity

`.pdf`, `doc`, `.docx`, `.xlsx`, and `.csv` are accepted.

## Parameters

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

## Example

```python theme={null}
results = metal.add_data_entity("datasource_id", "./file_path.csv", metadata=metadata)
```

## Get Data Entity

### Parameters

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

```python theme={null}
metal.get_data_entity("data_entity_id")
```

## List Data Entities

### Parameters

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

```python theme={null}
metal.get_all_data_entities("datasource_id", page=1, limit=10)
```

## Delete Data Entity

### Parameters

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

```python theme={null}
metal.delete_data_entity("data_entity_id")
```
