Lesson 14 / 25

Code Nodes

Python or JavaScript for exact logic.

A main function in, a dict out

A code node runs a short Python or JavaScript function in a sandbox: you declare input variables, write a main function that receives them, and return a dictionary whose keys become output variables. Use code for anything that must be exact: arithmetic, parsing JSON, date handling, formatting, filtering lists. Keep functions small, handle bad input, and test them locally first. Sandboxes restrict imports, network access and run time. Dify's node names, menus and options change between versions; check the current Dify documentation.

Deterministic steps around the model

Code nodes, parameter extraction and HTTP calls connect LLM steps to real data and systems.

Three ideas: code nodes, structured extraction, HTTP and tools.
Figure 5.1 — Code, extraction and HTTP.

A code-node function tested locally, run

I ran this with plain Python 3 (scikit-learn 1.9.1 where imported). It models or tests one piece of a Dify app locally; Dify itself was not running. The main function parses an order JSON string and returns subtotal 448.0, tax 80.64 at 18%, total 528.64 and an item count of 3, values an LLM should never be trusted to compute.

# A Dify code node runs a function named main that receives node variables and returns a dict.
import json

def main(raw_order: str, tax_rate: float) -> dict:
    order = json.loads(raw_order)
    subtotal = sum(item["qty"] * item["price"] for item in order["items"])
    return {
        "subtotal": round(subtotal, 2),
        "tax": round(subtotal * tax_rate, 2),
        "total": round(subtotal * (1 + tax_rate), 2),
        "item_count": sum(item["qty"] for item in order["items"]),
    }

# Local test before pasting the function into the node
print(main('{"items": [{"qty": 2, "price": 199.5}, {"qty": 1, "price": 49.0}]}', 0.18))

Output:

{'subtotal': 448.0, 'tax': 80.64, 'total': 528.64, 'item_count': 3}

Never let the LLM do arithmetic

Compute totals, taxes and dates in code nodes; models make silent numerical mistakes.

Quick check: What does a Dify code node's main function return?

  • Nothing; it only prints
  • A web page
  • A trained model
  • A dictionary whose keys become output variables
Answer

A dictionary whose keys become output variables — Returned keys feed downstream nodes.