AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Software Engineers Build Custom LLM Workflows in Dust Apps Using Chained Model Blocks, Code Blocks, and Data Source Extractors

Annika Bernklau · 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

Standard conversational AI assistants excel at open-ended dialogue, but they fail when software engineering teams require strict determinism. When building multi-source document extractors, automated code validators, or microservice data pipelines, a chat prompt cannot guarantee schema adherence, reproducible multi-step execution, or verifiable data routing. At 365Finds, we look at developer architectures with a strict lens: if an LLM pipeline cannot run regressions against test datasets, survive schema mutations, and provide predictable latency via an API, it belongs in a playground, not in production.

Dust Apps—the native developer orchestration layer of Dust—were built to bridge this divide. Instead of trusting an opaque autonomous agent loop to decide which tool to invoke next, Dust Apps allow platform engineers and backend architects to assemble Directed Acyclic Graphs (DAGs) and sequential execution pipelines. By chaining input, data_source, model, code, and map/reduce blocks, teams transform probabilistic language models into reliable, sandboxed microservices.

Below is our complete technical guide on the data topology, execution semantics, and deployment workflows for custom Dust Apps.


1. The Core Problem: Why Chat Assistants Fail Engineering Pipelines

Most enterprise LLM deployments start as conversational assistants in Slack or web widgets. However, integrating LLMs into automated business logic reveals three structural failures:

  1. Non-deterministic state transitions: A conversational prompt handles errors unpredictably. If an extraction misses a key field, a chat agent hallucinates or apologizes rather than raising a catchable runtime exception.
  2. Unchecked payload mutations: Downstream microservices require strict JSON structures (RFC 8259). Asking an LLM to "only output valid JSON" frequently leaks Markdown formatting (json ... ), truncated brackets, or unexpected null fields.
  3. Lack of regression suites: You cannot deploy code without unit and integration tests. Conversational bots do not offer native dataset benchmarking across code changes.

Dust Apps resolve this by treating the LLM call as just one computational block within a deterministic dataflow pipeline. Each block produces an immutable state object, verified and transformed by sandboxed code before reaching the next node.


2. Underlying Architecture and Data Topology

At runtime, a Dust App processes a workflow as an ordered sequence of blocks. Every block receives an execution context object termed env and outputs structured data that downstream blocks access through a centralized state graph.

The Execution State Topology (env)

Inside any programmable block (such as a Code block or a Model block's dynamic message function), Dust exposes the env object:

{
  state: {
    INPUT_BLOCK: { ... },
    RETRIEVAL_BLOCK: [ ... ],
    MAP_EXTRACT: [ ... ]
  },
  input: {
    input: { query: "SOC2 Compliance", org_id: "corp_102" },
    index: 0
  },
  map: {
    name: "MAP_CHUNKS",
    iteration: 2
  },
  config: {
    MODEL_EXTRACT: {
      provider_id: "openai",
      model_id: "gpt-4o"
    }
  }
}

Dual-Phase Execution: Design vs. Production

Dust Apps separate iteration from production execution:


3. Deep Dive: The Core Blocks of a Custom Workflow

Building a resilient workflow requires combining specialized blocks. Here is how software engineers configure each node.

The Input Block (input)

The input block is the entry gateway. It defines the contract expected by the pipeline.

The Data Source Extractor Block (data_source)

Dust features managed semantic search over connected stores (Notion, Google Drive, GitHub, Slack, or custom API-upserted documents). The data_source block queries these stores using vector embeddings.

block_type: data_source
name: RETRIEVE_CLAUSES
specification:
  query: "{{INPUT.contract_query}}"
  full_text: false
configuration:
  top_k: 8
  data_sources:
    - workspace_id: "w_enterprise_01"
      data_source_id: "legal_repository"
  filter:
    tags:
      in: ["enterprise_agreements", "v2025"]
      not: ["archived"]
    timestamp:
      gt: 1735689600000

Map and Reduce Blocks (map / reduce)

Standard RAG architectures often collapse multiple retrieved documents into a single massive context window, leading to "lost-in-the-middle" extraction degradation. Dust Apps solve this with parallel map/reduce blocks.

  1. map block:
    • from: References the name of an upstream block that outputs an array (e.g., RETRIEVE_CLAUSES).
    • Forks the execution stream across every element in that array in parallel.
  2. Intermediate blocks: Each item is processed independently by chained Model and Code blocks.
  3. reduce block:
    • Takes the exact same name as its counterpart map block.
    • Collects all outputs produced by intermediate blocks into a single consolidated array, making it available under env.state.<INTERMEDIATE_BLOCK_NAME> for downstream aggregation.

The Model Block (chat / model)

The Model block handles large language model execution across providers (OpenAI, Anthropic, Mistral, Google).

block_type: chat
name: EXTRACT_METRICS
specification:
  instructions: |
    You are a strict data extraction engine.
    Extract the SLA commitment and financial penalty percentages from the provided text.
    Return ONLY a raw JSON object matching:
    {"sla_percentage": number, "penalty_percentage": number, "clause_reference": string}
  messages_code: |
    function _fun(env) {
      return [
        {
          role: "user",
          content: "Context: " + env.state.RETRIEVE_CLAUSES[env.map.iteration].text
        }
      ];
    }
  temperature: 0.0
  max_tokens: 512
configuration:
  provider_id: "anthropic"
  model_id: "claude-3-5-sonnet-20241022"
  use_cache: true

The Code Block (code)

The Code block is the deterministic backbone of Dust Apps. Running within a sandboxed JavaScript runtime (V8), it enforces contracts, validates structures, and eliminates LLM hallucinations.

// Function signature required by Dust Code blocks
function _fun(env) {
  const rawOutput = env.state.EXTRACT_METRICS.text.trim();
  
  // Strip Markdown code fences if the LLM leaked them
  const sanitized = rawOutput
    .replace(/^```json\s*/i, "")
    .replace(/^```\s*/i, "")
    .replace(/\s*```$/, "");
  
  let parsed;
  try {
    parsed = JSON.parse(sanitized);
  } catch (err) {
    return {
      status: "error",
      error: "Malformed JSON emitted by model",
      raw: rawOutput
    };
  }

  // Enforce schema validation and boundary checks
  const sla = Number(parsed.sla_percentage);
  const penalty = Number(parsed.penalty_percentage);
  
  if (isNaN(sla) || sla < 0 || sla > 100) {
    return { status: "validation_failed", reason: "Invalid SLA percentage" };
  }

  return {
    status: "valid",
    data: {
      sla_percentage: sla,
      penalty_percentage: penalty,
      reference: parsed.clause_reference || "N/A",
      extracted_at: new Date().toISOString()
    }
  };
}

365Finds strongly advises keeping Code blocks single-purposed: parse, sanitize, validate, or filter. Never overload a single Code block with extraction and complex aggregation simultaneously.


4. End-to-End Implementation: The Multi-Source Extraction Pipeline

Let us look at a canonical enterprise architecture: extracting compliance clauses from dozens of vendor contracts, verifying the values, and returning a normalized JSON report.

+--------------------------------------------------------+
| 1. INPUT Block: { "vendor_name": "Acme", "query": "..."} |
+--------------------------------------------------------+
                           |
                           v
+--------------------------------------------------------+
| 2. DATA_SOURCE: Semantic Search against Vendor Vault   |
|    Output: Array of Documents [DocA, DocB, DocC]       |
+--------------------------------------------------------+
                           |
                           v
+--------------------------------------------------------+
| 3. MAP: MAP_DOCS (forks on env.state.DATA_SOURCE)      |
|    |                                                   |
|    v                                                   |
|    4. MODEL: EXTRACT_FIELDS (JSON extraction)          |
|    |                                                   |
|    v                                                   |
|    5. CODE: VALIDATE_FIELDS (Sanitize, JSON.parse)     |
|    |                                                   |
+--------------------------------------------------------+
                           |
                           v
+--------------------------------------------------------+
| 6. REDUCE: MAP_DOCS (Aggregates array of validated data)|
+--------------------------------------------------------+
                           |
                           v
+--------------------------------------------------------+
| 7. CODE: CONSOLIDATE (Deduplicate & build final report)|
+--------------------------------------------------------+
  1. INPUT: Ingests { vendor_id: "acme_corp", requirement: "data residency" }.
  2. SEARCH_VAULT: Queries the contract data source with filter tags: { in: [env.input.input.vendor_id] }.
  3. MAP_DOCS: Forks an iteration for each retrieved contract document.
  4. EXTRACT_FIELDS: Calls gpt-4o or claude-3-5-sonnet with temperature: 0.0 to pull residency country, compliance dates, and liability caps.
  5. VALIDATE_FIELDS: JavaScript sandbox strips Markdown backticks, parses the JSON payload, checks that residency_country matches ISO 3166-1 alpha-2 format, and flags violations.
  6. REDUCE_DOCS: Aggregates the parallel validated outputs.
  7. CONSOLIDATE: Merges duplicate citations, resolves conflicting dates, and emits a single verified payload.

5. Production Delivery: API Microservices & Assistant Tool Binding

Once a Dust App is validated in the Studio, software engineers deploy it through two integration patterns: API execution and custom Assistant tools.

Pattern 1: Invocation via Dust REST API

Engineering teams can call the Dust App directly from their internal microservices (Python, Go, Node.js) via the execution API:

POST /api/v1/w/{wId}/spaces/{spaceId}/apps/{aId}/runs
Host: dust.tt
Authorization: Bearer YOUR_DUST_API_KEY
Content-Type: application/json

{
  "specification_hash": "8c0a4e6d2f3b1a9c8e7d6f5a4b3c2d1e",
  "config": {
    "EXTRACT_FIELDS": {
      "provider_id": "anthropic",
      "model_id": "claude-3-5-sonnet-20241022",
      "use_cache": true
    }
  },
  "inputs": [
    {
      "vendor_id": "acme_corp",
      "contract_query": "data residency and sovereign hosting requirements"
    }
  ],
  "blocking": true,
  "block_filter": ["CONSOLIDATE"]
}

Why specification_hash is Non-Negotiable

At 365Finds, our primary rule for enterprise integrations is immutability. The specification_hash parameter represents a cryptographic SHA hash of the exact block configuration, prompt strings, and JavaScript functions of the app.

When your production backend passes specification_hash:

Pattern 2: Binding Dust Apps as Custom Assistant Tools

If business users interact via natural language, engineers can expose the completed Dust App as a deterministic tool within a custom Dust Agent (Assistant):

  1. Navigate to Agent Builder in Dust.
  2. Under Tools, select Run App (or select the workspace-published App).
  3. The Agent's planner exposes the Dust App's input variables to the LLM function-calling mechanism.
  4. When a user asks: "Check Acme Corp's compliance status," the Assistant formulates the structured JSON arguments, triggers the App run, waits for the sandboxed pipeline to return verified data, and summarizes the result.

This hybrid model gives organizations the best of both worlds: natural language usability on the frontend, backed by strict code verification on the backend.


6. 365Finds Assessment and Engineering Recommendations

DimensionStandard Conversational AgentCustom Dust App Pipeline
Execution ModelUnpredictable recursive agent loopExplicit DAG with sequential and parallel blocks
Data ValidationPrompt-based ("Please return valid JSON")Sandboxed V8 JavaScript execution with JSON.parse & schema checks
Batch ProcessingSequential, slow, token-heavyNative parallel map/reduce over arrays
Version ControlFragile system prompt textCryptographic specification_hash locking
Production FitAd-hoc internal inquiriesBackend microservices, CI/CD pipelines, SLA contracts

Our Verdict and Practical Rules

365Finds views Dust Apps as an underappreciated architectural pattern that solves the fundamental dilemma of enterprise LLM engineering: bridging fuzzy language and rigid database contracts.

When building workflows in Dust, adhere to four foundational practices:

  1. Always lock specification_hash in production: Never call the run endpoint without pinning the hash. Unpinned calls track the mutable "draft" state of the app, creating catastrophic regressions when prompts are touched in the UI.
  2. Never allow raw LLM output into an API response: Insert a code block immediately after every model block to catch unescaped characters, strip Markdown fences, and validate types.
  3. Leverage map/reduce to preserve context quality: Do not dump 10 long documents into a single model context. Map individual extractions across chunks, then reduce and summarize. This avoids attention decay and reduces hallucination rates.
  4. Mind the deprecation landscape: Dust has focused recent developments on modern Agent frameworks and Model Context Protocol (MCP) integrations, categorizing older visual Dust Apps under legacy maintenance for pre-October 2025 apps. If your workspace operates existing Dust Apps, preserve their stability via API version pinning; if designing greenfield architectures, implement these exact same block principles (explicit code sanitization, deterministic RAG extraction, and tool binding) via the modern Developer Platform and custom MCP tools.

Deterministic AI is not an oxymoron; it simply requires replacing conversational optimism with disciplined block orchestration.


References