Skip to content

Contract with rules

Key terms of a services agreement and two business rules. A rule can be blocking (it stops a document from flowing on) or only a warning: here the notice period is shorter than the 30 days policy, so the answer carries a failed warning next to the data.

The documents are synthetic (invented names, amounts and accounts), generated by scripts/docs_examples.py:

The graph

parse → extract
extract → validate

The full version body (graph and schemas), as the API takes it:

{
  "graph": {
    "nodes": [
      {
        "id": "parse",
        "type": "parse"
      },
      {
        "id": "extract",
        "type": "extract",
        "config": {
          "schema_id": "contract"
        }
      },
      {
        "id": "validate",
        "type": "validate",
        "config": {
          "rules": [
            {
              "id": "fee_is_positive",
              "kind": "deterministic",
              "severity": "error",
              "blocking": true,
              "check": {
                "type": "comparison",
                "left": "monthly_fee",
                "op": ">",
                "right": {
                  "literal": 0
                }
              }
            },
            {
              "id": "notice_at_least_30_days",
              "kind": "deterministic",
              "severity": "warning",
              "blocking": false,
              "check": {
                "type": "comparison",
                "left": "notice_days",
                "op": ">=",
                "right": {
                  "literal": 30
                }
              }
            }
          ]
        }
      }
    ],
    "edges": [
      {
        "source": "parse",
        "target": "extract"
      },
      {
        "source": "extract",
        "target": "validate"
      }
    ]
  },
  "schemas": {
    "contract": {
      "type": "object",
      "x-dx": {
        "document_type": "contract"
      },
      "properties": {
        "title": {
          "type": "string"
        },
        "provider": {
          "type": "string"
        },
        "client": {
          "type": "string"
        },
        "effective_date": {
          "type": "string",
          "format": "date"
        },
        "monthly_fee": {
          "type": "number"
        },
        "notice_days": {
          "type": "integer"
        },
        "governing_law": {
          "type": "string"
        }
      }
    }
  }
}

Create it and run it

Set DX_BASE_URL and DX_API_KEY (see the quickstart), cd to docs/examples/gallery/contract/ and run any of the three. They do the same.

Python

# SPDX-License-Identifier: Apache-2.0
# expect: "status": "succeeded"
"""Contract with rules: create the workflow, run it on the document and print what comes back."""

import json
import os
import secrets
from pathlib import Path

import httpx

api = httpx.Client(
    base_url=os.environ["DX_BASE_URL"],
    headers={"Authorization": f"Bearer {os.environ['DX_API_KEY']}"},
    timeout=120,
)
name = f"contract-{secrets.token_hex(3)}"  # unique, so the example can run again

# 1. Create the workflow, add the version (graph + schemas), publish it, point `prod` at it.
workflow = api.post("/v1/workflows", json={"name": name}).raise_for_status().json()
version = (
    api.post(
        f"/v1/workflows/{workflow['id']}/versions",
        json=json.loads(Path("workflow.json").read_text()),
    )
    .raise_for_status()
    .json()
)
api.post(f"/v1/workflow-versions/{version['id']}:publish", json={}).raise_for_status()
api.put(
    f"/v1/workflows/{workflow['id']}/aliases/prod", json={"version_id": version["id"]}
).raise_for_status()

# 2. Run it on the document and wait for the result.
run = (
    api.post(
        "/v1/runs",
        data={"workflow": f"{name}@prod"},
        files=[("files", ("contract.pdf", Path("contract.pdf").read_bytes(), "application/pdf"))],
    )
    .raise_for_status()
    .json()
)
run = api.get(f"/v1/runs/{run['id']}", params={"wait": 60}).raise_for_status().json()
result = api.get(f"/v1/runs/{run['id']}/result").raise_for_status().json()

node = result["outputs"]["extractions"]["extract"]
view = {
    "status": run["status"],
    "data": node["data"],
    "citations": [
        {"path": f["path"], "page": f["evidence"][0]["page"], "quote": f["evidence"][0]["quote"]}
        for f in node["fields"]
        if f["evidence"] and "[" not in f["path"]
    ],
    "checks": [
        {"rule": v["rule_id"], "status": v["status"]}
        for v in result["outputs"]["validations"]["validate"]
    ],
}
print(json.dumps(view, indent=2))

TypeScript

// SPDX-License-Identifier: Apache-2.0
// expect: "status": "succeeded"
// Contract with rules: create the workflow, run it on the document and print what comes back.
// Node 22+: node --experimental-strip-types create.ts
import { readFileSync } from "node:fs";

const base = process.env.DX_BASE_URL as string;
const auth = { Authorization: `Bearer ${process.env.DX_API_KEY}` };
const name = `contract-${Math.random().toString(16).slice(2, 8)}`; // unique, so it can run again

async function call(path: string, init: RequestInit = {}): Promise<any> {
  const response = await fetch(base + path, { ...init, headers: { ...auth, ...init.headers } });
  if (!response.ok) throw new Error(`${response.status} ${path}: ${await response.text()}`);
  return response.json();
}
const json = (body: unknown): RequestInit => ({
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(body),
});

// 1. Create the workflow, add the version (graph + schemas), publish it, point `prod` at it.
const workflow = await call("/v1/workflows", json({ name }));
const version = await call(
  `/v1/workflows/${workflow.id}/versions`,
  json(JSON.parse(readFileSync("workflow.json", "utf8"))),
);
await call(`/v1/workflow-versions/${version.id}:publish`, json({}));
await call(`/v1/workflows/${workflow.id}/aliases/prod`, {
  ...json({ version_id: version.id }),
  method: "PUT",
});

// 2. Run it on the document and wait for the result.
const form = new FormData();
form.append("workflow", `${name}@prod`);
form.append("files", new Blob([readFileSync("contract.pdf")], { type: "application/pdf" }), "contract.pdf");
const started = await call("/v1/runs", { method: "POST", body: form });
const run = await call(`/v1/runs/${started.id}?wait=60`);
const result = await call(`/v1/runs/${run.id}/result`);

const node = result.outputs.extractions["extract"];
const view = {
  status: run.status,
  data: node.data,
  citations: node.fields
    .filter((f: any) => f.evidence.length > 0 && !f.path.includes("["))
    .map((f: any) => ({ path: f.path, page: f.evidence[0].page, quote: f.evidence[0].quote })),
  checks: result.outputs.validations["validate"].map((v: any) => ({
    rule: v.rule_id,
    status: v.status,
  })),
};
console.log(JSON.stringify(view, null, 2));

curl

#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# expect: "status": "succeeded"
# Contract with rules: create the workflow, run it on the document and print what comes back.
# Needs curl and jq; DX_BASE_URL and DX_API_KEY in the environment.
set -euo pipefail
api() { curl -sS --fail-with-body -H "Authorization: Bearer $DX_API_KEY" "$@"; }
JSON='Content-Type: application/json'
NAME="contract-$RANDOM$RANDOM"  # unique, so the example can run again

# 1. Create the workflow, add the version (graph + schemas), publish it, point `prod` at it.
WORKFLOW=$(api -X POST "$DX_BASE_URL/v1/workflows" -H "$JSON" -d "{\"name\": \"$NAME\"}" | jq -r .id)
VERSION=$(api -X POST "$DX_BASE_URL/v1/workflows/$WORKFLOW/versions" -H "$JSON" -d @workflow.json | jq -r .id)
api -X POST "$DX_BASE_URL/v1/workflow-versions/$VERSION:publish" -H "$JSON" -d '{}' > /dev/null
api -X PUT "$DX_BASE_URL/v1/workflows/$WORKFLOW/aliases/prod" -H "$JSON" \
  -d "{\"version_id\": \"$VERSION\"}" > /dev/null

# 2. Run it on the document and wait for the result.
RUN=$(api -X POST "$DX_BASE_URL/v1/runs" -F "workflow=$NAME@prod" -F "[email protected]" | jq -r .id)
STATUS=$(api "$DX_BASE_URL/v1/runs/$RUN?wait=60" | jq -r .status)
api "$DX_BASE_URL/v1/runs/$RUN/result" | jq --arg status "$STATUS" '{status: $status, data: .outputs.extractions["extract"].data, citations: [.outputs.extractions["extract"].fields[] | select((.evidence | length) > 0 and (.path | contains("[") | not)) | {path, page: .evidence[0].page, quote: .evidence[0].quote}], checks: [.outputs.validations["validate"][] | {rule: .rule_id, status}]}'

Response

Produced by running the script above against a server with the fake model and these documents; make docs runs all the examples again and fails if an answer changes.

{
  "status": "succeeded",
  "data": {
    "client": "Globex Corporation",
    "effective_date": "2026-04-01",
    "governing_law": "Spain",
    "monthly_fee": 2500,
    "notice_days": 15,
    "provider": "Harbor Analytics SL",
    "title": "SERVICES AGREEMENT"
  },
  "citations": [
    {
      "path": "client",
      "page": 1,
      "quote": "Globex Corporation"
    },
    {
      "path": "effective_date",
      "page": 1,
      "quote": "2026-04-01"
    },
    {
      "path": "governing_law",
      "page": 1,
      "quote": "Spain"
    },
    {
      "path": "monthly_fee",
      "page": 1,
      "quote": "2500.00"
    },
    {
      "path": "notice_days",
      "page": 1,
      "quote": "15"
    },
    {
      "path": "provider",
      "page": 1,
      "quote": "Harbor Analytics SL"
    },
    {
      "path": "title",
      "page": 1,
      "quote": "SERVICES AGREEMENT"
    }
  ],
  "checks": [
    {
      "rule": "fee_is_positive",
      "status": "pass"
    },
    {
      "rule": "notice_at_least_30_days",
      "status": "fail"
    }
  ]
}