Files
dify-docs/en/guides/workflow/node/code.mdx
2025-10-11 11:43:18 +08:00

197 lines
7.6 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "Code"
---
## Introduction
The Code node allows you to embed custom Python or JavaScript scripts into your workflow to manipulate variables in ways that built-in nodes cannot achieve. It can simplify your workflow and is suitable for scenarios such as arithmetic operations, JSON transformations, text processing, and more.
To use variables from other nodes in a Code node, you must select them in the `Input Variables` field and then reference them in your code.
<img
src="https://assets-docs.dify.ai/dify-enterprise-mintlify/en/guides/workflow/node/9969aa1bc1912aebe366f5d8f5dde296.png"
width="400"
/>
## What a Code Node Can Do
With the Code node, you can perform common operations such as structured data processing, mathematical calculations, and data concatenation.
### Structured Data Processing
In workflows, you often have to deal with unstructured data processing, such as parsing, extracting, and transforming JSON strings.
A typical example is data processing from an HTTP node: in common API return structures, data may be nested within multiple layers of JSON objects, and you need to extract certain fields. The Code node can help you perform these operations.
Here is a simple example that extracts the `data.name` field from a JSON string returned by an HTTP node:
```python
def main(http_response: str) -> dict:
import json
data = json.loads(http_response)
return {
# Note to declare 'result' in the output variables
'result': data['data']['name']
}
```
### Mathematical Calculations
When you need to perform complex mathematical calculations in a workflow, you can also use the Code node. For example, calculating a complex mathematical formula or performing some statistical analysis on data.
Here is a simple example that calculates the variance of an array:
```python
def main(x: list) -> dict:
return {
# Note to declare 'result' in the output variables
'result': sum([(i - sum(x) / len(x)) ** 2 for i in x]) / len(x)
}
```
### Data Concatenation
Sometimes you may need to concatenate multiple data sources, such as multiple knowledge retrievals, data searches, API calls, etc. The Code node can help you integrate these data sources together.
Here is a simple example that merges data from two knowledge bases:
```python
def main(knowledge1: list, knowledge2: list) -> dict:
return {
# Note to declare 'result' in the output variables
'result': knowledge1 + knowledge2
}
```
## Local Deployment
If you are a local deployment user, you need to start a sandbox service to prevent the execution of malicious code.
This sanbox service requires Docker and you can start it directly using `docker-compose`:
```bash
docker-compose -f docker-compose.middleware.yaml up -d
```
<Note>
If your system has Docker Compose V2 installed, use `docker compose` instead of `docker-compose`. You can check the version with `$ docker compose version`.
For more information, see the [official Docker documentation](https://docs.docker.com/compose/#compose-v2-and-the-new-docker-compose-command).
</Note>
<Tip>
You can learn more about the sandbox service [here](https://github.com/langgenius/dify/tree/main/docker/docker-compose.middleware.yaml).
</Tip>
## Security Policies
Both Python and JavaScript execution environments are strictly isolated (sandboxed) to ensure security. This means that functions that consume large amounts of system resources or may pose security risks are prohibited, such as direct file system access, making network requests, or executing operating system-level commands. These limitations ensure the safe execution of the code while avoiding excessive consumption of system resources.
### Advanced Features
#### Retry on Failure
Certain node errors are transient and can often be resolved by rerunning the node. By enabling the error retry feature, the node will automatically attempt to rerun according to a predefined policy upon failure.
You can adjust the maximum number of retries and the interval between each retry to set the retry strategy.
- The maximum number of retries is 10
- The maximum retry interval is 5000 ms
![](https://assets-docs.dify.ai/2024/12/9fdd5525a91dc925b79b89272893becf.png)
#### Error Handling
When processing information, Code nodes may encounter code execution errors. You can follow these steps to configure error branches. This allows you to enable a contingency plan when an error occurs in the node, preventing the entire workflow from being interrupted.
1. Enable **Error Handling** for the Code node.
2. Select and configure an error handling strategy.
![Code Error Handling](https://assets-docs.dify.ai/2024/12/58f392734ce44b22cd8c160faf28cd14.png)
<Tip>
For more information about error handling approaches, see [Error Handling](/en/guides/workflow/error-handling/README).
</Tip>
### FAQ
**Why can't I save the code it in the Code node?**
Check if the code contains potentially dangerous behaviors. For example:
```python
def main() -> dict:
return {
"result": open("/etc/passwd").read(),
}
```
This code snippet has the following issues:
- **Unauthorized file access**: The code attempts to read the `/etc/passwd` file, which is a critical system file in Unix/Linux systems that stores user account information.
- **Sensitive information disclosure**: The `/etc/passwd` file contains important information about system users, such as usernames, user IDs, group IDs, home directory paths, etc. Direct access could lead to information leakage.
Dangerous code will be automatically blocked by Cloudflare WAF. You can check if it's been blocked by looking at the **Network** tab in your browser's **Web Developer Tools**.
![Cloudflare WAF](https://assets-docs.dify.ai/2024/12/ad4dc065c4c567c150ab7fa7bfd123a3.png)
## Code Fix
The **Code Fix** feature enables automatic code fix by leveraging the previous runs `current_code` and `error_message` variables.
When a Code node fails:
- The system captures the code and error message.
- These are passed into the prompt as context variables.
- A new version of the code is generated for review and retry.
### Fix Prompt
You can customize a prompt like:
```
Fix the following code based on this error message:
Code: {{current_code}}
Error: {{error_message}}`
```
<Info>
In the prompt editor, use the variable insertion menu (`/` or `{`) to insert variables.
</Info>
![Codefix PN](/images/codefix.PNG)
### Context Variables
To enable automatic code fix, reference the following context variables in your prompt:
- `current_code`: The code from the last run of this node.
- `error_message`: The error message from the last run if it failed; otherwise, empty.
These variables are automatically available when the Code node runs, allowing the model to use prior run information for iterative correction.
<Info>
- The `last_run` variable can be used to reference the input/output of the previous run.
- In addition to the variable above, you can reference the output variables of any preceding nodes as needed.
</Info>
### Version Management
Version management reduces manual copy-paste and allows iterative debugging directly within the workflow.
1. Each correction attempt is saved as a separate version (e.g., Version 1, Version 2).
2. You can switch between versions via the dropdown in the result display area.
---
{/*
Contributing Section
DO NOT edit this section!
It will be automatically generated by the script.
*/}
[Edit this page](https://github.com/langgenius/dify-docs/edit/main/en/guides/workflow/node/code.mdx) | [Report an issue](https://github.com/langgenius/dify-docs/issues/new?template=docs.yml)