mirror of
https://github.com/langgenius/dify-docs.git
synced 2026-03-26 13:18:34 +07:00
@@ -4,9 +4,9 @@ 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.
|
||||
With Code nodes, you can embed custom Python or JavaScript scripts into your workflow to manipulate variables in ways that are not possible with built-in nodes. Code nodes can simplify your workflow and are suitable for scenarios such as arithmetic operations, JSON transformation, and text processing.
|
||||
|
||||
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.
|
||||
To use variables from other nodes within a Code node, select them as Input Variables and then reference them in your code.
|
||||
|
||||
<img
|
||||
src="https://assets-docs.dify.ai/dify-enterprise-mintlify/en/guides/workflow/node/9969aa1bc1912aebe366f5d8f5dde296.png"
|
||||
@@ -15,15 +15,15 @@ To use variables from other nodes in a Code node, you must select them in the `I
|
||||
|
||||
## 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.
|
||||
The Code node allows you to perform 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.
|
||||
A typical example is handling data from an HTTP node. In common API response structures, data is often nested within multiple layers of a JSON object, and you may need to extract specific fields. The Code node can help you accomplish these tasks.
|
||||
|
||||
Here is a simple example that extracts the `data.name` field from a JSON string returned by an HTTP node:
|
||||
For example, the following code extracts the `data.name` field from a JSON string returned by an HTTP node:
|
||||
|
||||
```python
|
||||
def main(http_response: str) -> dict:
|
||||
@@ -37,9 +37,9 @@ def main(http_response: str) -> dict:
|
||||
|
||||
### 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.
|
||||
The Code node can also be used for complex mathematical computations within a workflow, such as evaluating intricate mathematical formulas or performing statistical analysis on data.
|
||||
|
||||
Here is a simple example that calculates the variance of an array:
|
||||
For example, you can use the following code to calculate the variance of an array:
|
||||
|
||||
```python
|
||||
def main(x: list) -> dict:
|
||||
@@ -51,9 +51,9 @@ def main(x: list) -> dict:
|
||||
|
||||
### 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.
|
||||
When you need to combine data from multiple sources (such as multiple knowledge base searches, data queries, or API calls), the Code node can help you merge them.
|
||||
|
||||
Here is a simple example that merges data from two knowledge bases:
|
||||
For example, the following code merges data from two knowledge bases:
|
||||
|
||||
```python
|
||||
def main(knowledge1: list, knowledge2: list) -> dict:
|
||||
@@ -65,35 +65,35 @@ def main(knowledge1: list, knowledge2: list) -> dict:
|
||||
|
||||
## Local Deployment
|
||||
|
||||
If you are a local deployment user, you need to start a sandbox service to prevent the execution of malicious code.
|
||||
If you are running an on-premises deployment, you must enable the Sandbox service to prevent the execution of malicious code.
|
||||
|
||||
This sandbox service requires Docker. You can start it directly using `docker-compose`:
|
||||
The Sandbox service is launched using Docker. You can start the service directly with `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`.
|
||||
If you have Docker Compose V2 installed, use `docker compose` instead of `docker-compose`. You can check your 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).
|
||||
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.
|
||||
Both Python and JavaScript execution environments are strictly isolated (sandboxed) to ensure security. This means you cannot use features that consume substantial system resources or could pose security risks, such as directly accessing the file system, making network requests, or executing operating system-level commands. These restrictions guarantee secure code execution while preventing 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.
|
||||
For certain exceptions that may occur in a node, a simple retry is often sufficient to resolve the issue. With **Retry on Failure** enabled, 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.
|
||||
You can adjust the maximum number of retries and the interval between each retry.
|
||||
|
||||
- The maximum number of retries is 10
|
||||
- The maximum retry interval is 5000 ms
|
||||
@@ -102,10 +102,10 @@ You can adjust the maximum number of retries and the interval between each retry
|
||||
|
||||
#### 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.
|
||||
When processing information, Code nodes may encounter code execution errors. You can follow these steps to configure error branches, enabling a contingency plan when the node fails and thus preventing the entire workflow from being interrupted.
|
||||
|
||||
1. Enable **Error Handling** for the Code node.
|
||||
2. Select and configure an error handling strategy.
|
||||
2. Select an error handling strategy and configure it.
|
||||
|
||||

|
||||
|
||||
@@ -115,9 +115,9 @@ For more information about error handling approaches, see [Error Handling](/en/g
|
||||
|
||||
### FAQ
|
||||
|
||||
**Why can't I save the code it in the Code node?**
|
||||
**Why can't I save the code in the Code node?**
|
||||
|
||||
Check if the code contains potentially dangerous behaviors. For example:
|
||||
Please check if your code contains any potentially harmful actions. For example:
|
||||
|
||||
```python
|
||||
def main() -> dict:
|
||||
@@ -126,18 +126,17 @@ def main() -> dict:
|
||||
}
|
||||
```
|
||||
|
||||
This code snippet has the following issues:
|
||||
This code 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**.
|
||||
|
||||
Harmful code will be automatically blocked by the Cloudflare WAF. You can check if the code has been blocked by inspecting the **Network** tab in your browser's **Developer Tools**.
|
||||

|
||||
|
||||
## Code Fix
|
||||
|
||||
The **Code Fix** feature enables automatic code fix by leveraging the previous run’s `current_code` and `error_message` variables.
|
||||
You can enable automatic code fixing by using the `current_code` and `error_message` variables from the last run.
|
||||
|
||||
When a Code node fails:
|
||||
|
||||
@@ -147,7 +146,7 @@ When a Code node fails:
|
||||
|
||||
### Fix Prompt
|
||||
|
||||
You can customize a prompt like:
|
||||
You can customize the fix prompt, for example:
|
||||
|
||||
```
|
||||
Fix the following code based on this error message:
|
||||
@@ -161,29 +160,28 @@ Error: {{error_message}}`
|
||||
In the prompt editor, use the variable insertion menu (`/` or `{`) to insert variables.
|
||||
</Info>
|
||||
|
||||

|
||||

|
||||
|
||||
### 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.
|
||||
- `error_message`: The error message if the last run failed; otherwise, it is empty.
|
||||
|
||||
These variables are automatically available when the Code node runs, allowing the model to use prior run information for iterative correction.
|
||||
These variables are automatically available when the Code node runs, allowing the LLM to use information from the previous run to fix the code.
|
||||
|
||||
<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.
|
||||
- In addition to the variable above, you can also 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.
|
||||
Version management reduces manual copy-pasting and allows you to debug and iterate on your code directly within the workflow.
|
||||
|
||||
1. Each fix attempt is saved as a separate version (e.g., Version 1, Version 2).
|
||||
2. You can switch between versions using the dropdown menu in the results display area.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ def main(http_response: str) -> dict:
|
||||
|
||||
当工作流中需要进行复杂的数学计算时(如计算复杂的数学公式或对数据进行统计分析),也可以使用代码节点。
|
||||
|
||||
例如,你可以通过以下代码计算一个数组的平方差:
|
||||
例如,你可以通过以下代码计算一个数组的方差:
|
||||
|
||||
```python
|
||||
def main(x: list) -> dict:
|
||||
|
||||
Reference in New Issue
Block a user