# Overview

A Blueprint creates related resources in one transaction. Define their templates in order, use context to supply runtime values, and reference records created by earlier entries. If an insert fails, the transaction rolls back.

## Understanding Blueprints

A Blueprint contains an ordered `models` list. Each entry uses an inline `template`, a stored `templateId`, or both. Give an entry a `name` when later entries need its created ID. Use `overrides` to supply shared fields such as `projectId` or `organizationId`.

| Component    | Purpose                                                                                                                                             |
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `models`     | Ordered list of model entries to create                                                                                                             |
| `overrides`  | Key-value pairs applied after `templateId` data but before the per-entry `template`; fields in `template` take priority                             |
| `name`       | Optional label on an entry; exposes the created record's ID to subsequent entries via `{{ blueprint.<name> }}`                                      |
| `templateId` | UUID of a stored Template record whose `data` is used as the base template                                                                          |
| `template`   | Inline object used as the base template, or merged on top of a `templateId` result                                                                  |
| `context`    | Caller-supplied values available during interpolation as `{{ <key> }}`; the key `blueprint` is reserved and always refers to the named-model ID map |

---

## Data model

### Blueprint

Store a reusable definition as a `Blueprint` record. Its `data` field contains a [`BlueprintObject`](#blueprintobject).

| Field        | Type   | Required    | Description                                                                                                       |
| ---------------- | -------- | -------------- | ------------------------------------------------------------------------------ |
| `id`             | uuid     | Auto-generated | Unique identifier                                                     |
| `name`           | string   | Yes            | Human-readable label for the Blueprint                                |
| `data`           | object   | Yes            | The [`BlueprintObject`](#blueprintobject) payload; validated on write |
| `type`           | enum     | Yes            | `assistant`, `mapper`, or `automation`; must match the models in `data`        |
| `metadata`       | object   | No             | Catalogue information such as description and icon                             |
| `context`        | object   | No             | JSON Schema used to validate caller context when running this stored Blueprint |
| `tags`           | string[] | No             | Catalogue tags                                                                 |
| `organizationId` | uuid     | No             | Scopes the Blueprint to an Organisation          |
| `createdAt`      | datetime | Auto-generated | Creation timestamp                                                    |
| `updatedAt`      | datetime | Auto-generated | Last-updated timestamp                                                |

**Example:**

```json
{
  "id": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
  "name": "Standard assistant setup",
  "type": "assistant",
  "data": {
    "models": [
      {
        "name": "KB",
        "model": "ai.KnowledgeBase",
        "template": { "name": "{{ clientName }} KB" }
      },
      {
        "model": "conversational.Assistant",
        "templateId": "f1e2d3c4-b5a6-4978-8b7c-6d5e4f3a2b1c",
        "template": { "knowledgeBaseIds": ["{{ blueprint.KB }}"] }
      }
    ]
  },
  "organizationId": "c3d4e5f6-a7b8-4c9d-0e1f-2a3b4c5d6e7f",
  "createdAt": "2026-01-15T10:00:00.000Z",
  "updatedAt": "2026-01-15T10:00:00.000Z"
}
```

---

### BlueprintObject

The `BlueprintObject` is the structure stored in `Blueprint.data` and also accepted inline by the `/run` endpoint.

| Field        | Type   | Required    | Description                                                                                                       |
| ----------- | ------------------ | -------- | -------------------------------------------------------------------------------------------------------------- |
| `models`    | `ModelBlueprint[]` | Yes      | Non-empty ordered list of model entries to create                                                              |
| `overrides` | object             | No       | Fields applied after `templateId` data but before the per-entry `template`; fields in `template` take priority |

### ModelBlueprint

| Field        | Type   | Required    | Description                                                                                                       |
| ------------ | ------ | ----------- | ----------------------------------------------------------------------------------------------------------------- |
| `model`      | string | Yes         | Dot-separated model reference, e.g. `conversational.Assistant` or `conversational.Channel`                        |
| `name`       | string | No          | Unique label within the Blueprint; exposes the created ID to subsequent entries                                   |
| `templateId` | uuidv4 | Conditional | ID of a stored Template record to use as the base; required if `template` is absent                               |
| `template`   | object | Conditional | Inline field values; merged on top of `templateId` data when both are present; required if `templateId` is absent |

:::info{title="Note"}

When both `templateId` and `template` are provided, the stored Template's `data` is loaded first, then `overrides` are applied on top, and finally the per-entry `template` is merged last. Fields in `template` therefore take the highest priority, followed by `overrides`, then the base Template data.

:::

---

## Running a Blueprint

Use `/core/blueprints/run` for an inline definition or `/core/blueprints/:id/run` for a stored Blueprint. Both return an array of created records in the same order as `models`.

Both endpoints accept these optional parameters:

| Parameter | Type | Effect |
| --- | --- | --- |
| `context` | Object | Supplies values for template interpolation. A stored Blueprint's `context` field is a JSON Schema that validates these values, not the values themselves. |
| `projectId` | String | Selects the destination project. The server checks access and supplies its project and organization IDs to models that have those fields, unless their resolved templates already provide them. |
| `dryRun` | Boolean | When `true`, executes the inserts, rolls back the transaction, and returns the rows that would have been created. Omit it to persist the records. |

### POST /core/blueprints/run

Send the definition in `blueprint`. This example requires an existing stored Template with the specified `templateId` that supplies the Assistant's other required fields. Replace all sample IDs with your own.

```http
POST /core/blueprints/run
Content-Type: application/json
Authorization: Bearer <api-key>

{
  "blueprint": {
    "models": [
      {
        "name": "KB",
        "model": "ai.KnowledgeBase",
        "template": {
          "name": "Acme KB"
        }
      },
      {
        "model": "conversational.Assistant",
        "templateId": "f1e2d3c4-b5a6-4978-8b7c-6d5e4f3a2b1c",
        "template": {
          "name": "Acme Assistant",
          "knowledgeBaseIds": ["{{ blueprint.KB }}"]
        }
      }
    ],
    "overrides": {
      "projectId": "{{ projectId }}"
    }
  },
  "context": {
    "clientName": "Acme",
    "projectId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e"
  }
}
```

**Response:**

```json
[
  {
    "id": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
    "name": "Acme KB",
    "projectId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
    "createdAt": "2026-01-15T10:05:00.000Z",
    "updatedAt": "2026-01-15T10:05:00.000Z"
  },
  {
    "id": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
    "name": "Acme Assistant",
    "knowledgeBaseIds": ["d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a"],
    "projectId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
    "createdAt": "2026-01-15T10:05:00.000Z",
    "updatedAt": "2026-01-15T10:05:00.000Z"
  }
]
```

### POST /core/blueprints/:id/run

Pass the stored Blueprint's ID in the URL and its input values in `context`. The server loads the definition from `data`, validates the caller's context against the stored context schema when present, and runs the definition.

The response below assumes the stored Blueprint supplies the shown project ID. Supply a top-level `projectId` in the run request when the templates do not already specify the destination project.

```http
POST /core/blueprints/a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d/run
Content-Type: application/json
Authorization: Bearer <api-key>

{
  "context": {
    "clientName": "Acme"
  }
}
```

**Response:**

```json
[
  {
    "id": "d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a",
    "name": "Acme KB",
    "projectId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
    "createdAt": "2026-01-15T10:05:00.000Z",
    "updatedAt": "2026-01-15T10:05:00.000Z"
  },
  {
    "id": "e5f6a7b8-c9d0-4e1f-2a3b-4c5d6e7f8a9b",
    "name": "Acme Assistant",
    "knowledgeBaseIds": ["d4e5f6a7-b8c9-4d0e-1f2a-3b4c5d6e7f8a"],
    "projectId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e",
    "createdAt": "2026-01-15T10:05:00.000Z",
    "updatedAt": "2026-01-15T10:05:00.000Z"
  }
]
```

---

## Template interpolation

The following `BlueprintObject` requires `clientName`, an existing STS model's `stsId`, and a compatible `voiceId` in the caller's context. Wrap it in a run request's `blueprint` field and supply the destination `projectId` at the top level. Examples that use `templateId` assume the stored Template supplies all other required Assistant fields.

Before inserting each entry, Morpher processes all string values in its resolved template:

* `{{ clientName }}` reads `clientName` from the caller's context.
* `{{ blueprint.KB }}` reads the ID of the earlier entry named `KB`. The key `blueprint` is reserved and takes priority over the caller's context.
* A field containing only one `{{ }}` template preserves the value's type.
* `{% path %}` becomes literal `{{ path }}` text for a later workflow execution pass.

```json
{
  "models": [
    {
      "name": "KB",
      "model": "ai.KnowledgeBase",
      "template": {
        "name": "{{ clientName }} Knowledge Base"
      }
    },
    {
      "model": "conversational.Assistant",
      "template": {
        "name": "{{ clientName }} Assistant",
        "voiceId": "{{ voiceId }}",
        "stsId": "{{ stsId }}",
        "instructions": "You are a helpful assistant for {{ clientName }}.",
        "language": "en-US",
        "timezone": "Europe/Paris",
        "knowledgeBaseIds": ["{{ blueprint.KB }}"]
      }
    }
  ]
}
```

The Assistant's `knowledgeBaseIds` contains the ID of the Knowledge Base created by the first entry.

:::warning{title="Order matters"}

Entries are processed sequentially. A `{{ blueprint.<name> }}` reference is only valid for entries that appear after the named entry in the `models` array. Forward references are missing values. A sole template returns `undefined`; when embedded in text, it becomes empty text. Required field validation may then fail.

:::

---

## Overrides

Use `overrides` for fields shared by every entry. Each entry merges fields in this order, with later values replacing earlier ones:

1. Template record `data` (if `templateId` is provided)
2. `overrides`
3. Per-entry `template`

Per-entry `template` fields have the highest priority. Use them when one entry needs a different value from the shared override. This example requires `voiceId` and `stsId` in the caller's context.

```json
{
  "models": [
    {
      "name": "KB",
      "model": "ai.KnowledgeBase",
      "template": { "name": "Acme KB" }
    },
    {
      "model": "conversational.Assistant",
      "template": {
        "name": "Acme Assistant",
        "voiceId": "{{ voiceId }}",
        "stsId": "{{ stsId }}",
        "instructions": "You are a helpful assistant for Acme.",
        "language": "en-US",
        "timezone": "Europe/Paris",
        "knowledgeBaseIds": ["{{ blueprint.KB }}"]
      }
    }
  ],
  "overrides": {
    "projectId": "b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e"
  }
}
```

Both records receive the shared `projectId`. To read it from caller context instead, set `"projectId": "{{ projectId }}"` in `overrides`.

---

## Validation rules

Definition checks run before inserts. Stored Template lookup and model checks also run during execution; insertion failures roll back the transaction. The following errors can be returned:

| Error code              | HTTP status | Cause                                                            |
| ----------------------------- | ----------- | --------------------------------------------------------------------- |
| `EMPTY_BLUEPRINT`       | 400         | The Blueprint object is missing or has no `models` field         |
| `INVALID_MODELS`        | 400         | `models` is not an array, or is an empty array                   |
| `MISSING_TEMPLATE_DATA` | 400         | An entry has neither `template` nor `templateId`                 |
| `INVALID_UUID`          | 400         | `templateId` is present but is not a valid UUIDv4                |
| `INVALID_TEMPLATE`      | 400         | `template` is an array instead of an object, or is not an object |
| `DUPLICATE_NAME`        | 400         | Two or more entries share the same `name` value                  |
| `INVALID_MODEL`         | 400         | The `model` string does not refer to a blueprintable model       |
| `TEMPLATE_NOT_FOUND`    | 404         | A `templateId` does not match any stored Template record         |
| `NOT_FOUND`                   | 404         | The Blueprint ID passed to `/:id/run` does not exist                  |
| `BAD_INPUT`                   | 400         | The `blueprint` field in a `/run` request body is not an object       |
| `INVALID_TEMPLATE_EXPRESSION` | 400         | A template contains invalid syntax or an unknown helper               |
| `BLUEPRINT_TYPE_MISMATCH`     | 400         | A stored Blueprint's `type` does not match its models                 |
| `INVALID_CONTEXT`             | 400         | Caller context does not match a stored Blueprint's context schema     |
| `PROJECT_NOT_FOUND`           | 404         | The requested destination project is not accessible or does not exist |

---

## Best practices

### Name entries that are referenced by others

* Always set `name` on any entry whose ID will be used by a later entry via `{{ blueprint.<name> }}`.
* Use descriptive names such as `KB`, `ASSISTANT`, or `HOOK` so references are easy to identify. Uppercase is a naming convention, not a requirement.
* Names must be unique within a Blueprint; duplicate names are rejected at validation time.

### Use overrides for shared fields

* Place fields that are identical across all entries, such as `projectId`, `organizationId`, or a shared configuration flag, in `overrides` rather than repeating them in every `template`.
* Overrides support Morpher expressions, so `"projectId": "{{ projectId }}"` lets callers supply the value at runtime via the `context` object without modifying the stored Blueprint.

### Store reusable Blueprints as Blueprint records

* Use the inline `/run` endpoint during development and testing.
* Store reusable definitions as `Blueprint` records and invoke them by ID to avoid embedding the full definition in every request.

### Keep Blueprints small and focused

* A Blueprint should provision one logical unit of configuration, for example a single Assistant with its associated Knowledge Base and Channel. The stored Blueprint's type is `assistant` if it contains a `conversational.Assistant`, otherwise `mapper` if it contains an `automation.Mapper`, otherwise `automation` if it contains an `automation.Hook` or `automation.Process`.
* Avoid creating large, monolithic blueprints that provision unrelated resources. Smaller blueprints are easier to test, debug, and reuse independently.
