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

# Generate workflow imports with AI

> An agent-oriented reference and complete JSON example for generating Weles workflows, document types, classification, OCR, verification, and export.

This guide is for AI agents and developers generating a Weles workflow import. It describes the `1.0` export shape implemented by the current application, how references are resolved, a complete example, and the checks required before processing real documents. For the agent-oriented overview and separate Tool Manager package format, see [Start here: building Weles with AI](https://docs.welesai.com/ai-agents/start-here.md) and [Create Tool Manager packages](https://docs.welesai.com/ai-agents/tool-packages.md). Follow it along with the [stage reference](https://docs.welesai.com/workflows/stages.md), [document types](https://docs.welesai.com/workflows/document-types.md), and [agent tools](https://docs.welesai.com/workflows/agent-tools.md).

> [!WARNING]
>
> The importer does **not** remap document type IDs inside classifier classes. A portable import with new document types therefore requires a post-import classifier mapping step. Do not claim that a generated file is ready to process multiple document types until its class IDs, models, and destinations have been verified in the target environment.

## Instructions for a generating agent

1. Determine the desired workflow mode, document categories and fields, model names available to the target deployment, verification requirements, and output destination. Do not invent credentials, provider capabilities, endpoints, or business rules. Ask for missing deployment-specific values or clearly mark them for replacement.
2. Produce one UTF-8 JSON object, not Markdown, comments, trailing commas, or a Weles API response. Include `export_version`, `workflow`, and `document_types` in the shape below. Use distinct stage positions and UUID-shaped source keys for document types.
3. For each category, define a document type with a unique name, integer version, model, extraction prompt, and schema. Put types in `document_types` even when referenced only by classifier classes. Consider name/version collisions in the destination.
4. Construct the ordered pipeline, using `classification` before `ocr`, and `use_classification: true` when OCR should use the class's type. Provide a `verification` stage if human review is required. Add `export` only with an approved destination.
5. For target-existing document types, insert their **actual target IDs** into `classes[].document_type_id` and verify their schemas and versions. For newly imported types, leave class IDs empty and instruct the administrator to select the imported types after import. A generated temporary/source ID in a class is not automatically replaced.
6. Validate the JSON and all references, then import as an administrator. Configure prerequisites, assign users, and test every class using approved representative samples before release. Report the exact outstanding steps; importing successfully is not proof of correct execution.

## Import envelope

```json theme={null}
{
  "export_version": "1.0",
  "exported_at": "2026-01-01T00:00:00Z",
  "workflow": {
    "name": "Workflow name",
    "description": "Business purpose",
    "mode": "ocr_pipeline",
    "stages": []
  },
  "document_types": {}
}
```

`export_version` and `workflow` must be present. The importer currently checks for their presence rather than validating a version number or a complete schema; generate `"1.0"`, the value exported by this build. `exported_at` is optional metadata and is not used to create the workflow. Use `ocr_pipeline` for a document pipeline or `agent_only` for an API/chat agent. An import always creates a new workflow and new stage IDs; it does not update an existing workflow. It does not import users, permissions, credentials, transitions, or provider/service configuration.

Each stage has `name`, integer `order_index`, booleans `is_start`, `is_end`, `is_verification`, a `stage_type`, and a `configuration` object or `null`. Use unique increasing positions. Set `is_start` on the single start stage and `is_verification` on a verification stage, consistent with the builder. Keep flags consistent with stage type: behavior is not configured by flags alone. Processing advances by stage order, not a JSON-defined conditional transition graph. Do not promise branching based on classification or confidence: classification chooses a document type for later OCR, not a separate path.

## Document type records and ID resolution

`document_types` is an object keyed by **source ID**. Each value carries `id`, `name`, `version`, `description`, `model_name`, `system_prompt`, and `schema_definition`. The importer uses the map key as the source ID; use the same value in the record's `id` for export compatibility. Version is an integer.

For each entry, the importer first reuses a target record with the exact source ID, otherwise reuses a record with the same name and version, otherwise creates a record with a new ID. Reuse does **not** compare or overwrite schemas, prompts, or models: review matches before relying on them. A newly created type is active only if no type with the same name already exists. Import differs from saving a new type version in the UI; it does not automatically activate a new version of an existing name.

The importer remaps only `configuration.document_type_id` at the stage's top level. It does not remap `configuration.classes[].document_type_id`, tool IDs, or arbitrary nested references. If the ID is unknown to the mapping, it remains unchanged. Export also collects only types referenced by the top-level stage field: types referenced solely inside classifier classes may be absent from an exported file. Inspect and repair exports before transferring them between environments.

> [!WARNING]
>
> Do not put a temporary source ID into a classifier class and assume it will become the new target ID. For new types, use empty strings, import, then select and save the correct target type/version for each class. If using existing target IDs, verify each record really exists in that destination. Avoid a top-level OCR fallback merely to force export inclusion: it can preassign a type during upload and lead to mismatched document-type metadata.

## Extraction schema

The document type editor produces an object with `type`, `properties`, and `required`. Scalar editor types are `string`, `number`, `boolean`, and `date`. Weles uses the literal `"type": "date"` in its editor; this is a Weles convention, not a standard JSON Schema primitive. A repeatable scalar uses `"type": "array"`, `"x-repeatable": "field"`, and `items`. A repeating group uses `"x-repeatable": "group"` with object `items.properties`. Named top-level fields/groups appear in `required`; group children are not automatically required. Unique nonempty names are essential.

## Complete two-type example

This example creates a five-stage OCR pipeline and two type definitions. It is valid import JSON, but the model name is illustrative: replace `llama3` with an approved model available through the target OCR provider and capable of handling your sample files. The empty class IDs intentionally require the post-import mapping below. The folder export also requires an accessible shared volume and appropriate authorization. No credentials are included.

```json theme={null}
{
  "export_version": "1.0",
  "exported_at": "2026-01-01T00:00:00Z",
  "workflow": {
    "name": "Invoice and purchase order processing",
    "description": "Classify, extract, review, and export purchasing documents.",
    "mode": "ocr_pipeline",
    "stages": [
      {
        "name": "Input",
        "order_index": 1,
        "is_start": true,
        "is_end": false,
        "is_verification": false,
        "stage_type": "start",
        "configuration": {"input_source": "api"}
      },
      {
        "name": "Classify document",
        "order_index": 2,
        "is_start": false,
        "is_end": false,
        "is_verification": false,
        "stage_type": "classification",
        "configuration": {
          "model_name": "llama3",
          "classes": [
            {"name": "Invoice", "document_type_id": "", "keywords": ["invoice", "amount due"]},
            {"name": "Purchase order", "document_type_id": "", "keywords": ["purchase order", "order number"]}
          ]
        }
      },
      {
        "name": "Extract fields",
        "order_index": 3,
        "is_start": false,
        "is_end": false,
        "is_verification": false,
        "stage_type": "ocr",
        "configuration": {"use_classification": true, "extract_full_text": false}
      },
      {
        "name": "Human review",
        "order_index": 4,
        "is_start": false,
        "is_end": false,
        "is_verification": true,
        "stage_type": "verification",
        "configuration": {}
      },
      {
        "name": "Export reviewed results",
        "order_index": 5,
        "is_start": false,
        "is_end": true,
        "is_verification": false,
        "stage_type": "export",
        "configuration": {"export_type": "folder", "include_workflow_context": false}
      }
    ]
  },
  "document_types": {
    "11111111-1111-4111-8111-111111111111": {
      "id": "11111111-1111-4111-8111-111111111111",
      "name": "Purchasing Invoice Example",
      "version": 1,
      "description": "Invoice fields and repeating line items.",
      "model_name": "llama3",
      "system_prompt": "Extract the invoice fields and line items. Do not invent missing values.",
      "schema_definition": {
        "type": "object",
        "properties": {
          "invoice_number": {"type": "string"},
          "issue_date": {"type": "date"},
          "total": {"type": "number"},
          "items": {
            "type": "array",
            "x-repeatable": "group",
            "items": {"type": "object", "properties": {"description": {"type": "string"}, "quantity": {"type": "number"}, "price": {"type": "number"}}}
          }
        },
        "required": ["invoice_number", "issue_date", "total", "items"]
      }
    },
    "22222222-2222-4222-8222-222222222222": {
      "id": "22222222-2222-4222-8222-222222222222",
      "name": "Purchasing Order Example",
      "version": 1,
      "description": "Purchase order fields.",
      "model_name": "llama3",
      "system_prompt": "Extract the purchase order fields. Do not invent missing values.",
      "schema_definition": {
        "type": "object",
        "properties": {
          "order_number": {"type": "string"},
          "supplier": {"type": "string"},
          "total": {"type": "number"},
          "references": {"type": "array", "x-repeatable": "field", "items": {"type": "string"}}
        },
        "required": ["order_number", "supplier", "total", "references"]
      }
    }
  }
}
```

### Make the example operational

1. Replace model names with verified target values; confirm the OCR provider supports the file formats and model. Confirm the shared export volume and file permissions.
2. Save the code block as a `.json` file and use **Workflows → Import** as an administrator. The backend endpoint is `POST /workflows/import` with the file in multipart form field `file` and administrator authentication; the UI handles the upload.
3. Inspect **Document Types** for both imported records and their versions. If an ID or name/version matched an existing record, confirm its schema, prompt and model; resolve conflicts before proceeding.
4. Open the imported workflow's **Classify document** stage. Set the Invoice class to **Purchasing Invoice Example**, and Purchase order to **Purchasing Order Example**, selecting the intended versions. Save the stage. Confirm OCR uses the classification result and does not have an unintended fallback type.
5. Assign users to the workflow. Upload one approved sample of each category, review the class, document type, extracted fields, verification form, approval and exported JSON. Also test an ambiguous/unrecognized document: the classifier can return `unknown` with no type; the example does not implement a confidence threshold or an exception route. Decide and document an operational handling procedure before production.

### Fully pre-resolved target variant

If both document types already exist in the target, obtain their IDs and verify their names, versions and definitions. Replace the two source map keys **and** corresponding record `id` values with those exact target IDs; set each classifier class `document_type_id` to its respective target ID. The importer reuses the records by ID, and the unchanged nested class references already point to valid target records. Verify the configuration after import and complete all model, access, export, and sample tests above. This variant is target-specific, not portable to another environment.

## Other stage configurations

Use the exact `stage_type` and keys below; omit stages not required by the task. JSON snippets are `configuration` values, not standalone imports.

| Stage type | Configuration and guidance |
| - | - |
| `start` | `input_source`: `api` or `queue`; for a queue use `queue_name`. Folder import is separately configured per workflow. |
| `agent_input` | Start stage for `agent_only`; exposes `input_question`, `input_file_content`, and `input_filename` when supplied. |
| `classification` | `model_name`, `classes`: array of `{name, document_type_id, keywords}`; keyword values are an array of strings. See ID warning above. |
| `ocr` | `document_type_id` for a fixed type, or `use_classification: true`; `extract_full_text` controls full-text extraction. Top-level IDs are remapped only if included in `document_types`. |
| `agent` | `agent_config` with `model_name`, `system_prompt`, `temperature`, `max_tokens`, optionally `num_ctx`; arrays `tools`, `input_vars`, `output_vars`; `batch_execution`: `per_document` or `once`. An empty input selection passes the whole context. |
| `verification` | Human review; use an empty configuration. |
| `export` | `export_type` is `webhook`, `queue`, or `folder`; configure `webhook_url`, `queue_name`, or `include_workflow_context` respectively. |
| `vector_db_upload` | `url`, optional `api_key`, `collection_name`, `embedding_model`, `chunk_size`, `chunk_overlap`, and `selected_ocr_fields` (`"*"` or field names). Require `0 <= chunk_overlap < chunk_size`; configure compatible Qdrant and embeddings. |
| `generic` | No dedicated stage-specific settings; do not assume it performs extraction or agent execution. |

For an agent stage, each entry in `tools` has `tool_type`, `name`, and `config`, with optional `description`. Use only tool types and settings supported by the target build; see the [tool catalogue](https://docs.welesai.com/workflows/agent-tools.md). Imported tool configuration may contain secrets or point to external services. Treat export files as sensitive and verify all permissions, actions, network destinations, and credentials before use. Installed tools must already be installed and enabled in the target deployment.

For batch processing, `batch_sync_point: true` on a non-input stage waits for all documents in the batch to finish that stage before any advance. It does not provide classification branching. Test batching separately.

## Validation checklist for agents

* Parse JSON strictly; ensure required envelope keys, proper types, unique nonempty stage and schema names, unique increasing `order_index` values, and matching start/verification flags.
* Check that each fixed OCR ID is a map key or a verified target ID. For classifier IDs, distinguish verified target IDs from unresolved new types; never treat source IDs as automatically remapped.
* Check target type collisions, active state, configured provider/model capabilities, stage order, class names and representative keywords. Make no unsupported claims about unknown classes or conditional routing.
* Validate tool, vector and export settings, avoid embedding secrets, verify network and filesystem permissions, and ensure the operator has the required access.
* Test import and end-to-end processing for every class, including errors and human verification. Compare extracted output and metadata with the original and inspect the final destination. Report any required post-import actions explicitly.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.