AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Engineering Teams Use Dust Apps to Build Custom Data Extraction Pipelines with Python Code Blocks and Schema Enforcement

장은미 · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Probabilistic language models should never be trusted to write directly into an enterprise relational database or production data warehouse. When platform engineers hand document extraction tasks to conversational AI bots or generic chat endpoints, production incidents follow almost immediately: markdown backticks enclosing supposedly raw JSON, dropped object keys when input documents get lengthy, hallucinated enum values, and dates formatted in five different conventions across ten documents.

At 365Finds, our research indicates that treating conversational assistants as ETL workers is an architectural anti-pattern. Enterprise data pipelines require determinism. If an incoming unstructured document—whether a vendor agreement, utility bill, commercial invoice, or compliance questionnaire—fails to meet a strict database schema, the pipeline must catch and quarantine the error before the downstream system ever sees it.

Dust offers a developer-oriented environment known as Dust Apps. Unlike basic Slack bots, workspace knowledge mounts, or conversational multi-agent chats, a Dust App is a sequential execution chain composed of discrete, auditable blocks. By chaining an Input block, a Model block, and a sandboxed Code block, engineering teams can construct an industrial-grade extraction pipeline. The model handles fuzzy semantic interpretation; the sandboxed code enforces structural integrity.

Here is how engineering teams architect, test, and deploy Dust Apps for deterministic document extraction, and how they bridge the native Dust runtime with Python backends.


The Architectural Flaw of Unconstrained Chat Extraction

Why do standard LLM calls break downstream data pipelines? The root problem lies in the gap between probabilistic token generation and the rigid type safety required by modern data engineering stacks.

+-----------------------------------------------------------------------------------+
|                         FRAGILE CHAT BOT ARCHITECTURE                             |
|                                                                                   |
|  Unstructured Doc ---> LLM Chat API ---> "```json { ... }```" ---> DB Crash       |
|                                  \                                                |
|                                   +--> Missing Fields / Hallucinated Enums        |
+-----------------------------------------------------------------------------------+

+-----------------------------------------------------------------------------------+
|                     DUST APPS DETERMINISTIC PIPELINE                              |
|                                                                                   |
|  Raw Corpus ---> [Input Block] ---> [Model Block] ---> [Code Sandbox] ---> Valid  |
|                                      (Few-Shot LLM)     (Schema & Guard)   JSON   |
|                                                                |                  |
|                                                                +---> Quarantined  |
|                                                                      Error Object |
+-----------------------------------------------------------------------------------+

When an engineer prompts a frontier LLM to extract data as JSON, three failure modes frequently occur in production:

  1. Formatting Bleed: Models wrap payloads in markdown code fences (```json ... ```) or append conversational pleasantries ("Here is the extracted invoice data:"), instantly causing standard JSON deserializers to crash.
  2. Schema Drift and Silent Key Dropping: As input documents vary in length and quality, optional fields disappear completely rather than returning explicit null values, breaking strongly typed relational schemas.
  3. Type Confusion: Numeric currency values arrive as strings with currency symbols ("$12,450.00" instead of 12450.00), and timestamps arrive in ambiguous regional formats rather than ISO 8601 strings.

Attempting to fix these failures by simply yelling louder in the prompt ("Return ONLY raw JSON, do not include markdown!") reduces the error rate from 20% to 2%. In enterprise data engineering, a 2% failure rate across 50,000 documents per month translates to 1,000 silent pipeline failures or corrupt database rows.

Dust Apps solve this by establishing an immutable block-based pipeline where the LLM's raw output is intercepted by a sandboxed code execution layer before leaving the boundary of the extraction service.


Anatomy of an Extraction App in Dust

A Dust App executes sequentially. Data flows from one block to the next inside an execution context. For data extraction, three block types form the core engine:

[Input Block: payload] 
       |
       v
[Model Block: few-shot prompt] 
       |
       v
[Code Block: schema enforcement & sanitization]
       |
       v
[Output Payload / API Response]

1. The Input Block (input)

The Input block serves as the ingress gateway for the pipeline. During app development and testing within the Dust console, the Input block connects to an uploaded dataset containing representative sample files (e.g., edge-case contracts, scanned OCR transcripts, noisy PDF text dumps).

When deployed to production, the dataset is superseded: runtime arguments supplied via the Dust API map directly into this block.

A clean Input block definition establishes the expected incoming payload structure:

{
  "document_id": "doc_corp_99482",
  "document_type": "vendor_contract",
  "raw_text": "MASTER SERVICES AGREEMENT\nBetween Acme Cloud Inc. and Beta Logistics...\nEffective Date: October 14, 2024\nAnnual Commitment: $144,000 USD\nPayment Terms: Net 45\nGoverning Law: State of Delaware...",
  "correlation_id": "corr_etl_881923"
}

The Input block forks execution cleanly: if a batch of documents is submitted, Dust forks parallel execution streams across the app, tracking state separately per record.

2. The Model Block (model)

The Model block handles the linguistic heavy lifting: reading messy, human-drafted legal or operational language and isolating target fields.

To achieve maximum extraction consistency, engineering teams should follow three configuration rules in Dust:

An effective prompt template inside the Model block looks like this:

You are a deterministic data extraction engine.
Extract commercial terms from the document provided below into a strict JSON object.

Target Schema:
- vendor_name: string
- client_name: string
- effective_date: ISO 8601 date string (YYYY-MM-DD) or null
- total_contract_value: number (float, no currency symbols) or null
- currency: ISO 4217 3-letter currency code (e.g. "USD", "EUR") or null
- payment_terms_days: integer (e.g. 30, 45, 60) or null
- governing_law: string or null
- auto_renewal: boolean

Output must be raw JSON only. No explanations, no markdown tags.

Document:
{{INPUT.raw_text}}

Despite these strict instructions, the model will still occasionally output leading spaces, markdown fences, or unparsed numeric formatting. That is where the Code block steps in.

3. The Sandboxed Code Block (code)

In the Dust App engine, Code blocks execute in an isolated runtime environment. By default, Dust's native block engine runs JavaScript, executing an entry point function named _fun that receives an env environment variable.

The env object provides structured access to upstream pipeline data:

The Code block functions as a deterministic schema validator and data sanitizer. It strips markdown artifacts, attempts strict JSON parsing, validates against expected types, normalizes messy fields (such as converting string currencies to floats and arbitrary date representations to ISO 8601), and produces a standardized envelope containing either validated data or explicit validation failure diagnostics.

// Native Dust Apps Code Block (_fun)
function _fun(env) {
  const rawModelOutput = env.state.MODEL_EXTRACT?.text || "";
  const inputMeta = env.input || {};

  // 1. Sanitize raw text: strip markdown code blocks and whitespace
  let cleaned = rawModelOutput.trim();
  if (cleaned.startsWith("```json")) {
    cleaned = cleaned.substring(7);
  } else if (cleaned.startsWith("```")) {
    cleaned = cleaned.substring(3);
  }
  if (cleaned.endsWith("```")) {
    cleaned = cleaned.substring(0, cleaned.length - 3);
  }
  cleaned = cleaned.trim();

  let parsed = null;
  const errors = [];

  // 2. Strict JSON Parse
  try {
    parsed = JSON.parse(cleaned);
  } catch (err) {
    return {
      status: "parse_error",
      error_message: `Invalid JSON syntax: ${err.message}`,
      raw_output: rawModelOutput,
      document_id: inputMeta.document_id || null,
      extracted_at: new Date().toISOString()
    };
  }

  // 3. Schema Enforcement & Field Normalization
  const validated = {};

  // vendor_name (Required String)
  if (typeof parsed.vendor_name === "string" && parsed.vendor_name.trim().length > 0) {
    validated.vendor_name = parsed.vendor_name.trim();
  } else {
    errors.push("Missing or invalid field: vendor_name");
  }

  // client_name (Required String)
  if (typeof parsed.client_name === "string" && parsed.client_name.trim().length > 0) {
    validated.client_name = parsed.client_name.trim();
  } else {
    errors.push("Missing or invalid field: client_name");
  }

  // total_contract_value (Float Normalization)
  if (parsed.total_contract_value !== null && parsed.total_contract_value !== undefined) {
    let num = Number(parsed.total_contract_value);
    if (isNaN(num) && typeof parsed.total_contract_value === "string") {
      // Clean out currency symbols and commas if model leaked them
      num = Number(parsed.total_contract_value.replace(/[^0-9.-]+/g, ""));
    }
    validated.total_contract_value = !isNaN(num) ? num : null;
    if (isNaN(num)) errors.push("Unparseable number for total_contract_value");
  } else {
    validated.total_contract_value = null;
  }

  // currency (ISO 4217 3-letter string)
  if (typeof parsed.currency === "string" && parsed.currency.trim().length === 3) {
    validated.currency = parsed.currency.trim().toUpperCase();
  } else {
    validated.currency = null;
  }

  // payment_terms_days (Integer)
  if (parsed.payment_terms_days !== null && parsed.payment_terms_days !== undefined) {
    const days = parseInt(parsed.payment_terms_days, 10);
    validated.payment_terms_days = !isNaN(days) ? days : null;
  } else {
    validated.payment_terms_days = null;
  }

  // auto_renewal (Boolean)
  validated.auto_renewal = Boolean(parsed.auto_renewal);

  // Return final response envelope
  if (errors.length > 0) {
    return {
      status: "schema_validation_failed",
      validation_errors: errors,
      partial_data: validated,
      raw_output: rawModelOutput,
      document_id: inputMeta.document_id || null,
      extracted_at: new Date().toISOString()
    };
  }

  return {
    status: "success",
    data: validated,
    document_id: inputMeta.document_id || null,
    correlation_id: inputMeta.correlation_id || null,
    extracted_at: new Date().toISOString()
  };
}

This architecture guarantees that the block chain never emits unhandled JSON syntax crashes to downstream consumers. Downstream systems receive either a confirmed status: "success" with typed fields or an explicit status: "schema_validation_failed" containing the exact error array for dead-letter queuing.


Integrating Dust Apps with Python Backends and Pydantic

While Dust Apps natively run JavaScript blocks inside their execution canvas, 90% of enterprise ETL pipelines, document parsers, and data engineering stacks are written in Python.

The production integration pattern consists of using Python to:

  1. Ingest, OCR, and chunk raw documents.
  2. Call the Dust App run endpoint over HTTP.
  3. Validate the returned payload against a strict Pydantic V2 model before writing to the database.
+-------------------------------------------------------------------------------+
|                             PYTHON ETL RUNNER                                 |
|                                                                               |
|  1. Ingest PDF / OCR                                                          |
|  2. POST payload to Dust App Run API                                          |
|                                                                               |
|     Dust Endpoint: /api/v1/w/{wId}/apps/{appId}/runs                          |
|                                                                               |
|  3. Receive Envelope:                                                         |
|     if envelope["status"] == "success":                                       |
|         model = ContractSchema.model_validate(envelope["data"])               |
|         save_to_warehouse(model)                                              |
|     else:                                                                     |
|         route_to_quarantine_dlq(envelope)                                     |
+-------------------------------------------------------------------------------+

Production Python Orchestrator

Below is a robust, production-ready Python client using pydantic and httpx to trigger a Dust App and enforce strict schema boundaries:

import os
import sys
from typing import Optional
from pydantic import BaseModel, Field, ValidationError
import httpx

# 1. Define Strict Pydantic Schema
class ExtractedContract(BaseModel):
    vendor_name: str = Field(..., min_length=1)
    client_name: str = Field(..., min_length=1)
    total_contract_value: Optional[float] = None
    currency: Optional[str] = Field(None, min_length=3, max_length=3)
    payment_terms_days: Optional[int] = Field(None, ge=0, le=365)
    auto_renewal: bool = False

class DustPipelineResponse(BaseModel):
    status: str
    data: Optional[ExtractedContract] = None
    validation_errors: Optional[list[str]] = None
    document_id: Optional[str] = None
    correlation_id: Optional[str] = None
    extracted_at: str

# 2. Pipeline Execution Service
class DustExtractionService:
    def __init__(self, workspace_id: str, app_id: str, api_key: str, region: str = "us"):
        self.workspace_id = workspace_id
        self.app_id = app_id
        self.api_key = api_key
        # Dust operates in US and EU cloud regions
        base_domain = "eu.dust.tt" if region.lower() == "eu" else "dust.tt"
        self.endpoint = f"https://{base_domain}/api/v1/w/{self.workspace_id}/apps/{self.app_id}/runs"
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

    def execute_extraction(self, document_id: str, raw_text: str, correlation_id: str) -> DustPipelineResponse:
        payload = {
            "specification_hash": None, # Defaults to the latest deployed version
            "config": {},
            "inputs": [
                {
                    "document_id": document_id,
                    "raw_text": raw_text,
                    "correlation_id": correlation_id
                }
            ]
        }

        with httpx.Client(timeout=60.0) as client:
            response = client.post(self.endpoint, json=payload, headers=self.headers)
            response.raise_for_status()
            result_json = response.json()

        # Extract output from the final block in the Dust App execution trace
        try:
            # Dust returns an array of runs matching the inputs array
            run_traces = result_json.get("run", {}).get("traces", [])
            # Find output of the code block named 'ENFORCE_SCHEMA'
            code_block_traces = [t for t in run_traces if t[0][0] == "ENFORCE_SCHEMA"]
            if not code_block_traces:
                # Fallback to direct results payload if app structure exposes top-level results
                app_output = result_json.get("run", {}).get("results", [[{}]])[0][0].get("value")
            else:
                app_output = code_block_traces[0][1][0][0]["value"]

            # Parse through Pydantic
            return DustPipelineResponse.model_validate(app_output)

        except (KeyError, IndexError, ValidationError) as e:
            return DustPipelineResponse(
                status="orchestrator_parsing_error",
                validation_errors=[f"Failed to parse Dust execution trace: {str(e)}"],
                document_id=document_id,
                correlation_id=correlation_id,
                extracted_at=""
            )

# Example Execution
if __name__ == "__main__":
    service = DustExtractionService(
        workspace_id=os.getenv("DUST_WORKSPACE_ID", "w_test123"),
        app_id=os.getenv("DUST_APP_ID", "app_contract_extract"),
        api_key=os.getenv("DUST_API_KEY", "sk-test-key")
    )

    sample_contract = (
        "AGREEMENT between Apex Systems and Horizon Retail. "
        "Apex will provide infrastructure monitoring for $48,000 annually. "
        "Payment terms are Net 30. No automatic renewal clause."
    )

    pipeline_result = service.execute_extraction(
        document_id="doc_8091",
        raw_text=sample_contract,
        correlation_id="job_772"
    )

    if pipeline_result.status == "success" and pipeline_result.data:
        print(f"Extracted Validated Vendor: {pipeline_result.data.vendor_name}")
        print(f"Contract Value: ${pipeline_result.data.total_contract_value} {pipeline_result.data.currency}")
        print(f"Payment Terms: {pipeline_result.data.payment_terms_days} days")
    else:
        print(f"Pipeline Quarantined Document: {pipeline_result.validation_errors}", file=sys.stderr)

The 365Finds Technical Evaluation

At 365Finds, we evaluate AI platform architectures based on engineering maintainability, failure isolation, and operational overhead. Here is our assessment of Dust Apps for data extraction:

Strengths

Trade-offs and Limitations


Implementation Checklist

To deploy a high-reliability extraction pipeline using Dust Apps, follow this four-phase sequence:

  1. Curate the Validation Dataset: Before writing code, gather 20 representative documents in a Dust Dataset, including at least 5 noisy edge cases (missing dates, foreign currencies, handwritten scans).
  2. Lock Down the Model Block: Use temperature: 0, specify JSON key names explicitly, and include 2 few-shot input/output examples inside the prompt template.
  3. Write Defensive Sandbox Code: Treat LLM output as untrusted user input. Always strip markdown tags, wrap JSON.parse() in try/catch blocks, enforce type conversions, and return a standardized status payload.
  4. Enforce Double-Check Validation in Python: Do not assume the remote endpoint is infallible. Validate the returned Dust payload with a local Pydantic model before committing records to your operational database.

References