# Training

Our training endpoints allow you to programmatically train models based off of datasets you've uploaded to Akkio. They can be viewed as a better-designed v2 of our legacy `/v1/models` route.

Training is a fundamentally long operation, so is surfaced through a polling-based mechanism where you make the following calls:

* One call to `/new` to submit the task
* Polling calls to `/{task_id}/status` to check up on your task's status
* One last call to `/{task_id}/result` once `/status` indicates it's done

## &#x20;Submit Controller

> Model creation via API.

```json
{"openapi":"3.1.0","info":{"title":"Akkio Public API (Beta)","version":"0.1.0"},"paths":{"/api/v1/models/train/new":{"post":{"description":"Model creation via API.","operationId":"_submit_controller_api_v1_models_train_new_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TrainRequestPayload"}}},"required":true},"responses":{"201":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/APITaskStartedResponse"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":" Submit Controller","tags":["Training"]}}},"components":{"schemas":{"TrainRequestPayload":{"additionalProperties":true,"properties":{"dataset_id":{"description":"The ID of the dataset to train the model on.","title":"Dataset Id","type":"string"},"duration":{"description":"Integer corresponding to how much time we should spend on training. Higher values will take longer but generally be more accurate. Allowed values: 10 (Fastest), 60 (High Quality), 300 (Higher Quality), 1800 (Production)","title":"Duration","type":"integer"},"extra_attention":{"default":false,"description":"Helps with predicting rare cases.","title":"Extra Attention","type":"boolean"},"force":{"default":false,"description":"Forces the creation of a new model even if another currently exists.","title":"Force","type":"boolean"},"ignore_fields":{"default":[],"description":"An array of field names to ignore (case sensitive).","items":{"type":"string"},"title":"Ignore Fields","type":"array"},"predict_fields":{"description":"An array of field names to predict (case sensitive).","items":{"type":"string"},"title":"Predict Fields","type":"array"}},"required":["dataset_id","predict_fields","duration"],"title":"TrainRequestPayload","type":"object"},"APITaskStartedResponse":{"additionalProperties":true,"properties":{"task_id":{"description":"The ID of the task that was started. This is generally queryable at a nearby `/status` endpoint to get the current status of the task.","title":"Task Id","type":"string"}},"required":["task_id"],"title":"APITaskStartedResponse","type":"object"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"title":"Detail","type":"array"}},"title":"HTTPValidationError","type":"object"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"title":"Location","type":"array"},"msg":{"title":"Message","type":"string"},"type":{"title":"Error Type","type":"string"}},"required":["loc","msg","type"],"title":"ValidationError","type":"object"}}}}
```

## &#x20;Get Status Controller

> Retrieves the status of the provided model creation call.

```json
{"openapi":"3.1.0","info":{"title":"Akkio Public API (Beta)","version":"0.1.0"},"paths":{"/api/v1/models/train/{task_id}/status":{"get":{"description":"Retrieves the status of the provided model creation call.","operationId":"_get_status_controller_api_v1_models_train__task_id__status_get","parameters":[{"in":"path","name":"task_id","required":true,"schema":{"title":"Task Id","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/APIStatusResponse"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":" Get Status Controller","tags":["Training"]}}},"components":{"schemas":{"APIStatusResponse":{"additionalProperties":true,"properties":{"metadata":{"description":"Metadata, contextually dependent on the status of the task being queried.","discriminator":{"mapping":{"FAILED":"#/components/schemas/APIStatusMetadataFailed","IN_PROGRESS":"#/components/schemas/APIStatusMetadataInProgress","PENDING":"#/components/schemas/APIStatusMetadataPending","SUCCEEDED":"#/components/schemas/APIStatusMetadataSucceeded"},"propertyName":"type"},"oneOf":[{"$ref":"#/components/schemas/APIStatusMetadataPending"},{"$ref":"#/components/schemas/APIStatusMetadataInProgress"},{"$ref":"#/components/schemas/APIStatusMetadataSucceeded"},{"$ref":"#/components/schemas/APIStatusMetadataFailed"}],"title":"Metadata"},"status":{"$ref":"#/components/schemas/TaskStatusEnum","description":"The current status of the task being queried."}},"required":["status","metadata"],"title":"APIStatusResponse","type":"object"},"APIStatusMetadataPending":{"additionalProperties":true,"properties":{"type":{"const":"PENDING","default":"PENDING","enum":["PENDING"],"title":"Type","type":"string"}},"title":"APIStatusMetadataPending","type":"object"},"APIStatusMetadataInProgress":{"additionalProperties":true,"properties":{"estimate_seconds":{"anyOf":[{"type":"number"},{"type":"null"}],"description":"If provided, an estimate of how many seconds we expect this task to take. This value should be treated as a rough estimate on a best-effort basis, not a guarantee.","title":"Estimate Seconds"},"type":{"const":"IN_PROGRESS","default":"IN_PROGRESS","enum":["IN_PROGRESS"],"title":"Type","type":"string"}},"title":"APIStatusMetadataInProgress","type":"object"},"APIStatusMetadataSucceeded":{"additionalProperties":true,"properties":{"location":{"description":"The path at which you can submit a GET request to retrieve the result of the successful job. May require proper authentication or authorization to access.","title":"Location","type":"string"},"type":{"const":"SUCCEEDED","default":"SUCCEEDED","enum":["SUCCEEDED"],"title":"Type","type":"string"}},"required":["location"],"title":"APIStatusMetadataSucceeded","type":"object"},"APIStatusMetadataFailed":{"additionalProperties":true,"properties":{"error":{"default":"Unable to complete request. Please verify your inputs, try again later, or get in touch at support@akkio.com.","description":"If provided, a text representation of what went wrong with the task, including if any action on your part may rectify the issue.","title":"Error","type":"string"},"type":{"const":"FAILED","default":"FAILED","enum":["FAILED"],"title":"Type","type":"string"}},"title":"APIStatusMetadataFailed","type":"object"},"TaskStatusEnum":{"description":"Celery task status enum. Update apps/web-backend-api/src/types/TaskStatusEnum.ts if you update this enum.","enum":["PENDING","IN_PROGRESS","SUCCEEDED","FAILED","UNKNOWN_TIMEOUT"],"title":"TaskStatusEnum","type":"string"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"title":"Detail","type":"array"}},"title":"HTTPValidationError","type":"object"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"title":"Location","type":"array"},"msg":{"title":"Message","type":"string"},"type":{"title":"Error Type","type":"string"}},"required":["loc","msg","type"],"title":"ValidationError","type":"object"}}}}
```

## &#x20;Get Result Controller

> Retrieves the result of a model creation call.

```json
{"openapi":"3.1.0","info":{"title":"Akkio Public API (Beta)","version":"0.1.0"},"paths":{"/api/v1/models/train/{task_id}/result":{"get":{"description":"Retrieves the result of a model creation call.","operationId":"_get_result_controller_api_v1_models_train__task_id__result_get","parameters":[{"in":"path","name":"task_id","required":true,"schema":{"title":"Task Id","type":"string"}}],"responses":{"200":{"content":{"application/json":{"schema":{"title":"Response  Get Result Controller Api V1 Models Train  Task Id  Result Get","type":"object"}}},"description":"Successful Response"},"422":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}},"description":"Validation Error"}},"summary":" Get Result Controller","tags":["Training"]}}},"components":{"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"title":"Detail","type":"array"}},"title":"HTTPValidationError","type":"object"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"title":"Location","type":"array"},"msg":{"title":"Message","type":"string"},"type":{"title":"Error Type","type":"string"}},"required":["loc","msg","type"],"title":"ValidationError","type":"object"}}}}
```

***

## Example Call Sequence[​](https://api-docs.akkio.com/endpoints/training#example-call-sequence) <a href="#example-call-sequence" id="example-call-sequence"></a>

Here's a rough outline of how you'd make a request to the Inference bulk predictions endpoints.

#### HTTP Headers[​](https://api-docs.akkio.com/endpoints/training#http-headers) <a href="#http-headers" id="http-headers"></a>

| Header Name | Required | Value                                                                                          |
| ----------- | -------- | ---------------------------------------------------------------------------------------------- |
| X-API-Key   | Yes      | Your team's API key. See [Authentication](https://api-docs.akkio.com/concepts/authentication). |

#### 1. Create Request[​](https://api-docs.akkio.com/endpoints/training#1-create-request) <a href="#id-1-create-request" id="id-1-create-request"></a>

First, we'll submit the task into our asynchronous processing queue.

`POST /api/v1/models/train/new`

```
{
  "dataset_id": "YTV32jCdVf5DbcMxzvX5",
  "predict_fields": ["Positive Lead"]
}
```

You'll receive an object like this containing a task id:

```
{
  "task_id": "<task_id>"
}
```

We'll use this in the next request.

#### 2. Query for Task Status[​](https://api-docs.akkio.com/endpoints/training#2-query-for-task-status) <a href="#id-2-query-for-task-status" id="id-2-query-for-task-status"></a>

Next, we'll query the status endpoint at a cadence to see whether the task is complete yet. This request might look something like this:

`GET /api/v1/models/train/<task_id>/status`

Note that you must use the same Task ID that you received from the task creation endpoint above.

This will provide you with a `status` field set to either `SUBMITTED`, `IN_PROGRESS`, `FAILED`, or `SUCCEEDED`. You can read more about each state on the [Asynchronous Endpoints](https://api-docs.akkio.com/concepts/asynchronous-endpoints) page.

Here's an example response you might get:

```
{
  "status": "IN_PROGRESS",
  "metadata": {
    "type": "IN_PROGRESS"
  }
}
```

You should retry ("poll") this endpoint at a regular cadence until you get a response that looks something like this:

```
{
  "status": "SUCCEEDED",
  "metadata": {
    "type": "SUCCEEDED",
    "location": "/api/v1/models/train/<task_id>/result"
  }
}
```

note

The `location` field is always relative to the **API root** (`https://api.akkio.com/api/v1`), *not* the overall website root (`https://api.akkio.com`). You'll need to remember to construct the end URL from the site name, API root, and the provided location.

Armed with this information, we'll move to the last request.

#### 3. Query for Result[​](https://api-docs.akkio.com/endpoints/training#3-query-for-result) <a href="#id-3-query-for-result" id="id-3-query-for-result"></a>

Armed with the location we got from the status call, we'll make a request for the end result.

`GET /api/v1/models/train/<task_id>/result`

You'll get a response that looks something like this:

```
{
  "status": "success",
  "model_id": "AyooDGG4IB7iJDkgLKJR",
  "stats": [
    [
      {
        "field": 12,
        "field_name": "Positive Lead",
        "field_type": "category",
        "class": 0,
        "class_name": "0",
        "count": 19,
        "true positives": 19,
        "false positives": 0,
        "false negatives": 0,
        "precision": 1.0,
        "recall": 1.0,
        "f1": 1.0,
        "frequency": 0.95
      },
      {
        "field": 12,
        "field_name": "Positive Lead",
        "field_type": "category",
        "class": 1,
        "class_name": "1",
        "count": 1,
        "true positives": 1,
        "false positives": 0,
        "false negatives": 0,
        "precision": 1.0,
        "recall": 1.0,
        "f1": 1.0,
        "frequency": 0.05
      }
    ]
  ],
  "field_importance": {
    "Job Title": 0.09528297930955887,
    "Years of Experience": 0.09974530339241028,
    "Company Size": 0.08637341856956482,
    "Industry": 0.08510678261518478,
    "Location": 0.050445690751075745,
    "Webinars Attended": 0.1286168396472931,
    "Whitepapers Downloaded": 0.10489732772111893,
    "Pages Visited": 0.08934492617845535,
    "Days Since Last Visit": 0.07931949943304062,
    "Email Open Rate": 0.08199360221624374,
    "Email Click Rate": 0.05456322059035301,
    "Responded to Survey": 0.04431045055389404,
    "Positive Lead": 8.27786672541464e-10
  },
  "data_story": [
    {
      "name": "Positive Lead",
      "type": "category",
      "outcomes": [
        {
          "outcome": "0",
          "causes": [
            {
              "field": "Webinars Attended",
              "top_value": "3",
              "bottom_value": "3"
            },
            {
              "field": "Whitepapers Downloaded",
              "top_value": "3",
              "bottom_value": "7"
            },
            {
              "field": "Years of Experience",
              "top_value": "6",
              "bottom_value": "7"
            },
            {
              "field": "Job Title",
              "top_value": "Executive",
              "bottom_value": "Assistant"
            },
            {
              "field": "Pages Visited",
              "top_value": "27",
              "bottom_value": "1"
            }
          ],
          "top_case": 1.0,
          "avg_case": 0.94,
          "bottom_case": 1.0
        },
        {
          "outcome": "1",
          "causes": [
            {
              "field": "Webinars Attended",
              "top_value": "3",
              "bottom_value": "3"
            },
            {
              "field": "Whitepapers Downloaded",
              "top_value": "7",
              "bottom_value": "3"
            },
            {
              "field": "Years of Experience",
              "top_value": "7",
              "bottom_value": "6"
            },
            {
              "field": "Job Title",
              "top_value": "Assistant",
              "bottom_value": "Executive"
            },
            {
              "field": "Pages Visited",
              "top_value": "1",
              "bottom_value": "27"
            }
          ],
          "top_case": 0.0,
          "avg_case": 0.06,
          "bottom_case": 0.0
        }
      ]
    }
  ]
}
```
